From 8dbe7bd3cbea134c2a8073267c5664f4710c7323 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Tue, 10 Nov 2026 19:17:39 -0800 Subject: [PATCH 001/176] MCP: validate numeric transform steps before editing (#6488) --- crates/mcp/src/tests.rs | 40 ++++++++++++++++++++++++++++++++ crates/mcp/src/tools/dispatch.rs | 10 +++++++- 2 files changed, 49 insertions(+), 1 deletion(-) diff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rs index dba3ed9def..cd8cd35f6d 100644 --- a/crates/mcp/src/tests.rs +++ b/crates/mcp/src/tests.rs @@ -1921,3 +1921,43 @@ fn add_text_reports_overflow_and_takes_a_fit() { let point = made(&call(&mut s, 3, "add_text", json!({"text": "NEON DRIVE", "x": 0, "y": 300, "size": 60}))); assert!(point.get("overflow").is_none(), "{point}"); } + +#[test] +fn transform_rejects_nonnumeric_steps_before_editing() { + let inspect = |s: &mut Server, id| serde_json::from_str::(&text_of(&call(s, id, "doc_inspect", json!({})))).unwrap(); + let mut s = server(); + let first = id_of(&call(&mut s, 1, "draw_path", json!({"d": "M10 10 L30 10 L30 25 Z"}))); + let second = id_of(&call(&mut s, 2, "draw_path", json!({"d": "M40 40 L60 40 L60 55 Z"}))); + let before = inspect(&mut s, 3); + assert_eq!(before["selection"], json!([second])); + + let cases = [ + ("rotate", json!({"dx": 10, "rotate": "bad"})), + ("scale", json!({"dx": 10, "scale": "bad"})), + ("scaleX", json!({"dx": 10, "scaleX": "bad", "scaleY": 150})), + ("scaleY", json!({"dx": 10, "scaleX": 150, "scaleY": "bad"})), + ("shear", json!({"dx": 10, "shear": "bad"})), + ]; + for (index, (field, mut args)) in cases.into_iter().enumerate() { + args["ids"] = json!([first]); + let request_id = 4 + index as u64 * 2; + let rejected = call(&mut s, request_id, "transform", args); + assert_eq!(rejected["isError"], true, "{field}: {rejected}"); + assert!(text_of(&rejected).contains(field), "{field}: {rejected}"); + assert_eq!(inspect(&mut s, request_id + 1), before, "{field}"); + } + + let applied = call(&mut s, 14, "transform", json!({"ids": [first], "dx": 10, "rotate": null, "scale": 150, "scaleX": 125})); + assert_eq!(applied["isError"], false, "{applied}"); + let applied: Value = serde_json::from_str(&text_of(&applied)).unwrap(); + assert_eq!(applied["applied"], json!(["move", "scale"])); + let after = inspect(&mut s, 15); + assert_ne!(after, before); + assert_eq!(after["objects"], before["objects"]); + assert_eq!(after["selection"], json!([first])); + let bounds = &after["selectionBounds"]; + assert!((bounds["width"].as_f64().unwrap() - 25.0).abs() < 1e-6, "{bounds}"); + assert!((bounds["height"].as_f64().unwrap() - 22.5).abs() < 1e-6, "{bounds}"); + assert!(after["history"].as_array().unwrap().contains(&json!("Move"))); + assert!(after["history"].as_array().unwrap().contains(&json!("Scale"))); +} diff --git a/crates/mcp/src/tools/dispatch.rs b/crates/mcp/src/tools/dispatch.rs index b1c5af70bb..272ade4c9c 100644 --- a/crates/mcp/src/tools/dispatch.rs +++ b/crates/mcp/src/tools/dispatch.rs @@ -251,7 +251,15 @@ fn dispatch(b: &mut dyn Backend, name: &str, a: &Args) -> Result j(transform(b, a)?), + "transform" => { + // Validate all numeric steps before the handler changes selection or runs a step. + for field in ["rotate", "scale", "scaleX", "scaleY", "shear"] { + if a.get(field).is_some_and(|value| !value.is_null() && value.as_f64().is_none()) { + return Err(format!("`{field}` must be a number")); + } + } + j(transform(b, a)?) + } "create_graph" => { let mut p = Value::Object(a.clone()); if p.get("type").is_none() { From 98fcf6a497d5a12dedd4b705705b1af8c63b2a90 Mon Sep 17 00:00:00 2001 From: yoriswind Date: Tue, 10 Nov 2026 20:45:20 -0800 Subject: [PATCH 002/176] #6490: reject malformed move offsets before selection or copy --- crates/mcp/src/tests.rs | 13 ++++++ crates/mcp/src/tests/move_offsets.rs | 67 ++++++++++++++++++++++++++++ crates/mcp/src/tools/dispatch.rs | 2 +- 3 files changed, 81 insertions(+), 1 deletion(-) create mode 100644 crates/mcp/src/tests/move_offsets.rs diff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rs index cd8cd35f6d..a027f4e0f9 100644 --- a/crates/mcp/src/tests.rs +++ b/crates/mcp/src/tests.rs @@ -16,6 +16,7 @@ mod gradient; mod limits; mod links; mod liquify; +mod move_offsets; mod pen; mod persp; mod place; @@ -1960,4 +1961,16 @@ fn transform_rejects_nonnumeric_steps_before_editing() { assert!((bounds["height"].as_f64().unwrap() - 22.5).abs() < 1e-6, "{bounds}"); assert!(after["history"].as_array().unwrap().contains(&json!("Move"))); assert!(after["history"].as_array().unwrap().contains(&json!("Scale"))); + + let applied = call(&mut s, 16, "transform", json!({"ids": [second], "dx": 10, "rotate": 90, "origin": [0, 0]})); + assert_eq!(applied["isError"], false, "{applied}"); + let applied: Value = serde_json::from_str(&text_of(&applied)).unwrap(); + assert_eq!(applied["applied"], json!(["move", "rotate"])); + let after = inspect(&mut s, 17); + assert_eq!(after["selection"], json!([second])); + let bounds = &after["selectionBounds"]; + for (field, expected) in [("x", 40.0), ("y", -70.0), ("width", 15.0), ("height", 20.0)] { + assert!((bounds[field].as_f64().unwrap() - expected).abs() < 1e-6, "{field}: {bounds}"); + } + assert!(after["history"].as_array().unwrap().ends_with(&[json!("Move"), json!("Rotate")])); } diff --git a/crates/mcp/src/tests/move_offsets.rs b/crates/mcp/src/tests/move_offsets.rs new file mode 100644 index 0000000000..77fb8860a2 --- /dev/null +++ b/crates/mcp/src/tests/move_offsets.rs @@ -0,0 +1,67 @@ +use serde_json::{Value, json}; + +use super::{Server, call, id_of, server, text_of}; + +fn inspect(s: &mut Server, id: u64) -> Value { + serde_json::from_str(&text_of(&call(s, id, "doc_inspect", json!({})))).unwrap() +} + +fn path(s: &mut Server, id: u64, d: &str) -> u64 { + id_of(&call(s, id, "draw_path", json!({"d": d}))) +} + +fn child(doc: &Value, id: u64) -> Value { + doc["layers"][0]["children"].as_array().unwrap().iter().find(|node| node["id"] == id).unwrap().clone() +} + +#[test] +fn transform_rejects_malformed_move_offsets_before_selection_or_copy() { + let mut s = server(); + let first = path(&mut s, 1, "M40 40 L60 40 L60 60 L40 60 Z"); + let second = path(&mut s, 2, "M100 100 L130 100 L130 140 L100 140 Z"); + let before = inspect(&mut s, 3); + assert_eq!(before["selection"], json!([second])); + + let cases = [("dx", json!({"ids": [first], "dx": "bad", "copy": true})), ("dy", json!({"ids": [first], "dx": 10, "dy": "bad", "copy": true}))]; + for (index, (field, args)) in cases.into_iter().enumerate() { + let request_id = 4 + index as u64 * 2; + let result = call(&mut s, request_id, "transform", args); + assert_eq!(result["isError"], true, "{field}: {result}"); + assert!(text_of(&result).contains(field), "{field}: {result}"); + assert_eq!(inspect(&mut s, request_id + 1), before, "{field}"); + } + + // The recorded request omits dx and must still move a copy down by 10 points. + let result = call(&mut s, 8, "transform", json!({"ids": [first], "dy": 10, "copy": true})); + assert_eq!(result["isError"], false, "{result}"); + let reply: Value = serde_json::from_str(&text_of(&result)).unwrap(); + assert_eq!(reply["applied"], json!(["move"])); + let after = inspect(&mut s, 9); + let copied = after["selection"][0].as_u64().unwrap(); + assert_ne!(copied, first); + assert_ne!(copied, second); + let original_before = child(&before, first); + let original_after = child(&after, first); + let second_after = child(&after, second); + let copy_after = child(&after, copied); + assert_eq!(original_after["bounds"], original_before["bounds"]); + assert_eq!(second_after["bounds"], child(&before, second)["bounds"]); + assert_eq!(copy_after["bounds"]["x"], original_before["bounds"]["x"]); + assert_eq!(copy_after["bounds"]["y"], original_before["bounds"]["y"].as_f64().unwrap() + 10.0); + assert_eq!(copy_after["bounds"]["width"], original_before["bounds"]["width"]); + assert_eq!(copy_after["bounds"]["height"], original_before["bounds"]["height"]); + let before_history = before["history"].as_array().unwrap(); + let after_history = after["history"].as_array().unwrap(); + assert_eq!(after_history.len(), before_history.len() + 1); + assert_eq!(after_history.last(), Some(&json!("Move"))); + + // Null keeps the engine's optional-number default while a negative numeric offset is applied. + let result = call(&mut s, 10, "transform", json!({"ids": [second], "dx": null, "dy": -7})); + assert_eq!(result["isError"], false, "{result}"); + let after_null = inspect(&mut s, 11); + let moved = child(&after_null, second); + let second_before = child(&before, second); + assert_eq!(moved["bounds"]["x"], second_before["bounds"]["x"]); + assert_eq!(moved["bounds"]["y"], second_before["bounds"]["y"].as_f64().unwrap() - 7.0); + assert_eq!(after_null["history"].as_array().unwrap().last(), Some(&json!("Move"))); +} diff --git a/crates/mcp/src/tools/dispatch.rs b/crates/mcp/src/tools/dispatch.rs index 272ade4c9c..65bcc30453 100644 --- a/crates/mcp/src/tools/dispatch.rs +++ b/crates/mcp/src/tools/dispatch.rs @@ -253,7 +253,7 @@ fn dispatch(b: &mut dyn Backend, name: &str, a: &Args) -> Result { // Validate all numeric steps before the handler changes selection or runs a step. - for field in ["rotate", "scale", "scaleX", "scaleY", "shear"] { + for field in ["dx", "dy", "rotate", "scale", "scaleX", "scaleY", "shear"] { if a.get(field).is_some_and(|value| !value.is_null() && value.as_f64().is_none()) { return Err(format!("`{field}` must be a number")); } From e02101f9259084be19d3a917320bf667d9a287ca Mon Sep 17 00:00:00 2001 From: yoriswind Date: Wed, 11 Nov 2026 14:54:30 -0800 Subject: [PATCH 003/176] Fix #6625: select path interiors from enabled fill rows --- crates/doc/src/appearance.rs | 5 + crates/doc/src/hit.rs | 8 +- crates/engine/tests/path_fill_hits.rs | 145 ++++++++++++++++++++++++++ docs/gaps.md | 5 + docs/roadmap.md | 5 +- docs/target-app-parity.md | 9 +- docs/ui-parity.md | 4 + 7 files changed, 174 insertions(+), 7 deletions(-) create mode 100644 crates/engine/tests/path_fill_hits.rs diff --git a/crates/doc/src/appearance.rs b/crates/doc/src/appearance.rs index 2e19ad44a3..06a4f77525 100644 --- a/crates/doc/src/appearance.rs +++ b/crates/doc/src/appearance.rs @@ -143,6 +143,11 @@ impl Appearance { pub fn fill_paint(&self) -> Paint { self.fill().map(|f| f.paint.clone()).unwrap_or(Paint::None) } + /// Whether any visible fill has non-None paint. Unlike [`Self::fill`], this + /// includes lower fills in the stack; zero opacity still counts for selecting its geometry. + pub fn has_visible_fill(&self) -> bool { + self.items.iter().any(|item| matches!(item, AppearanceItem::Fill(fill) if fill.visible && !fill.paint.is_none())) + } pub fn stroke_paint(&self) -> Paint { self.stroke().map(|s| s.paint.clone()).unwrap_or(Paint::None) } diff --git a/crates/doc/src/hit.rs b/crates/doc/src/hit.rs index 94fbb5ff52..32fd5eb5ce 100644 --- a/crates/doc/src/hit.rs +++ b/crates/doc/src/hit.rs @@ -800,6 +800,7 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio LEAVES_TESTED.with(|c| c.set(c.get() + 1)); match &n.kind { NodeKind::Path { path, rule, .. } => { + let has_fill = n.appearance.has_visible_fill(); if opt.outline && let Some((hit, needs_full_check)) = near_path_body(path, p, opt.tol, 0.0) { @@ -812,7 +813,7 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio } let mut strokes = n.appearance.painted_strokes(); if !opt.outline - && n.appearance.fill().is_none_or(|f| f.paint.is_none()) + && !has_fill && let Some(s) = strokes.next() && strokes.next().is_none() && s.align == StrokeAlign::Center @@ -841,8 +842,7 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio if let Some(k) = hit_stroke(n, &bp, *rule, p, opt) { return Some(k); } - let filled = !n.appearance.fill_paint().is_none(); - if !opt.outline && !opt.path_only && filled && fill_contains(&bp, *rule, p) { + if !opt.outline && !opt.path_only && has_fill && fill_contains(&bp, *rule, p) { return Some(HitKind::Fill); } None @@ -863,7 +863,7 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio if vectorcraft_geom::hit::distance_to_outline(&near, p) <= opt.tol { return Some(HitKind::Outline); } - (!opt.outline && !opt.path_only && fill_contains(&near, *rule, p)).then_some(HitKind::Fill) + (!opt.outline && !opt.path_only && n.appearance.has_visible_fill() && fill_contains(&near, *rule, p)).then_some(HitKind::Fill) } // The type path lies within the bounds: they rule out the rest before it is measured. NodeKind::Text(t) if opt.type_path_only => { diff --git a/crates/engine/tests/path_fill_hits.rs b/crates/engine/tests/path_fill_hits.rs new file mode 100644 index 0000000000..652a82667e --- /dev/null +++ b/crates/engine/tests/path_fill_hits.rs @@ -0,0 +1,145 @@ +//! Path fill hit testing follows the visible paint stack while transparent paint remains selectable. +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::sync::Arc; + +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::hit::{HitKind, HitOptions, hit_test}; +use vectorcraft_doc::{Appearance, AppearanceItem, Document, FillLayer, Node, NodeKind, StrokeLayer}; +use vectorcraft_geom::{Affine, FillRule, Point, Rect, shapes}; +use vectorcraft_render::{RenderOptions, Renderer}; + +fn fill(paint: Paint) -> FillLayer { + FillLayer::new(paint) +} + +fn rectangle(fills: Vec, stroke: bool) -> Document { + let mut doc = Document::new(128.0, 128.0); + let layer = doc.layers[0].id; + let id = doc.alloc_id(); + let mut appearance = Appearance::default(); + appearance.items.extend(fills.into_iter().map(AppearanceItem::Fill)); + if stroke { + appearance.items.push(AppearanceItem::Stroke(StrokeLayer::new(Paint::solid(Color::BLACK), 2.0))); + } + let path = shapes::rectangle(Rect::new(20.0, 20.0, 100.0, 100.0)); + doc.insert(Some(layer), usize::MAX, Node::path(id, path, appearance)).unwrap(); + doc +} + +fn compound(fills: Vec) -> Document { + let mut doc = Document::new(128.0, 128.0); + let layer = doc.layers[0].id; + let outer_id = doc.alloc_id(); + let inner_id = doc.alloc_id(); + let compound_id = doc.alloc_id(); + let children = vec![ + Arc::new(Node::path(outer_id, shapes::rectangle(Rect::new(20.0, 20.0, 100.0, 100.0)), Appearance::default())), + Arc::new(Node::path(inner_id, shapes::rectangle(Rect::new(50.0, 40.0, 70.0, 80.0)), Appearance::default())), + ]; + let mut appearance = Appearance::default(); + appearance.items.extend(fills.into_iter().map(AppearanceItem::Fill)); + appearance.items.push(AppearanceItem::Stroke(StrokeLayer::new(Paint::solid(Color::BLACK), 2.0))); + let mut node = Node::new(compound_id, NodeKind::Compound { children, rule: FillRule::EvenOdd }); + node.appearance = appearance.into(); + doc.insert(Some(layer), usize::MAX, node).unwrap(); + doc +} + +#[test] +fn hit_uses_the_visible_fill_stack() { + let black = || fill(Paint::solid(Color::BLACK)); + + let mut hidden = black(); + hidden.visible = false; + let mut transparent = black(); + transparent.opacity = 0.0; + let mut hidden_lower = black(); + hidden_lower.visible = false; + + let cases = vec![ + ("visible black fill", rectangle(vec![black()], true)), + ("lower black fill under a top None fill", rectangle(vec![black(), fill(Paint::None)], true)), + ("lower black fill under a top None fill without stroke", rectangle(vec![black(), fill(Paint::None)], false)), + ("only hidden non-None fill", rectangle(vec![hidden], true)), + ("basic Fill None", rectangle(vec![fill(Paint::None)], true)), + ("hidden lower black and top None fills", rectangle(vec![hidden_lower, fill(Paint::None)], true)), + ("visible fill at zero opacity", rectangle(vec![transparent], true)), + ]; + + let mut observed = Vec::new(); + for (name, doc) in cases { + let image = Renderer::new().render( + &doc, + 128, + 128, + Affine::IDENTITY, + &RenderOptions { background: None, artboards: false, ..RenderOptions::default() }, + ); + let center_alpha = image.pixel(60, 60)[3]; + let edge_alpha = image.pixel(100, 60)[3]; + let center = hit_test(&doc, Point::new(60.0, 60.0), HitOptions::default()).map(|hit| hit.kind); + let edge = hit_test(&doc, Point::new(100.5, 60.0), HitOptions::default()).map(|hit| hit.kind); + let outline = hit_test(&doc, Point::new(60.0, 60.0), HitOptions { outline: true, ..HitOptions::default() }).map(|hit| hit.kind); + let path_only = hit_test(&doc, Point::new(60.0, 60.0), HitOptions { path_only: true, ..HitOptions::default() }).map(|hit| hit.kind); + observed.push((name, center_alpha, edge_alpha, center, edge, outline, path_only)); + } + + let expected = vec![ + ("visible black fill", 255, 255, Some(HitKind::Fill), Some(HitKind::Stroke), None, None), + ("lower black fill under a top None fill", 255, 255, Some(HitKind::Fill), Some(HitKind::Stroke), None, None), + ("lower black fill under a top None fill without stroke", 255, 0, Some(HitKind::Fill), Some(HitKind::Outline), None, None), + ("only hidden non-None fill", 0, 255, None, Some(HitKind::Stroke), None, None), + ("basic Fill None", 0, 255, None, Some(HitKind::Stroke), None, None), + ("hidden lower black and top None fills", 0, 255, None, Some(HitKind::Stroke), None, None), + ("visible fill at zero opacity", 0, 255, Some(HitKind::Fill), Some(HitKind::Stroke), None, None), + ]; + assert_eq!(observed, expected, "render and hit-test observations by fill-stack case"); +} + +#[test] +fn compound_hit_uses_visible_fill_stack() { + let black = || fill(Paint::solid(Color::BLACK)); + + let mut hidden = black(); + hidden.visible = false; + let mut transparent = black(); + transparent.opacity = 0.0; + + let cases = vec![ + ("visible black fill", compound(vec![black()])), + ("lower black fill under a top None fill", compound(vec![black(), fill(Paint::None)])), + ("only hidden non-None fill", compound(vec![hidden])), + ("basic Fill None", compound(vec![fill(Paint::None)])), + ("visible fill at zero opacity", compound(vec![transparent])), + ]; + + let mut observed = Vec::new(); + for (name, doc) in cases { + let image = Renderer::new().render( + &doc, + 128, + 128, + Affine::IDENTITY, + &RenderOptions { background: None, artboards: false, ..RenderOptions::default() }, + ); + let ring_alpha = image.pixel(30, 60)[3]; + let hole_alpha = image.pixel(60, 60)[3]; + let edge_alpha = image.pixel(100, 60)[3]; + let ring = hit_test(&doc, Point::new(30.0, 60.0), HitOptions::default()).map(|hit| hit.kind); + let hole = hit_test(&doc, Point::new(60.0, 60.0), HitOptions::default()).map(|hit| hit.kind); + let edge = hit_test(&doc, Point::new(100.5, 60.0), HitOptions::default()).map(|hit| hit.kind); + let outline = hit_test(&doc, Point::new(30.0, 60.0), HitOptions { outline: true, ..HitOptions::default() }).map(|hit| hit.kind); + let path_only = hit_test(&doc, Point::new(30.0, 60.0), HitOptions { path_only: true, ..HitOptions::default() }).map(|hit| hit.kind); + observed.push((name, ring_alpha, hole_alpha, edge_alpha, ring, hole, edge, outline, path_only)); + } + + let expected = vec![ + ("visible black fill", 255, 0, 255, Some(HitKind::Fill), None, Some(HitKind::Stroke), None, None), + ("lower black fill under a top None fill", 255, 0, 255, Some(HitKind::Fill), None, Some(HitKind::Stroke), None, None), + ("only hidden non-None fill", 0, 0, 255, None, None, Some(HitKind::Stroke), None, None), + ("basic Fill None", 0, 0, 255, None, None, Some(HitKind::Stroke), None, None), + ("visible fill at zero opacity", 0, 0, 255, Some(HitKind::Fill), None, Some(HitKind::Stroke), None, None), + ]; + assert_eq!(observed, expected, "render and hit-test observations by Compound fill-stack case"); +} diff --git a/docs/gaps.md b/docs/gaps.md index b722ace84c..6760392229 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,6 +1,8 @@ # Gaps > **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-11 · **Change:** minor (G5: built-in Energy Beams brush library; estimate 5–15 → 4–14 h; previously minor: G5: built-in Skill Icons symbol library; estimate 6–16 → 5–15 h; previously minor: ruler double-click adds a guide at the pointer, #5239; G5: built-in Status Effects graphic style library; estimate 7–17 → 6–16 h; MCP docs catch-up for UI Frames and Map Markers; previously minor: G5: built-in Inventory Icons symbol library; estimate 8–18 → 7–17 h; previously minor: G9: `.ai` save names a variable font instance's design-space setting, #6388; previously minor: G5: built-in Game Trails brush library; estimate 9–19 → 8–18 h; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: docs tidy-up, no content change: stray notes at the top moved into the revision table; scores and estimates unchanged; previously 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) +> +> Selection update (2026-11-11): path and compound-path interiors follow enabled non-None fill rows, including lower fills beneath a top None row (#6625). Hidden-only interiors miss; zero-opacity fills remain selectable. Scores and estimates unchanged. ## Feature submission evidence @@ -110,6 +112,8 @@ from G14 and the budget run of G15: **~170–270 h** one agent, ~50–80 h wall macOS cursor delivery (#2292) is narrowed to a native host adapter using the existing artwork and aligned 1×/2× representations. Headless tests cover visible fallbacks, preparation and ownership; native focus/menu/handback timing, mixed displays, Spotlight and full-screen Spaces remain open validation work (see [hardware parity](hardware-parity.md)). This does not close the interaction-fidelity gap or change its score/estimate. +- **Selection fill eligibility (#6625):** Path and compound-path interiors use any enabled non-None fill row (#6625). A lower visible fill remains selectable beneath a top None row in the same object; hidden-only and true-None interiors miss. Zero-opacity fills remain selectable. Original CPU-render and document-hit regressions in `crates/engine/tests/path_fill_hits.rs` cover seven Path and five Compound cases, including stroke edges, geometric outlines, Outline/path-only modes and compound holes. Scores and estimates unchanged. + - **Panel collapse controls (#5925, in part):** The small » in a floating tab-group header moves that group into the side icon rail, reusing the existing rail or creating one. An opened rail panel has the same control to fold its flyout back into the rail, including after a tab switch. Both controls preserve the tab group and its menu; other floating groups and full-width docked headers stay as they were. Pointer regressions in `crates/ui-egui/src/panel_docking/tests.rs` cover grouped tabs, reopening, separate groups, a missing rail, the menu and flyout closure after switching tabs; `native_tests.rs` covers the native-window click and removal of the empty palette. Scores and estimates unchanged. - **Done:** Distance Guides ([public page](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/use-distance-guides-for-accurate-placement.html)): with Smart Guides on and something selected, the Selection tool with Alt/Option held over another object shows the horizontal and vertical distances between them, and over an empty part of an artboard the selection's distances from its four edges, labelled in the General unit; Preferences › Smart Guides › Invoke Distance Guides turns them off. Hover only, as documented: not while moving or nudging. No entry closed; estimates unchanged. @@ -854,6 +858,7 @@ trap, and the defaults (0.25 pt, 100%, 40%) are VectorCraft's own, the pages giv | Date | Change | Summary | |---|---|---| +| 2026-11-11 | minor | #6625: path and compound-path interior hits follow enabled non-None fill rows, including lower fills beneath a top None row; hidden-only interiors miss; zero-opacity fills remain selectable. Scores and estimates unchanged. | | 2026-11-11 | minor | G5: built-in Energy Beams brush library (Laser Bolt, Plasma Arc, Charge Wave, Spark Trail); Missing trimmed; estimate 5–15 → 4–14 h; MCP Brush libraries list Energy Beams. | | 2026-11-11 | minor | G5: built-in Skill Icons symbol library (Attack, Defend, Heal, Buff, Ult); Missing trimmed; estimate 6–16 → 5–15 h; MCP Symbol libraries list Skill Icons. | | 2026-11-10 | minor | G6: MCP catalogue (#6460): headless lists `UI_COMMANDS` (`ui: true`), eight prompts, effect vs command ids, 33 tools, commands/reference; estimate unchanged. | diff --git a/docs/roadmap.md b/docs/roadmap.md index 1b55740614..47e3ced469 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -2,6 +2,8 @@ > **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-10 · **Change:** minor (M10/G5: Energy Beams brush library; MCP docs list Energy Beams; previously minor: M10/G5: Skill Icons symbol library; MCP docs list Skill Icons; previously minor: M10/G5: Status Effects graphic style library; MCP docs catch-up for symbol libraries; previously minor: M10/G5: Inventory Icons built-in symbol library; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously 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) > +> Selection update (2026-11-11): path and compound-path interiors follow enabled non-None fill rows, including lower fills beneath a top None row (#6625). Hidden-only interiors miss; zero-opacity fills remain selectable. Scores and estimates unchanged. +> > Vector Halftone preview update (2026-11-10): temporary dot selection marks are hidden, and the bounding box stays available (#6369). > > **Flyout update:** 2026-11-06 — resizable icon-strip flyouts and bottom-aligned panel footers (#5713); scores and estimates unchanged. @@ -48,6 +50,7 @@ M7 type: Touch Type moves a right-to-left character along its line and up from i | Date | Change | Summary | |---|---|---| +| 2026-11-11 | minor | #6625: path and compound-path interior hits follow enabled non-None fill rows, including lower fills beneath a top None row; hidden-only interiors miss; zero-opacity fills remain selectable. 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. | @@ -140,7 +143,7 @@ native wording review, layout checks and a web Devanagari font remain. [Notes](l | # | Milestone | Status | Est. remaining, one agent (h) | |---|---|---|---| | M0 | Skeleton + vertical slice | ✅ done | — | -| M1 | Selection, transform, layers, MCP (common command tools, strict keys, session resources and version-aware result hints) | ✅ mostly done (document-tab artwork drag with lossless resource transfer and one target Undo; malformed MCP app replies discard the connection without replay, #1761; bounded control socket waits and connection-slot recovery, #1726; bounded synthetic control input, #1709; no-op anchor Align keeps Undo, Redo and saved state (#1180 follow-up); transform reference point snaps to anchors/centres; rotated objects keep a rotated bounding box and their angle; Free Transform, Scale and Reflect along a rotated box pending; the Transform fields take one Tab each, the W/H link after them) | 4–6 | +| M1 | Selection, transform, layers, MCP (common command tools, strict keys, session resources and version-aware result hints) | ✅ mostly done (path and compound-path interior selection follows enabled fill rows (#6625); document-tab artwork drag with lossless resource transfer and one target Undo; malformed MCP app replies discard the connection without replay, #1761; bounded control socket waits and connection-slot recovery, #1726; bounded synthetic control input, #1709; no-op anchor Align keeps Undo, Redo and saved state (#1180 follow-up); transform reference point snaps to anchors/centres; rotated objects keep a rotated bounding box and their angle; Free Transform, Scale and Reflect along a rotated box pending; the Transform fields take one Tab each, the W/H link after them) | 4–6 | | M2 | Drawing tools + smart guides | ✅ mostly done (#3380 deletion creates independent selected path pieces and keeps bounds-fitted gradients in place; endpoint highlighting remains open; Polygon/Star exact-size count persistence, with repeated-drag, tool-switch and Cancel regression coverage; Curvature point markers without direction handles (#1236, in part); Direct Selection segment click/Delete preserves neighboring edges, #1278; Flare, Reshape, Live Corners widget dragging and per-corner radii and kinds landed, on any path's corners; Shaper rough-shape recognition and orientation steps, the remaining Pen modifier nuances; Shaper Groups with editable sources and separate fill/stroke edits landed; custom ruler origin with drag preview, active-artboard reset, relative X/Y fields and native round-trip (#1212); construction widget/refinements pending); a shape just drawn moves by its centre point and turns from the zone outside a corner with its tool still active (#5477); Tangent and straight-segment perpendicular snapping use saved Smart Guides Geometric Guides preferences and Control bar quick access (#2537), including the existing Snap to Glyph and Alignment Guides toggles (#6164); no View submenu; Copy and Cut with the Pen or Curvature tool take the anchors a Cmd/Ctrl-lent Direct Selection picked (#6123) | 12–18 | | 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; finite-arithmetic follow-up regressions and full CI passed ([Validation evidence](target-app-parity.md#evidence-what-ships-today-by-area))), 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; Recolor model selection is available through the engine and MCP only (#2520); the dialog retains its existing controls | 4–8 | | M4 | Files (native, SVG, PDF, raster, Export for Screens, clipboard interop) | PDF authored ActualText preserved once in editable import (#6165; first-glyph line/style, bounded input; estimates unchanged); 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. `.ai`/EPS type from the text document keeps its paragraphs' tab stops (#6147); `.ai`/EPS type from the text document keeps auto leading per line, its 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 (#6137); ✅ done (M4.14–M4.98 on 2026-10-05): Save As/Save a Copy/Revert/templates, Data Recovery and background save, SVG import and export fidelity (units, text, symbols, filters, SVGZ, Preserve Editing, SVG Options), shared guarded PDF writer and windowed reader ([pdf-backend.md](pdf-backend.md)), PDF import (colours, layers, masks, editable text, security) and export (presets, marks, bleed, ICC and output intent, raster effects, subset fonts, PDF/X-1a, X-3 and X-4, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3), Place and Links, Package, EPS and DXF in and out (EPS legacy mesh corners, vector opacity masks and raster page comparison verified; closed SPLINE flags round-trip and circular paths export as native CIRCLE/ARC, #1299), EMF/WMF, TIFF/BMP/Targa/PSD/GIF/PNG-8 export, Print and print presets, slices, Save for Web, TIFF in Export for Screens and Asset Export, clipboard flavours, File Info; AF.1–AF.4 add Affinity import (native layers, artboards, vectors, text and images from Affinity 1–3 files; the embedded preview only as a warned fallback; AF.4 expands current `.af` fixtures and every-board round-trip validation); EPS Save and Save As keep an opened EPS as EPS with its page frame and complete editable VectorCraft document (2026-10-26; G9 import fidelity unchanged). Left: DWG (use DXF), PSD placement as layers, overprint read back from PDF, Affinity export, polish; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts | 3–6 (existing scope; Affinity export unestimated) | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index b4c949f742..cb7926f14c 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2,6 +2,8 @@ > **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-11 · **Change:** minor (G5: Energy Beams brush library; bundled content ~44% → ~46%; previously minor: G5: Skill Icons symbol library; bundled content ~42% → ~44%; previously minor: `.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art (#6570; scores and estimates unchanged); previously minor: ruler double-click adds a guide at the pointer, #5239; G5: Status Effects graphic style library; bundled content ~40% → ~42%; MCP symbol libraries list UI Frames and Map Markers; previously minor: G5: Inventory Icons built-in symbol library; bundled content ~38% → ~40%; previously minor: `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke (#3179; scores and estimates unchanged); previously minor: `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid where VectorCraft's warp doesn't draw as their drawn art (#3179; scores and estimates unchanged); G5: Game Trails brush library; bundled content ~36% → ~38%; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page (#3179; scores and estimates unchanged); G5: Game HUD graphic style library; bundled content ~34% → ~36%; previously minor: Line Arrow arrowhead (#5421; scores and estimates unchanged); G5: Map Markers built-in symbol library; bundled content ~32% → ~34%; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Canvas: a 3D effect changed on type or a group redraws where its solid was; Fit to Artwork Bounds and per-artboard SVG export build each solid once for all artboards; previously minor: Effect Gallery: a thumbnail for each filter and a preview area inside the dialog, on an original drawing; Raster effects 52% → 55%, hours 1–2 → none; headline numbers unchanged; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: UI Frames built-in symbol library with default 9-slice; bundled content ~32%; previously minor: G5: dynamic symbol part on-canvas opacity/blend/gradient/pattern; strokes remaining no longer lists Overlap/auto corners; symbols ~88%; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: harakat paint fallback clarified; previously minor: current Guides feature-area rows consolidated using existing ruler evidence; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap and Pattern brush auto corners removed from strokes remaining; symbols remaining lists dynamic on-canvas beyond solid and guides outside the art; previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; `.ai` and EPS import: older Art brush objects read; numeric fields step on wheel hover without taking keyboard focus, and a panel wheel turn cannot seed a canvas zoom glide, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; the canvas keeps selection outlines and anchors between frames; Indian-language hyphenation review and license allowlist, #4947; Stroke gradients: an arrowhead aligned to the tip is painted to the corners of its base, #5964; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) > +> Selection update (2026-11-11): path and compound-path interiors follow enabled non-None fill rows, including lower fills beneath a top None row (#6625). Hidden-only interiors miss; zero-opacity fills remain selectable. Scores and estimates unchanged. +> > Vector Halftone preview update (2026-11-10): temporary dot selection marks are hidden, and the bounding box stays available (#6369). > > **Flyout update:** 2026-11-06 — resizable icon-strip flyouts and bottom-aligned panel footers (#5713); scores and estimates unchanged. @@ -214,7 +216,7 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | Area | Weight | Done | Main gaps | One agent (h) | Kind | |---|---:|---:|---|---:|---| -| Selection, transform & align tools | 6 | 85% | Direct Selection segment click/Delete corrected (#1278); deletion splits an ordinary contour into selected sibling objects with bounds-fitted gradients kept in place (#3380, deletion only; `crates/engine/tests/it/delete_path_pieces.rs`); open-path anchor Delete keeps gaps; Select › Start Global Edit finds the paths, compound paths and symbol instances of the selected object's shape (Appearance, Size and artboard options) and gives an edit of one to all of them in proportion, as one undo step (#3521), and on a group the groups like it, an edit inside one reaching the same object in the others (#4939), and a Shift-click on a highlighted match leaves it out; the Align panel menu's Align to Glyph Bounds › Point Text and Area Text measure type by its glyphs' ink for Align and Distribute (#4231); remaining: Free Transform/Scale/Reflect along a rotated box, Global Edit of rotated copies, transform nuances (no-op anchor Align history regression-tested, #1180 follow-up) | 4–6 | estimated; Global Edit regression-tested (`crates/engine/src/tests/globaledit.rs`; Quick Action, menu label and Escape in `panels::properties::tests::start_global_edit_quick_action_and_escape`) | +| Selection, transform & align tools | 6 | 85% | Direct Selection segment click/Delete corrected (#1278); deletion splits an ordinary contour into selected sibling objects with bounds-fitted gradients kept in place (#3380, deletion only; `crates/engine/tests/it/delete_path_pieces.rs`); open-path anchor Delete keeps gaps; Select › Start Global Edit finds the paths, compound paths and symbol instances of the selected object's shape (Appearance, Size and artboard options) and gives an edit of one to all of them in proportion, as one undo step (#3521), and on a group the groups like it, an edit inside one reaching the same object in the others (#4939), and a Shift-click on a highlighted match leaves it out; the Align panel menu's Align to Glyph Bounds › Point Text and Area Text measure type by its glyphs' ink for Align and Distribute (#4231); remaining: Free Transform/Scale/Reflect along a rotated box, Global Edit of rotated copies, transform nuances (no-op anchor Align history regression-tested, #1180 follow-up) | 4–6 | estimated; fill-stack selection regression-tested (`crates/engine/tests/path_fill_hits.rs`, #6625); Global Edit regression-tested (`crates/engine/src/tests/globaledit.rs`; Quick Action, menu label and Escape in `panels::properties::tests::start_global_edit_quick_action_and_escape`) | | Drawing tools (Pen, Curvature, Pencil, shapes, Shaper) | 7 | 85% | Shaper construction widget, Pencil/Pen nuances, Blob Brush options, Touch Type, Dimension tool; see [ui-parity.md](ui-parity.md) | 8–13 | estimated; Curvature point display regression-tested (#1236, in part); Polygon/Star exact-size count persistence regression-covered; Live Corners' Relative rounding done (#3091), score unchanged; Copy and Cut with the Pen or Curvature tool take the anchors a Cmd/Ctrl-lent Direct Selection picked (#6123), score and hours unchanged | | Path operations, Pathfinder, Shape Builder, Live Paint | 5 | 80% | Shape Builder on the reporter's file (#937: art past 4,096 segments is cut by lines again; unconfirmed on the file itself); gap detection shares Live Paint’s finder, with a 72 pt custom cap and the existing options; Live Paint Gap Options | 4–8 | estimated; 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 (lowered from 86%: open issues); compound attributes regression-tested (#1197); single-result source names survive SVG export/import (#1293), with [SVG ID semantics](https://www.w3.org/TR/SVG2/struct.html#IDAttribute) and original-shape tests; Simplify component selection and preview regression-tested (#1272); Simplify of a Direct Selection part of a path regression-tested (`tests/simplify_part.rs`); Divide open-cutting-path geometry and appearance regression-tested (#1307); the Shape Builder's edge-source grid is bounded in memory and files a segment once per cell (`planar.rs` test `rect_index_holds_a_bounded_number_of_references`); live compound shapes (Make, Alt-click, member Shape Modes, Release, Expand, saved and exported) regression-tested (#4522) | | Colour, swatches, gradients, patterns, mesh, recolor | 7 | 92% | 30.0's gradient additions are done (dither, perceptual blending, presets); freeform gradients in SVG/PDF, mixed spot/process gradients in SVG, PDF gradients mixing a spot color with RGB or Lab stops, and dithered spot gradient fills and Perceptual spot gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve, which PDF export writes as images in process colors | 4–7 | estimated; Recolor model selection is available through the engine and MCP (#2520), and the dialog's color sliders (HSB, RGB, CMYK, Lab, Tint for a spot color) edit the selected row's new color in its mode, and the Edit tab's Global Adjust sliders (Saturation, Brightness, Temperature, Luminosity, -100% to 100%) change every recolored color at once (lowered from 96%: target moved); unpainted zero-width stroke restoration fixed (#1253), score and hours unchanged; Eyedropper source reads regression-tested (#1251); screen-bounded Recolor Edit chip list (#3416), score and hours unchanged | @@ -551,6 +553,8 @@ since 2026-10-01. ## Evidence: what ships today, by area +**Selection fill eligibility (#6625):** Path and compound-path interiors use any enabled non-None fill row (#6625). A lower visible fill remains selectable beneath a top None row in the same object; hidden-only and true-None interiors miss. Zero-opacity fills remain selectable. Original CPU-render and document-hit regressions in `crates/engine/tests/path_fill_hits.rs` cover seven Path and five Compound cases, including stroke edges, geometric outlines, Outline/path-only modes and compound holes. Scores and estimates unchanged. + - **PDF authored replacement text (#6165):** `crates/pdf/src/tests/actual_text.rs` covers replacement once with suffix placement, PDF text-string decoding, empty and nested owners, sibling spans, page reset, multiple text-show operations, style/line changes, fill-and-stroke, reader windows and bounded input. Authored logical-order stretches are protected while adjacent ordinary text still undergoes reconstruction. The replacement takes its first placed glyph's style and line; its characters are not redistributed over later lines/styles. Exact mixed-direction paragraph layout is not claimed. No export changes; scores and hours stay at 75% / 10–20 h. @@ -1981,6 +1985,7 @@ Edit › Copy and Cut put the selected ruler guides on the clipboard, with the s | Date | Change | Summary | |---|---|---| +| 2026-11-11 | minor | #6625: path and compound-path interior hits follow enabled non-None fill rows, including lower fills beneath a top None row; hidden-only interiors miss; zero-opacity fills remain selectable. Scores and estimates unchanged. | | 2026-11-11 | minor | Bundled content: built-in Energy Beams brush library (Laser Bolt, Plasma Arc, Charge Wave, Spark Trail); brush libraries evidence updated; ~44% → ~46%; more built-in brush libraries remain. | | 2026-11-11 | minor | Bundled content: built-in Skill Icons symbol library (Attack, Defend, Heal, Buff, Ult); symbol libraries evidence updated; ~42% → ~44%; more built-in symbol libraries remain. | | 2026-11-10 | minor | Automation: MCP tool count 33; headless `command_list` lists `UI_COMMANDS` (`ui: true`); eight prompts; effect-id vs command-id clarified (#6460); scores and hours unchanged. | @@ -2367,4 +2372,4 @@ Edit › Copy and Cut put the selected ruler guides on the clipboard, with the s 2026-10-28 Flare interaction: the center drag turns only the rays by one degree per document point of increasing pointer y and back at the same rate for decreasing y. This is an application rule independent of event frequency. Shift keeps the current turn; Space during either drag moves the flare without changing its size or turn, including the first drag sample. Releasing a modifier resumes from the current pointer position without catching up skipped rotation. Scores and remaining estimates unchanged. ## EPS Save evidence (2026-10-26) -Ordinary Save and Save As keep EPS as EPS, with the chosen page frame, transparent margins and the complete editable VectorCraft document. Existing import-loss confirmation and transparency warnings remain; the Save TIFF preview is capped at 1024 pixels, while Export retains 2048. See [file-format-parity.md](file-format-parity.md#eps-save-and-source-protection) for limits and regression evidence. This narrows G9 save-back workflow coverage; native Illustrator editing-data fidelity, parity scores and hour estimates are unchanged. \ No newline at end of file +Ordinary Save and Save As keep EPS as EPS, with the chosen page frame, transparent margins and the complete editable VectorCraft document. Existing import-loss confirmation and transparency warnings remain; the Save TIFF preview is capped at 1024 pixels, while Export retains 2048. See [file-format-parity.md](file-format-parity.md#eps-save-and-source-protection) for limits and regression evidence. This narrows G9 save-back workflow coverage; native Illustrator editing-data fidelity, parity scores and hour estimates are unchanged. diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 296826671f..bd9f30a549 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -2,6 +2,8 @@ > **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-11 · **Change:** minor (Outline view: images and gradient meshes are picked on what Outline draws, so a click inside them reaches the path behind, #6437; previously minor: a middle-click on a document tab closes it, #6506; previously minor: Blob Brush: a round tip's preview is the outline of the area it adds, round at both ends, as the stroke it commits (#4343); scores and estimates unchanged; previously:; ruler double-click adds a guide at the pointer, #5239; G5: Inventory Icons built-in symbol library (four built-ins); previously minor: files that record no units open in Preferences › Units › General, #5820; previously minor: 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; floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; 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; #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; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Layers: Rename (`ui.rename`) opens the name field of the selected layer, group or object, #5324; Properties in Edit Artboards: Transform section above the Artboards section, #5219; scrubby labels: the Control bar's Stroke: and Opacity: links and the Properties panel's Stroke link scrub their fields, #4088; Properties: Quick Actions has Repeat Options for one selected repeat, #5181; Direct Selection: Shift-click picks several blend spine points, which drag together, #5285; Direct Selection: Cmd/Ctrl held lends the Selection tool and shows its bounding box, #3901; Join tool trims two crossing open paths and joins them at the crossing, #5844; Control bar: Paragraph: link and Align left/center/right while type is selected, #5372; shape tools: a press on the selection's centre point moves it and one in the rotate zone outside a box corner turns it, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) > +> Selection update (2026-11-11): path and compound-path interiors follow enabled non-None fill rows, including lower fills beneath a top None row (#6625). Hidden-only interiors miss; zero-opacity fills remain selectable. Scores and estimates unchanged. +> > Vector Halftone preview update (2026-11-10): temporary dot selection marks are hidden, and the bounding box stays available (#6369). > > Numeric spinner update (2026-11-10): held mouse arrows repeat past the click timeout; scores and estimates unchanged (#6307). @@ -187,6 +189,7 @@ tools, never checked side by side) isn't captured row by row. | Behaviour | Status | Notes | |---|---|---| +| Path and compound-path interior selection follows enabled non-None fill rows | done | #6625; lower visible fill beneath a top None row stays selectable; hidden-only/None interiors miss; zero-opacity, edge, Outline/path-only and hole controls in `crates/engine/tests/path_fill_hits.rs` | | Deleting segments or anchors that disconnect an ordinary path creates independent selected objects | done | #3380, deletion only: first piece retains its ID, styles and transforms carry over in sibling order, bounds-fitted gradients keep their original placement, and one Undo restores the original. Existing multi-subpath paths and compound members stay intact. `delete_path_pieces` covers transformed/styled rectangles, cubic handles and Undo/Redo. Endpoint highlighting remains open. | | Click/Shift-click anchors; marquee toggles with Shift | done | #483 | | Align selected anchors to their bounds or the artboard; repeating an alignment that moves nothing keeps Undo, Redo and saved state | done | #1180 follow-up; engine regressions include rounding-only moves and unchanged handles; #1641 (fixes #1636): Align and Distribute act on the anchors selected with Direct Selection, the points of one path aligning to each other and Distribute spacing them | @@ -511,6 +514,7 @@ separate. Scores and hours unchanged. [Behavior and command details](development | Date | Change | Summary | |---|---|---| +| 2026-11-11 | minor | #6625: path and compound-path interior hits follow enabled non-None fill rows, including lower fills beneath a top None row; hidden-only interiors miss; zero-opacity fills remain selectable. Scores and estimates unchanged. | | 2026-11-11 | minor | Outline view: a click on a path's outline selects it through an image or a gradient mesh in front, which Outline draws as a frame or mesh lines (#6437). | | 2026-11-11 | minor | A middle-click on a document tab (or its ×) closes it as the × does; closing a document's last view with unsaved changes asks to save first (#6506). VectorCraft addition; scores and estimates unchanged. | | 2026-11-03 | minor | A double-click on a ruler adds a guide at the pointer (#5239): a vertical one on the top ruler, a horizontal one on the left ruler; scores and estimates unchanged. | From 8a9fa29ba2ea1bca3cd2a0dacad24ac93afa535a Mon Sep 17 00:00:00 2001 From: yoriswind Date: Thu, 12 Nov 2026 12:19:06 -0800 Subject: [PATCH 004/176] docs: separate selection note from volatile gap header --- docs/gaps.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/gaps.md b/docs/gaps.md index 882f44fe36..45fb7692bf 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -1,7 +1,7 @@ # Gaps > **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-11 · **Change:** minor (Glyphs panel: Alternates for Current Selection applies an OpenType feature value (`salt=2`) to the selected letter alone, so an Arabic word stays joined, and Entire Font lists the unencoded glyphs, #5514; #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: G5: built-in Energy Beams brush library; estimate 5–15 → 4–14 h; previously minor: G5: built-in Skill Icons symbol library; estimate 6–16 → 5–15 h; previously minor: ruler double-click adds a guide at the pointer, #5239; G5: built-in Status Effects graphic style library; estimate 7–17 → 6–16 h; MCP docs catch-up for UI Frames and Map Markers; previously minor: G5: built-in Inventory Icons symbol library; estimate 8–18 → 7–17 h; previously minor: G9: `.ai` save names a variable font instance's design-space setting, #6388; previously minor: G5: built-in Game Trails brush library; estimate 9–19 → 8–18 h; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: docs tidy-up, no content change: stray notes at the top moved into the revision table; scores and estimates unchanged; previously 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) -> + > Selection update (2026-11-11): path and compound-path interiors follow enabled non-None fill rows, including lower fills beneath a top None row (#6625). Hidden-only interiors miss; zero-opacity fills remain selectable. Scores and estimates unchanged. ## Feature submission evidence From c103439d2cc0548d6584bc099c14afd33747ff3a Mon Sep 17 00:00:00 2001 From: yoriswind Date: Thu, 12 Nov 2026 23:57:50 -0800 Subject: [PATCH 005/176] 6625: respect stroke caps and joins in fill hit testing --- crates/doc/src/hit.rs | 9 +-- crates/engine/tests/path_fill_hits.rs | 99 +++++++++++++++++++++++++++ docs/gaps.md | 5 +- docs/roadmap.md | 5 +- docs/target-app-parity.md | 7 +- docs/ui-parity.md | 5 +- 6 files changed, 117 insertions(+), 13 deletions(-) diff --git a/crates/doc/src/hit.rs b/crates/doc/src/hit.rs index 9b06e806f5..efeaf2c24a 100644 --- a/crates/doc/src/hit.rs +++ b/crates/doc/src/hit.rs @@ -752,8 +752,9 @@ fn hit_stroke(n: &Node, bp: &vectorcraft_geom::BezPath, rule: vectorcraft_geom:: stroke_contains(bp, 0.0, opt.tol, p).then_some(HitKind::Outline) } -/// Check the body without assembling a `BezPath`. A miss near a joint or cap may still hit a -/// miter or square cap, so the caller falls back to the full stroke check there. +/// Check the body without assembling a `BezPath`. Near an end or joint, the caller uses the +/// full stroke check for non-round caps or joins: Butt and Bevel can reject a radial body hit, +/// while Miter and Square can extend beyond it. fn near_path_body(path: &PathData, p: Point, radius: f64, decoration_reach: f64) -> Option<(bool, bool)> { if !radius.is_finite() || radius < 0.0 || !decoration_reach.is_finite() || decoration_reach < 0.0 { return None; @@ -832,10 +833,10 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio path, p, s.width / 2.0 + opt.tol, - if s.join == crate::LineJoin::Miter || s.cap == crate::LineCap::Square { s.reach() + opt.tol } else { 0.0 }, + if s.join != crate::LineJoin::Round || s.cap != crate::LineCap::Round { s.reach() + opt.tol } else { 0.0 }, ) { - if hit { + if hit && !near_decoration { return Some(HitKind::Stroke); } if !near_decoration { diff --git a/crates/engine/tests/path_fill_hits.rs b/crates/engine/tests/path_fill_hits.rs index 652a82667e..f8dfebafaf 100644 --- a/crates/engine/tests/path_fill_hits.rs +++ b/crates/engine/tests/path_fill_hits.rs @@ -143,3 +143,102 @@ fn compound_hit_uses_visible_fill_stack() { ]; assert_eq!(observed, expected, "render and hit-test observations by Compound fill-stack case"); } + +#[test] +fn hit_respects_open_stroke_caps_with_hidden_fill() { + use vectorcraft_doc::{LineCap, LineJoin}; + use vectorcraft_geom::{BezPath, PathData}; + + let mut observed = Vec::new(); + let mut expected = Vec::new(); + // Round and Square are legitimate controls before the Butt regression. + for (cap, endpoint_pixel, endpoint_hit) in [ + (LineCap::Round, [0, 0, 0, 255], Some(HitKind::Stroke)), + (LineCap::Square, [0, 0, 0, 255], Some(HitKind::Stroke)), + (LineCap::Butt, [255, 255, 255, 255], None), + ] { + for join in [LineJoin::Miter, LineJoin::Round] { + let mut hidden = fill(Paint::solid(Color::BLACK)); + hidden.visible = false; + for (name, fills) in [ + ("hidden painted fill", vec![hidden]), + ("absent fill", vec![]), + ("explicit Fill None", vec![fill(Paint::None)]), + ("visible fill on a zero-area line", vec![fill(Paint::solid(Color::BLACK))]), + ] { + let mut doc = Document::new(160.0, 96.0); + let layer = doc.layers[0].id; + let id = doc.alloc_id(); + let mut appearance = Appearance::default(); + appearance.items.extend(fills.into_iter().map(AppearanceItem::Fill)); + let mut stroke = StrokeLayer::new(Paint::solid(Color::BLACK), 10.0); + stroke.cap = cap; + stroke.join = join; + appearance.items.push(AppearanceItem::Stroke(stroke)); + let path = PathData::from_bezpath(&BezPath::from_svg("M24 48 L124 48").unwrap()); + doc.insert(Some(layer), usize::MAX, Node::path(id, path, appearance)).unwrap(); + let mut renderer = Renderer::new(); + renderer.threads = 0; + let image = renderer.render( + &doc, + 160, + 96, + Affine::IDENTITY, + &RenderOptions { background: Some([255, 255, 255, 255]), artboards: false, ..RenderOptions::default() }, + ); + let options = HitOptions { tol: 0.5, ..HitOptions::default() }; + let end = hit_test(&doc, Point::new(20.0, 48.0), options).map(|hit| hit.kind); + let body = hit_test(&doc, Point::new(60.0, 48.0), options).map(|hit| hit.kind); + assert_eq!(image.pixel(60, 48), [0, 0, 0, 255], "INPUT: {cap:?}/{join:?}/{name} stroke body must draw"); + assert_eq!(body, Some(HitKind::Stroke), "INPUT: {cap:?}/{join:?}/{name} stroke body must hit"); + observed.push((cap, join, name, image.pixel(20, 48), end, image.pixel(60, 48), body)); + expected.push((cap, join, name, endpoint_pixel, endpoint_hit, [0, 0, 0, 255], Some(HitKind::Stroke))); + } + } + } + assert_eq!(observed, expected, "visible stroke caps and hit testing must agree, including hidden-fill paths"); +} + +#[test] +fn hit_respects_hidden_fill_stroke_joins() { + use vectorcraft_doc::{LineCap, LineJoin}; + use vectorcraft_geom::{BezPath, PathData}; + + let mut observed = Vec::new(); + let mut expected = Vec::new(); + for (join, joint_painted, joint_hit) in + [(LineJoin::Round, true, Some(HitKind::Stroke)), (LineJoin::Miter, true, Some(HitKind::Stroke)), (LineJoin::Bevel, false, None)] + { + let mut doc = Document::new(160.0, 96.0); + let layer = doc.layers[0].id; + let id = doc.alloc_id(); + let mut hidden = fill(Paint::solid(Color::BLACK)); + hidden.visible = false; + let mut appearance = Appearance::default(); + appearance.items.push(AppearanceItem::Fill(hidden)); + let mut stroke = StrokeLayer::new(Paint::solid(Color::BLACK), 10.0); + stroke.cap = LineCap::Round; + stroke.join = join; + appearance.items.push(AppearanceItem::Stroke(stroke)); + let path = PathData::from_bezpath(&BezPath::from_svg("M32 64 L96 64 L96 24").unwrap()); + doc.insert(Some(layer), usize::MAX, Node::path(id, path, appearance)).unwrap(); + let mut renderer = Renderer::new(); + renderer.threads = 0; + let image = renderer.render( + &doc, + 160, + 96, + Affine::IDENTITY, + &RenderOptions { background: Some([255, 255, 255, 255]), artboards: false, ..RenderOptions::default() }, + ); + let options = HitOptions { tol: 0.5, ..HitOptions::default() }; + let joint = hit_test(&doc, Point::new(99.0, 67.0), options).map(|hit| hit.kind); + let body = hit_test(&doc, Point::new(60.0, 64.0), options).map(|hit| hit.kind); + assert_eq!(image.pixel(60, 64), [0, 0, 0, 255], "INPUT: {join:?} stroke body must draw"); + assert_eq!(body, Some(HitKind::Stroke), "INPUT: {join:?} stroke body must hit"); + // Round's corner pixel can be antialiased; only its visible paint is required. + observed.push((join, image.pixel(99, 67) != [255, 255, 255, 255], joint)); + expected.push((join, joint_painted, joint_hit)); + } + assert_eq!(observed, expected, "hidden-fill stroke joins must match actual CPU paint at the outer joint"); +} diff --git a/docs/gaps.md b/docs/gaps.md index 1f36fe1907..864f0ee2a8 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -2,7 +2,7 @@ > **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-12 · **Change:** minor (icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: oversized editing artboard import; Glyphs panel: Alternates for Current Selection applies an OpenType feature value (`salt=2`) to the selected letter alone, so an Arabic word stays joined, and Entire Font lists the unencoded glyphs, #5514; #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: G5: built-in Energy Beams brush library; estimate 5–15 → 4–14 h; previously minor: G5: built-in Skill Icons symbol library; estimate 6–16 → 5–15 h; previously minor: ruler double-click adds a guide at the pointer, #5239; G5: built-in Status Effects graphic style library; estimate 7–17 → 6–16 h; MCP docs catch-up for UI Frames and Map Markers; previously minor: G5: built-in Inventory Icons symbol library; estimate 8–18 → 7–17 h; previously minor: G9: `.ai` save names a variable font instance's design-space setting, #6388; previously minor: G5: built-in Game Trails brush library; estimate 9–19 → 8–18 h; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: docs tidy-up, no content change: stray notes at the top moved into the revision table; scores and estimates unchanged; previously 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) -> Selection update (2026-11-11): path and compound-path interiors follow enabled non-None fill rows, including lower fills beneath a top None row (#6625). Hidden-only interiors miss; zero-opacity fills remain selectable. Scores and estimates unchanged. +> Selection update (2026-11-11): path and compound-path interiors follow enabled non-None fill rows, including lower fills beneath a top None row (#6625). Hidden-only interiors miss; zero-opacity fills remain selectable. Cap/join follow-up (2026-11-12): hidden-fill and no-fill stroke hits must respect cap and join geometry; focused cap/join CPU regressions passed. Scores and estimates unchanged. ## Feature submission evidence @@ -113,7 +113,7 @@ from G14 and the budget run of G15: **~170–270 h** one agent, ~50–80 h wall macOS cursor delivery (#2292) is narrowed to a native host adapter using the existing artwork and aligned 1×/2× representations. Headless tests cover visible fallbacks, preparation and ownership; native focus/menu/handback timing, mixed displays, Spotlight and full-screen Spaces remain open validation work (see [hardware parity](hardware-parity.md)). This does not close the interaction-fidelity gap or change its score/estimate. -- **Selection fill eligibility (#6625):** Path and compound-path interiors use any enabled non-None fill row (#6625). A lower visible fill remains selectable beneath a top None row in the same object; hidden-only and true-None interiors miss. Zero-opacity fills remain selectable. Original CPU-render and document-hit regressions in `crates/engine/tests/path_fill_hits.rs` cover seven Path and five Compound cases, including stroke edges, geometric outlines, Outline/path-only modes and compound holes. Scores and estimates unchanged. +- **Selection fill eligibility (#6625):** Path and compound-path interiors use any enabled non-None fill row (#6625). A lower visible fill remains selectable beneath a top None row in the same object; hidden-only and true-None interiors miss. Zero-opacity fills remain selectable. Original CPU-render and document-hit regressions in `crates/engine/tests/path_fill_hits.rs` cover seven Path and five Compound cases, including stroke edges, geometric outlines, Outline/path-only modes and compound holes. Hidden-fill and no-fill stroked paths must respect butt, round and square caps and bevel, round and miter joins. Focused cap/join CPU regressions passed. Scores and estimates unchanged. - **Panel collapse controls (#5925, in part):** The small » in a floating tab-group header moves that group into the side icon rail, reusing the existing rail or creating one. An opened rail panel has the same control to fold its flyout back into the rail, including after a tab switch. Both controls preserve the tab group and its menu; other floating groups and full-width docked headers stay as they were. Pointer regressions in `crates/ui-egui/src/panel_docking/tests.rs` cover grouped tabs, reopening, separate groups, a missing rail, the menu and flyout closure after switching tabs; `native_tests.rs` covers the native-window click and removal of the empty palette. Scores and estimates unchanged. @@ -871,6 +871,7 @@ trap, and the defaults (0.25 pt, 100%, 40%) are VectorCraft's own, the pages giv | Date | Change | Summary | |---|---|---| | 2026-11-12 | minor | Explicit editing-data import keeps a single artboard beyond a capped 14,400 pt PDF page (#6865), with a warning; automatic mode stays unchanged. Scores and estimates unchanged. | +| 2026-11-12 | minor | #6625 cap/join follow-up: hidden-fill and no-fill stroke hits must respect their cap/join geometry; focused CPU regressions passed. Existing fill-stack evidence, scores and estimates unchanged. | | 2026-11-09 | minor | G4 review (#6084): positional variants no supported feature draws can be applied as glyph choices in both Glyphs views; unlisted glyphs still respect name ownership. OpenType style options keep only a valid last on-value when enabling a set. Existing contextual/ligature lookup and unsupported-feature gaps remain; estimate unchanged. | | 2026-11-07 | minor | G4: the Glyphs panel's Alternates for Current Selection applies the OpenType feature that draws a variant to that letter alone (`salt=2`; the style commands take `tag=N`; runs that differ only in their features shape as one piece of text), so an Arabic word stays joined, and Show › Entire Font lists the unencoded glyphs (#5514). Estimate unchanged. | | 2026-11-12 | minor | G11: numeric fields keep the caret when a focus click is released more than 1 pt from its press; a tap within 1 pt still selects the whole value (#6659, follow-up to #1326); short-drag and jitter-tap regressions in `tests/numfields.rs`; estimates unchanged. | diff --git a/docs/roadmap.md b/docs/roadmap.md index 7f3ac0c123..eceef1c627 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -4,7 +4,7 @@ > > Oversized artboard import update (2026-11-12): Explicit editing-data import retains a single artboard beyond a capped 14,400 pt PDF page (#6865). > -> Selection update (2026-11-11): path and compound-path interiors follow enabled non-None fill rows, including lower fills beneath a top None row (#6625). Hidden-only interiors miss; zero-opacity fills remain selectable. Scores and estimates unchanged. +> Selection update (2026-11-11): path and compound-path interiors follow enabled non-None fill rows, including lower fills beneath a top None row (#6625). Hidden-only interiors miss; zero-opacity fills remain selectable. Cap/join follow-up (2026-11-12): hidden-fill and no-fill stroke hits must respect cap and join geometry; focused cap/join CPU regressions passed. Scores and estimates unchanged. > > Vector Halftone preview update (2026-11-10): temporary dot selection marks are hidden, and the bounding box stays available (#6369). > @@ -149,7 +149,7 @@ native wording review, layout checks and a web Devanagari font remain. [Notes](l | # | Milestone | Status | Est. remaining, one agent (h) | |---|---|---|---| | M0 | Skeleton + vertical slice | ✅ done | — | -| M1 | Selection, transform, layers, MCP (common command tools, strict keys, session resources and version-aware result hints) | ✅ mostly done (path and compound-path interior selection follows enabled fill rows (#6625); document-tab artwork drag with lossless resource transfer and one target Undo; malformed MCP app replies discard the connection without replay, #1761; bounded control socket waits and connection-slot recovery, #1726; bounded synthetic control input, #1709; no-op anchor Align keeps Undo, Redo and saved state (#1180 follow-up); transform reference point snaps to anchors/centres; rotated objects keep a rotated bounding box and their angle; Free Transform, Scale and Reflect along a rotated box pending; the Transform fields take one Tab each, the W/H link after them) | 4–6 | +| M1 | Selection, transform, layers, MCP (common command tools, strict keys, session resources and version-aware result hints) | ✅ mostly done (path and compound-path interior selection follows enabled fill rows (#6625); hidden-fill and no-fill stroke cap/join CPU regressions passed; document-tab artwork drag with lossless resource transfer and one target Undo; malformed MCP app replies discard the connection without replay, #1761; bounded control socket waits and connection-slot recovery, #1726; bounded synthetic control input, #1709; no-op anchor Align keeps Undo, Redo and saved state (#1180 follow-up); transform reference point snaps to anchors/centres; rotated objects keep a rotated bounding box and their angle; Free Transform, Scale and Reflect along a rotated box pending; the Transform fields take one Tab each, the W/H link after them) | 4–6 | | M2 | Drawing tools + smart guides | ✅ mostly done (#3380 deletion creates independent selected path pieces and keeps bounds-fitted gradients in place; endpoint highlighting remains open; Polygon/Star exact-size count persistence, with repeated-drag, tool-switch and Cancel regression coverage; Curvature point markers without direction handles (#1236, in part); Direct Selection segment click/Delete preserves neighboring edges, #1278; Flare, Reshape, Live Corners widget dragging and per-corner radii and kinds landed, on any path's corners; Shaper rough-shape recognition and orientation steps, the remaining Pen modifier nuances; Shaper Groups with editable sources and separate fill/stroke edits landed; custom ruler origin with drag preview, active-artboard reset, relative X/Y fields and native round-trip (#1212); construction widget/refinements pending); a shape just drawn moves by its centre point and turns from the zone outside a corner with its tool still active (#5477); Tangent and straight-segment perpendicular snapping use saved Smart Guides Geometric Guides preferences and Control bar quick access (#2537), including the existing Snap to Glyph and Alignment Guides toggles (#6164); no View submenu; Copy and Cut with the Pen or Curvature tool take the anchors a Cmd/Ctrl-lent Direct Selection picked (#6123) | 12–18 | | M3 | Paint & appearance (swatches, color, gradient, stroke, appearance, transparency, styles) | ✅ done (M3.7–M3.98): swatches, groups, libraries, tints, Lab spots and Registration; Eyedropper copies transformed character dimensions (#6404) and 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; finite-arithmetic follow-up regressions and full CI passed ([Validation evidence](target-app-parity.md#evidence-what-ships-today-by-area))), 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; Recolor model selection is available through the engine and MCP only (#2520); the dialog retains its existing controls; Library panels' lists (swatch, Color Book, brush, symbol and graphic style libraries) fill a taller panel above its footer (#2992; scores and estimates unchanged); | Swatches list fills a taller panel above its footer (#1638; `the_list_fills_a_tall_panel_above_its_footer`; scores and estimates unchanged); 4–8 | | M4 | Files (native, SVG, PDF, raster, Export for Screens, clipboard interop) | Explicit editing-data import keeps oversized capped-page artboards (#6865; estimates unchanged); Save refusal continuation (#6146): ordinary Save offers Save As; unchanged format keeps options, changed format opens its Save options; cancellation/automation isolation; focused UI regressions passed, native acceptance pending; PDF authored ActualText preserved once in editable import (#6165; first-glyph line/style, bounded input; estimates unchanged); 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. `.ai`/EPS type from the text document keeps its paragraphs' tab stops (#6147); `.ai`/EPS type from the text document keeps auto leading per line, its 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 (#6137); ✅ done (M4.14–M4.98 on 2026-10-05): Save As/Save a Copy/Revert/templates, Data Recovery and background save, SVG import and export fidelity (units, text, symbols, filters, SVGZ, Preserve Editing, SVG Options), shared guarded PDF writer and windowed reader ([pdf-backend.md](pdf-backend.md)), PDF import (colours, layers, masks, editable text, security) and export (presets, marks, bleed, ICC and output intent, raster effects, subset fonts, PDF/X-1a, X-3 and X-4, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3), Place and Links, Package, EPS and DXF in and out (EPS legacy mesh corners, vector opacity masks and raster page comparison verified; closed SPLINE flags round-trip and circular paths export as native CIRCLE/ARC, #1299), EMF/WMF, TIFF/BMP/Targa/PSD/GIF/PNG-8 export, Print and print presets, slices, Save for Web, TIFF in Export for Screens and Asset Export, clipboard flavours, File Info; AF.1–AF.4 add Affinity import (native layers, artboards, vectors, text and images from Affinity 1–3 files; the embedded preview only as a warned fallback; AF.4 expands current `.af` fixtures and every-board round-trip validation); EPS Save and Save As keep an opened EPS as EPS with its page frame and complete editable VectorCraft document (2026-10-26; G9 import fidelity unchanged). Left: DWG (use DXF), PSD placement as layers, overprint read back from PDF, Affinity export, polish; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts | 3–6 (existing scope; Affinity export unestimated) | @@ -204,6 +204,7 @@ separate. Scores and hours unchanged. [Behavior and command details](development | 2026-11-12 | minor | M14: numeric fields keep the caret when a focus click is released more than 1 pt from its press; a tap within 1 pt still selects all (#6659, follow-up to #1326); estimates unchanged. | | 2026-11-12 | minor | M12: Live Paint Bucket fills faces crossed in one drag (#6373). Scores and estimates unchanged. | | 2026-11-12 | minor | Save refusal follow-up (#6146): changed format opens its Save options; unchanged format retains original options. Focused UI regressions passed, including the format-change case that failed before the fix; native panel acceptance pending. Scores and estimates unchanged. | +| 2026-11-12 | minor | #6625 cap/join follow-up: hidden-fill and no-fill stroke hits must respect their cap/join geometry; focused CPU regressions passed. Existing fill-stack evidence, scores and estimates unchanged. | | 2026-11-11 | minor | Eyedropper copies effective character dimensions between transformed text objects (#6404); scores and estimates unchanged. | | 2026-11-11 | minor | Ordinary Save to a location refusing writes offers Save As (#6146); cancellation preserves the original path and modified state; automation receives READ_ONLY_LOCATION. Scores and estimates unchanged. Validation pending. | | 2026-11-11 | minor | M10/G5: Energy Beams built-in brush library; MCP docs catch-up; estimates unchanged | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 1dabac2566..ffd1747e36 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -8,7 +8,7 @@ > > Live Paint Bucket update (2026-11-12): one drag fills the faces crossed in the same group (#6373). > -> Selection update (2026-11-11): path and compound-path interiors follow enabled non-None fill rows, including lower fills beneath a top None row (#6625). Hidden-only interiors miss; zero-opacity fills remain selectable. Scores and estimates unchanged. +> Selection update (2026-11-11): path and compound-path interiors follow enabled non-None fill rows, including lower fills beneath a top None row (#6625). Hidden-only interiors miss; zero-opacity fills remain selectable. Cap/join follow-up (2026-11-12): hidden-fill and no-fill stroke hits must respect cap and join geometry; focused cap/join CPU regressions passed. Scores and estimates unchanged. > > Vector Halftone preview update (2026-11-10): temporary dot selection marks are hidden, and the bounding box stays available (#6369). > @@ -226,7 +226,7 @@ dominate; 3D, graphs and automation are specialist). They sum to 105. Feature de | Area | Weight | Done | Main gaps | One agent (h) | Kind | |---|---:|---:|---|---:|---| -| Selection, transform & align tools | 6 | 85% | Direct Selection segment click/Delete corrected (#1278); deletion splits an ordinary contour into selected sibling objects with bounds-fitted gradients kept in place (#3380, deletion only; `crates/engine/tests/it/delete_path_pieces.rs`); open-path anchor Delete keeps gaps; Select › Start Global Edit finds the paths, compound paths and symbol instances of the selected object's shape (Appearance, Size and artboard options) and gives an edit of one to all of them in proportion, as one undo step (#3521), and on a group the groups like it, an edit inside one reaching the same object in the others (#4939), and a Shift-click on a highlighted match leaves it out; the Align panel menu's Align to Glyph Bounds › Point Text and Area Text measure type by its glyphs' ink for Align and Distribute (#4231); remaining: Free Transform/Scale/Reflect along a rotated box, Global Edit of rotated copies, transform nuances (no-op anchor Align history regression-tested, #1180 follow-up) | 4–6 | estimated; fill-stack selection regression-tested (`crates/engine/tests/path_fill_hits.rs`, #6625); Global Edit regression-tested (`crates/engine/src/tests/globaledit.rs`; Quick Action, menu label and Escape in `panels::properties::tests::start_global_edit_quick_action_and_escape`) | +| Selection, transform & align tools | 6 | 85% | Direct Selection segment click/Delete corrected (#1278); deletion splits an ordinary contour into selected sibling objects with bounds-fitted gradients kept in place (#3380, deletion only; `crates/engine/tests/it/delete_path_pieces.rs`); open-path anchor Delete keeps gaps; Select › Start Global Edit finds the paths, compound paths and symbol instances of the selected object's shape (Appearance, Size and artboard options) and gives an edit of one to all of them in proportion, as one undo step (#3521), and on a group the groups like it, an edit inside one reaching the same object in the others (#4939), and a Shift-click on a highlighted match leaves it out; the Align panel menu's Align to Glyph Bounds › Point Text and Area Text measure type by its glyphs' ink for Align and Distribute (#4231); remaining: Free Transform/Scale/Reflect along a rotated box, Global Edit of rotated copies, transform nuances (no-op anchor Align history regression-tested, #1180 follow-up) | 4–6 | estimated; fill-stack selection regression-tested (`crates/engine/tests/path_fill_hits.rs`, #6625); cap/join follow-up CPU regressions passed; Global Edit regression-tested (`crates/engine/src/tests/globaledit.rs`; Quick Action, menu label and Escape in `panels::properties::tests::start_global_edit_quick_action_and_escape`) | | Drawing tools (Pen, Curvature, Pencil, shapes, Shaper) | 7 | 85% | Shaper construction widget, Pencil/Pen nuances, Blob Brush options, Touch Type, Dimension tool; see [ui-parity.md](ui-parity.md) | 8–13 | estimated; Curvature point display regression-tested (#1236, in part); Polygon/Star exact-size count persistence regression-covered; Live Corners' Relative rounding done (#3091), score unchanged; Copy and Cut with the Pen or Curvature tool take the anchors a Cmd/Ctrl-lent Direct Selection picked (#6123), score and hours unchanged; the Pen, Smart Pen and Curvature tool show the measurement readout with the rubber band off (#7043), score, gaps and hours unchanged | | Path operations, Pathfinder, Shape Builder, Live Paint | 5 | 80% | Shape Builder on the reporter's file (#937: art past 4,096 segments is cut by lines again; unconfirmed on the file itself); gap detection shares Live Paint’s finder, with a 72 pt custom cap and the existing options; Live Paint Gap Options | 4–8 | estimated; 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 (lowered from 86%: open issues); compound attributes regression-tested (#1197); single-result source names survive SVG export/import (#1293), with [SVG ID semantics](https://www.w3.org/TR/SVG2/struct.html#IDAttribute) and original-shape tests; Simplify component selection and preview regression-tested (#1272); Simplify of a Direct Selection part of a path regression-tested (`tests/simplify_part.rs`); Divide open-cutting-path geometry and appearance regression-tested (#1307); the Shape Builder's edge-source grid is bounded in memory and files a segment once per cell (`planar.rs` test `rect_index_holds_a_bounded_number_of_references`); live compound shapes (Make, Alt-click, member Shape Modes, Release, Expand, saved and exported) regression-tested (#4522); Live Paint Bucket face drags, including narrow faces and one Undo, regression-tested (#6373) | | Colour, swatches, gradients, patterns, mesh, recolor | 7 | 92% | Eyedropper copies effective character dimensions across text transforms (#6404); 30.0's gradient additions are done (dither, perceptual blending, presets); freeform gradients in SVG/PDF, mixed spot/process gradients in SVG, PDF gradients mixing a spot color with RGB or Lab stops, and dithered spot gradient fills and Perceptual spot gradients with RGB or Lab stops other than white or more than 4,096 stops on their curve, which PDF export writes as images in process colors| 4–7 | estimated; Recolor model selection is available through the engine and MCP (#2520), and the dialog's color sliders (HSB, RGB, CMYK, Lab, Tint for a spot color) edit the selected row's new color in its mode, and the Edit tab's Global Adjust sliders (Saturation, Brightness, Temperature, Luminosity, -100% to 100%) change every recolored color at once (lowered from 96%: target moved); unpainted zero-width stroke restoration fixed (#1253), score and hours unchanged; Eyedropper source reads regression-tested (#1251); screen-bounded Recolor Edit chip list (#3416), score and hours unchanged; a point on a gradient mesh's outline locates on its edge on every side (#7006: `mesh_locate_takes_a_point_on_any_side_of_the_outline`, `mesh_add_line_exactly_on_the_edge_needs_no_tolerance`), score and hours unchanged | @@ -565,7 +565,7 @@ since 2026-10-01. - **Save refusal (#6146):** ordinary File > Save to its own location offers Save As after a terminal permission/read-only refusal, suggesting the original name and format, preserving options for the unchanged format and opening the chosen format’s Save options on a change. Cancel keeps the failed-save state. Busy pickers, recovery-copy errors, other failures, explicit destinations and Close/Quit keep the existing dialog. Engine, UI and MCP regression cases are in `cmd/fileio/tests_readonly.rs`, `io/tests_read_only_save.rs` and MCP `tests/fileio.rs`; focused UI regressions passed; engine regression execution and native panel acceptance pending. Scores and hours unchanged. -**Selection fill eligibility (#6625):** Path and compound-path interiors use any enabled non-None fill row (#6625). A lower visible fill remains selectable beneath a top None row in the same object; hidden-only and true-None interiors miss. Zero-opacity fills remain selectable. Original CPU-render and document-hit regressions in `crates/engine/tests/path_fill_hits.rs` cover seven Path and five Compound cases, including stroke edges, geometric outlines, Outline/path-only modes and compound holes. Scores and estimates unchanged. +**Selection fill eligibility (#6625):** Path and compound-path interiors use any enabled non-None fill row (#6625). A lower visible fill remains selectable beneath a top None row in the same object; hidden-only and true-None interiors miss. Zero-opacity fills remain selectable. Original CPU-render and document-hit regressions in `crates/engine/tests/path_fill_hits.rs` cover seven Path and five Compound cases, including stroke edges, geometric outlines, Outline/path-only modes and compound holes. Hidden-fill and no-fill stroked paths must respect butt, round and square caps and bevel, round and miter joins. Focused cap/join CPU regressions passed. Scores and estimates unchanged. - **PDF authored replacement text (#6165):** `crates/pdf/src/tests/actual_text.rs` covers replacement once with suffix placement, PDF text-string decoding, empty and nested owners, sibling spans, page reset, multiple text-show operations, style/line changes, fill-and-stroke, reader windows and bounded input. Authored logical-order stretches are protected while adjacent ordinary text still undergoes reconstruction. The replacement takes its first placed glyph's style and line; its characters are not redistributed over later lines/styles. Exact mixed-direction paragraph layout is not claimed. No export changes; scores and hours stay at 75% / 10–20 h. @@ -2168,6 +2168,7 @@ Edit › Copy and Cut put the selected ruler guides on the clipboard, with the s | 2026-11-12 | minor | `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints (its strokes' miter tips, and strokes a Transform effect moves, included), after its glyphs grown by half its strokes' weight; `.ai` import evidence updated (#6824); scores and estimates unchanged. | | 2026-11-12 | minor | Explicit editing-data import keeps a single artboard beyond a capped 14,400 pt PDF page (#6865), with a warning; automatic mode stays unchanged. Scores and estimates unchanged. | | 2026-11-12 | minor | Glyphs review (#6084): Entire Font uses the selection's version and variable axes for previews and alternate applicability. The default cell can reset an unlisted glyph choice when GSUB lists no alternates. Encoded Latin and other ordinary characters insert unchanged even if their glyph also has Arabic positional provenance; Arabic presentation forms retain base-letter insertion. Remove a redundant charmap scan from unlisted-glyph checks. Scores and estimates unchanged. | +| 2026-11-12 | minor | #6625 cap/join follow-up: hidden-fill and no-fill stroke hits must respect their cap/join geometry; focused CPU regressions passed. Existing fill-stack evidence, scores and estimates unchanged. | | 2026-11-09 | minor | Glyphs review (#6084): positional alternates with no supported feature are accepted as glyph choices in both panel views; Entire Font's unlisted-glyph and name-ownership behavior is retained. OpenType style options keep only a valid last on-value when enabling a set. Contradictory old glyph-choice evidence corrected; scores and estimates unchanged. | | 2026-11-07 | minor | Type core: the Glyphs panel's Alternates for Current Selection applies the OpenType feature that draws a variant to the selected letter alone, so an Arabic word stays joined (`salt=2`; the style commands take `tag=N`), and Show › Entire Font lists the glyphs no character maps (#5514; [Replace characters with alternate glyphs](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/replace-characters-with-alternate-glyphs.html)); evidence added; scores unchanged. | | 2026-11-12 | minor | UI chrome: a numeric-field focus click released more than 1 pt from its press keeps the caret; a tap within 1 pt still selects the whole value (#6659, follow-up to #1326); scores and hours unchanged. | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 6af5db10cf..133b58e9fa 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -2,7 +2,7 @@ > **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-13 · **Change:** minor (library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Remove Background in the Contextual Task Bar, Properties › Quick Actions and the Control bar; previously minor: Ruler origin: the corner drag snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Outline view: images and gradient meshes are picked on what Outline draws, so a click inside them reaches the path behind, #6437; previously minor: a middle-click on a document tab closes it, #6506; previously minor: Blob Brush: a round tip's preview is the outline of the area it adds, round at both ends, as the stroke it commits (#4343); scores and estimates unchanged; previously:; ruler double-click adds a guide at the pointer, #5239; G5: Inventory Icons built-in symbol library (four built-ins); previously minor: files that record no units open in Preferences › Units › General, #5820; previously minor: 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; floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; 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; #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; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Layers: Rename (`ui.rename`) opens the name field of the selected layer, group or object, #5324; Properties in Edit Artboards: Transform section above the Artboards section, #5219; scrubby labels: the Control bar's Stroke: and Opacity: links and the Properties panel's Stroke link scrub their fields, #4088; Properties: Quick Actions has Repeat Options for one selected repeat, #5181; Direct Selection: Shift-click picks several blend spine points, which drag together, #5285; Direct Selection: Cmd/Ctrl held lends the Selection tool and shows its bounding box, #3901; Join tool trims two crossing open paths and joins them at the crossing, #5844; Control bar: Paragraph: link and Align left/center/right while type is selected, #5372; shape tools: a press on the selection's centre point moves it and one in the rotate zone outside a box corner turns it, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) > -> Selection update (2026-11-11): path and compound-path interiors follow enabled non-None fill rows, including lower fills beneath a top None row (#6625). Hidden-only interiors miss; zero-opacity fills remain selectable. Scores and estimates unchanged. +> Selection update (2026-11-11): path and compound-path interiors follow enabled non-None fill rows, including lower fills beneath a top None row (#6625). Hidden-only interiors miss; zero-opacity fills remain selectable. Cap/join follow-up (2026-11-12): hidden-fill and no-fill stroke hits must respect cap and join geometry; focused cap/join CPU regressions passed. Scores and estimates unchanged. > > Vector Halftone preview update (2026-11-10): temporary dot selection marks are hidden, and the bounding box stays available (#6369). > @@ -195,7 +195,7 @@ tools, never checked side by side) isn't captured row by row. | Behaviour | Status | Notes | |---|---|---| -| Path and compound-path interior selection follows enabled non-None fill rows | done | #6625; lower visible fill beneath a top None row stays selectable; hidden-only/None interiors miss; zero-opacity, edge, Outline/path-only and hole controls in `crates/engine/tests/path_fill_hits.rs` | +| Path and compound-path interior selection follows enabled non-None fill rows | done | #6625; lower visible fill beneath a top None row stays selectable; hidden-only/None interiors miss; zero-opacity, edge, Outline/path-only and hole controls in `crates/engine/tests/path_fill_hits.rs`; hidden-fill and no-fill stroke cap/join CPU regressions passed | | Deleting segments or anchors that disconnect an ordinary path creates independent selected objects | done | #3380, deletion only: first piece retains its ID, styles and transforms carry over in sibling order, bounds-fitted gradients keep their original placement, and one Undo restores the original. Existing multi-subpath paths and compound members stay intact. `delete_path_pieces` covers transformed/styled rectangles, cubic handles and Undo/Redo. Endpoint highlighting remains open. | | Click/Shift-click anchors; marquee toggles with Shift | done | #483 | | Align selected anchors to their bounds or the artboard; repeating an alignment that moves nothing keeps Undo, Redo and saved state | done | #1180 follow-up; engine regressions include rounding-only moves and unchanged handles; #1641 (fixes #1636): Align and Distribute act on the anchors selected with Direct Selection, the points of one path aligning to each other and Distribute spacing them | @@ -538,6 +538,7 @@ before release (#6373). [Paint faces and edges](https://helpx.adobe.com/illustra | 2026-11-12 | minor | Remove Background for a selected image in the Contextual Task Bar, Properties › Quick Actions and the Control bar, which runs at once with its defaults. Scores and estimates unchanged. | | 2026-11-12 | minor | Live Paint Bucket fills faces crossed in one drag (#6373). Scores and estimates unchanged. | | 2026-11-12 | minor | Save refusal follow-up (#6146): changed format opens its Save options; unchanged format retains original options. Focused UI regressions passed, including the format-change case that failed before the fix; native panel acceptance pending. Scores and estimates unchanged. | +| 2026-11-12 | minor | #6625 cap/join follow-up: hidden-fill and no-fill stroke hits must respect their cap/join geometry; focused CPU regressions passed. Existing fill-stack evidence, scores and estimates unchanged. | | 2026-11-11 | minor | Ruler origin: the corner drag snaps as a drawn point does, onto the art's and the artboards' anchors, centres, edges and paths, and with Snap to Point along the ruler guides; scores and estimates unchanged | | 2026-11-11 | minor | macOS canvas cursor delivery (#2292): while the host owns the cursor it sets it again on every pass, so the tool's cursor stays after the pointer moves (#6362); `mac_cursor` ownership test updated; scores and estimates unchanged. | | 2026-11-11 | minor | Eyedropper copies effective character dimensions between transformed text objects (#6404); scores and estimates unchanged. | From 4716646c6bb4773c9866095029920ad4cc719b20 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 05:42:56 -0800 Subject: [PATCH 006/176] Scripts: File and Folder objects write files inside a script's scope, with per-script grants and pickers A script's File and Folder objects now open files for writing, appending and editing, and copy, rename, remove and create files and folders. A script reads and writes its run's temporary folder (Folder.temp) and its own data folder (Folder.userData), kept between runs for a script run from a file and inside Folder.temp for a script given as text. It reads its own folder, and reaches other places only through File.openDialog, File.saveDialog, Folder.selectDialog and the objects' openDlg, saveDlg and selectDlg. - A file dialog asks first. The person picks the file or folder with Choose..., then allows it once or, for a script run from a file, always. A kept grant is bound to the script's path, the SHA-256 of its text and every source the run evaluated. It is withdrawn when a later run of the script evaluates other code, including code an earlier run left in the same named engine. It stays on the real path that was granted, so a link put in that place later does not carry it elsewhere. - A dialog's filter is a string of file types or a function that is called with each file picked; multiSelect gives an array of the files picked, at most 2,048, and the dialog says when more were left out. - A folder's selectDlg opens the host's folder dialog in that folder, also where the host shows file dialogs in line. Enter in the file dialog denies, unless it goes to the focused Choose... button. script.grants.revoke is refused with the busy error while a script runs, as the run keeps the grants it started with. - The paths a file dialog allows come only from the host's file dialog: ui.dialog.set cannot set them. Only the person at the keyboard allows access; Allow Once and Always Allow sent by automation are refused. The dialog describes the access the run asked for, whatever its fields say. - No grant reaches the settings folder, also when the script's own folder holds it. - A file left open is not written through a link put in place of its folder since it was opened, and Folder.userData is null when the data folder or the script's folder in it is a link. - copy onto another link to the same file (a hard link) leaves the file's bytes as they are, after the source's open objects have written what they hold. Files are compared by identity (device and inode on Unix, volume and file index on Windows). - Folder.temp and Folder.userData check each folder they make against the automation write roots first, and Folder.create() makes nothing when a missing folder above the target is outside the places the script may write. - An open file holds at most 8 MiB, a run writes at most 32 MiB and keeps at most 256 files open, and the files a run left open are written in the order they were opened. Setting length and copying a file count the bytes every open object of that file takes, and write checks the joined text against the limit while joining it. The report names at most 4,096 written files and sets writtenMore when there were more. - Errors a script sees are translated in every complete message catalog. --- apps/vectorcraft-cli/src/main.rs | 6 +- apps/vectorcraft/src/host_services.rs | 48 +- apps/vectorcraft/src/main.rs | 1 + apps/vectorcraft/src/prefs_dir.rs | 9 + crates/engine/Cargo.toml | 5 +- crates/engine/src/cmd/scripts.rs | 66 +- crates/engine/src/file_access.rs | 254 +++- crates/engine/src/lib.rs | 4 + crates/engine/src/script/files.rs | 1339 +++++++++++++++++++++- crates/engine/src/script/mod.rs | 165 ++- crates/engine/src/session/documents.rs | 1 + crates/engine/src/tests/script_io.rs | 1259 +++++++++++++++++++- crates/engine/src/tests/script_run.rs | 140 ++- crates/js/src/builtins.rs | 2 + crates/js/src/file_classes.rs | 362 +++++- crates/js/src/host.rs | 7 +- crates/js/src/host_tests.rs | 18 + crates/js/src/interp.rs | 15 + crates/js/src/realm.rs | 18 +- crates/ui-egui/src/app.rs | 2 + crates/ui-egui/src/dialogs.rs | 4 + crates/ui-egui/src/dialogs/script_run.rs | 214 +++- crates/ui-egui/src/i18n/bg.tsv | 7 + crates/ui-egui/src/i18n/bs.tsv | 7 + crates/ui-egui/src/i18n/ca.tsv | 30 +- crates/ui-egui/src/i18n/cs.tsv | 30 +- crates/ui-egui/src/i18n/da.tsv | 7 + crates/ui-egui/src/i18n/de.tsv | 30 +- crates/ui-egui/src/i18n/el.tsv | 30 +- crates/ui-egui/src/i18n/es.tsv | 30 +- crates/ui-egui/src/i18n/fi.tsv | 30 +- crates/ui-egui/src/i18n/fr.tsv | 30 +- crates/ui-egui/src/i18n/hi.tsv | 30 +- crates/ui-egui/src/i18n/hu.tsv | 30 +- crates/ui-egui/src/i18n/id.tsv | 7 + crates/ui-egui/src/i18n/it.tsv | 30 +- crates/ui-egui/src/i18n/ja.tsv | 30 +- crates/ui-egui/src/i18n/ka.tsv | 30 +- crates/ui-egui/src/i18n/ko.tsv | 30 +- crates/ui-egui/src/i18n/nl.tsv | 7 + crates/ui-egui/src/i18n/pl.tsv | 30 +- crates/ui-egui/src/i18n/pt-br.tsv | 30 +- crates/ui-egui/src/i18n/ru.tsv | 30 +- crates/ui-egui/src/i18n/sv.tsv | 30 +- crates/ui-egui/src/i18n/tests.rs | 66 +- crates/ui-egui/src/i18n/tr.tsv | 30 +- crates/ui-egui/src/i18n/uk.tsv | 30 +- crates/ui-egui/src/i18n/vi.tsv | 30 +- crates/ui-egui/src/i18n/zh-hans.tsv | 30 +- crates/ui-egui/src/i18n/zh-hant.tsv | 30 +- crates/ui-egui/src/lib.rs | 5 + crates/ui-egui/src/picks.rs | 31 +- crates/ui-egui/src/script_runs.rs | 11 +- crates/ui-egui/src/services.rs | 11 + crates/ui-egui/src/tests/picks.rs | 7 +- crates/ui-egui/src/tests/script_run.rs | 327 +++++- docs/mcp.md | 118 +- docs/target-app-parity.md | 3 +- 58 files changed, 4948 insertions(+), 265 deletions(-) diff --git a/apps/vectorcraft-cli/src/main.rs b/apps/vectorcraft-cli/src/main.rs index 0d4deca36f..9e2a63a9c1 100644 --- a/apps/vectorcraft-cli/src/main.rs +++ b/apps/vectorcraft-cli/src/main.rs @@ -238,10 +238,12 @@ fn main() -> ExitCode { /// A headless session that remembers what the user keeps between runs: the PDF presets saved, the /// ICC profiles loaded, the plug-ins installed (#2168, #2174, #2541), the custom dictionary's words (#4936) and the Color Settings (#6335), in the folders /// and files next to the preferences that the desktop app uses too, and lists the scripts of the Scripts folder there -/// (`script.listInstalled`) and starts new documents from the New Document profiles there. `VECTORCRAFT_NO_PREFS` and -/// `VECTORCRAFT_CONFIG_DIR` apply as they do there. +/// (`script.listInstalled`), keeps each script's `Folder.userData` in the Script Data folder there and starts new +/// documents from the New Document profiles there. `VECTORCRAFT_NO_PREFS` and `VECTORCRAFT_CONFIG_DIR` apply as they +/// do there. fn with_stores(mut h: Headless) -> Headless { prefs_dir::attach_scripts_dir(&mut h.session); + prefs_dir::attach_script_data(&mut h.session); prefs_dir::attach_new_doc_profiles(&mut h.session); prefs_dir::attach_profile_store(&mut h.session); prefs_dir::attach_color_settings(&mut h.session); diff --git a/apps/vectorcraft/src/host_services.rs b/apps/vectorcraft/src/host_services.rs index 03a9b8848c..8622a19223 100644 --- a/apps/vectorcraft/src/host_services.rs +++ b/apps/vectorcraft/src/host_services.rs @@ -71,7 +71,7 @@ fn open_extensions(exts: &[impl AsRef], any_case: bool) -> Vec { /// `d` set up for `request`: its title, file types, folder and suggested name. fn dialog_for(d: D, request: &PickRequest) -> D { let pick = match request { - PickRequest::Open(pick) | PickRequest::Save(pick) => pick, + PickRequest::Open(pick) | PickRequest::Save(pick) | PickRequest::OpenFiles(pick) => pick, PickRequest::OpenMany => { return fileio::place_filters().fold(d.title(vectorcraft_ui_egui::i18n::t("Place")), |d, (name, exts)| { d.filter( @@ -81,8 +81,9 @@ fn dialog_for(d: D, request: &PickRequest) -> D { }); } PickRequest::Folder => return d, + PickRequest::FolderAt(folder) => return d.folder(folder), }; - let any_case = CASE_SENSITIVE_FILTERS && matches!(request, PickRequest::Open(_)); + let any_case = CASE_SENSITIVE_FILTERS && matches!(request, PickRequest::Open(_) | PickRequest::OpenFiles(_)); let d = pick.filters.iter().fold(d, |d, (name, exts)| { d.filter( vectorcraft_ui_egui::i18n::tr_ctx(vectorcraft_ui_egui::i18n::current(), "file-filter", name.as_str()), @@ -96,6 +97,37 @@ fn dialog_for(d: D, request: &PickRequest) -> D { if pick.name.is_empty() { d } else { d.file_name(&pick.name) } } +#[cfg(test)] +#[test] +fn a_folder_picker_asked_for_a_folder_starts_there() { + /// The settings a dialog was given, by name. + #[derive(Default)] + struct Recorded(Vec); + impl DialogSettings for Recorded { + fn parent(self, _: &winit::window::Window) -> Self { + self + } + fn title(mut self, title: &str) -> Self { + self.0.push(format!("title {title}")); + self + } + fn filter(mut self, name: &str, _: &[impl ToString]) -> Self { + self.0.push(format!("filter {name}")); + self + } + fn folder(mut self, folder: &str) -> Self { + self.0.push(format!("folder {folder}")); + self + } + fn file_name(mut self, name: &str) -> Self { + self.0.push(format!("name {name}")); + self + } + } + assert_eq!(dialog_for(Recorded::default(), &PickRequest::FolderAt("/a/b".into())).0, ["folder /a/b"]); + assert!(dialog_for(Recorded::default(), &PickRequest::Folder).0.is_empty()); +} + /// A native file dialog for `request` over `parent` (on Linux the portal then shows it over the /// window and keeps it in front). #[cfg(not(target_os = "macos"))] @@ -128,9 +160,9 @@ fn show_dialog(dialog: rfd::FileDialog, request: &PickRequest, parent: &Parent) } let paths = match request { PickRequest::Open(_) => dialog.pick_file().into_iter().collect(), - PickRequest::OpenMany => dialog.pick_files().unwrap_or_default(), + PickRequest::OpenMany | PickRequest::OpenFiles(_) => dialog.pick_files().unwrap_or_default(), PickRequest::Save(_) => dialog.save_file().into_iter().collect(), - PickRequest::Folder => dialog.pick_folder().into_iter().collect(), + PickRequest::Folder | PickRequest::FolderAt(_) => dialog.pick_folder().into_iter().collect(), }; paths.into_iter().map(|p| p.to_string_lossy().to_string()).collect() } @@ -313,7 +345,7 @@ fn start_pick(request: PickRequest, parent: &Parent, ui: &egui::Context) -> Opti let picked = dialog.pick_file(); Box::pin(async move { picked.await.iter().map(path).collect() }) } - PickRequest::OpenMany => { + PickRequest::OpenMany | PickRequest::OpenFiles(_) => { let picked = dialog.pick_files(); Box::pin(async move { picked.await.unwrap_or_default().iter().map(path).collect() }) } @@ -332,7 +364,7 @@ fn start_pick(request: PickRequest, parent: &Parent, ui: &egui::Context) -> Opti // on that nil; treat the pick as cancelled instead (#5980). Err(()) => Box::pin(async move { Vec::new() }), }, - PickRequest::Folder => { + PickRequest::Folder | PickRequest::FolderAt(_) => { let picked = dialog.pick_folder(); Box::pin(async move { picked.await.iter().map(path).collect() }) } @@ -353,7 +385,7 @@ pub(crate) fn services(parent: Parent, ui: egui::Context) -> Services { .and_then(|w| w.window_handle().ok()) .is_some_and(|h| matches!(h.as_raw(), RawWindowHandle::Xlib(_) | RawWindowHandle::Xcb(_))); let (clip, clip_probe) = (parent.clone(), parent.clone()); - let (p1, p2, p3, p4, p5) = (parent.clone(), parent.clone(), parent.clone(), parent.clone(), parent); + let (p1, p2, p3, p4, p5, p6, p7) = (parent.clone(), parent.clone(), parent.clone(), parent.clone(), parent.clone(), parent.clone(), parent); #[cfg(any(target_os = "macos", target_os = "linux"))] let sampled_ui = ui.clone(); #[cfg(target_os = "linux")] @@ -361,6 +393,7 @@ pub(crate) fn services(parent: Parent, ui: egui::Context) -> Services { Services { pick_open: Some(Box::new(move |pick: &FilePick| pick_now(PickRequest::Open(pick.clone()), &p1).into_iter().next())), pick_open_multi: Some(Box::new(move || pick_now(PickRequest::OpenMany, &p2))), + pick_open_files: Some(Box::new(move |pick: &FilePick| pick_now(PickRequest::OpenFiles(pick.clone()), &p6))), pick_save: Some(Box::new(move |pick: &FilePick| pick_now(PickRequest::Save(pick.clone()), &p3).into_iter().next())), // Linux shows dialogs on a thread of their own (#592), macOS as sheets (#867); Windows // dialogs run the window's events while they are open. @@ -407,6 +440,7 @@ pub(crate) fn services(parent: Parent, ui: egui::Context) -> Services { // Edit Original of a raster image with Use System Defaults for Edit Original off (#5236). open_in_photocraft: Some(Box::new(open_in_photocraft)), pick_folder: Some(Box::new(move || pick_now(PickRequest::Folder, &p4).into_iter().next())), + pick_folder_at: Some(Box::new(move |start: &str| pick_now(PickRequest::FolderAt(start.to_string()), &p7).into_iter().next())), // Sample Color from Screen: the system's color sampler. #[cfg(target_os = "macos")] screen_color: Some(mac_screen_color::sampler(sampled_ui)), diff --git a/apps/vectorcraft/src/main.rs b/apps/vectorcraft/src/main.rs index c2b40e37e6..92088fd67b 100644 --- a/apps/vectorcraft/src/main.rs +++ b/apps/vectorcraft/src/main.rs @@ -479,6 +479,7 @@ fn main() -> std::process::ExitCode { // File › Scripts lists the scripts of the Scripts folder next to the preferences. prefs_dir::attach_scripts_dir(&mut session); prefs_dir::attach_new_doc_profiles(&mut session); + prefs_dir::attach_script_data(&mut session); let mut app = VectorcraftApp::new(session, services(cc.winit_window().cloned(), cc.egui_ctx.clone())); app.set_startup_update_check(true); load_prefs(&mut app, saved); diff --git a/apps/vectorcraft/src/prefs_dir.rs b/apps/vectorcraft/src/prefs_dir.rs index 11afcfe121..80b42ef219 100644 --- a/apps/vectorcraft/src/prefs_dir.rs +++ b/apps/vectorcraft/src/prefs_dir.rs @@ -73,6 +73,15 @@ pub fn attach_new_doc_profiles(session: &mut vectorcraft_engine::Session) { } } +/// Keep each script's `Folder.userData` in the `Script Data` folder, and the file access people +/// allow scripts with Always in `Script Grants.json` beside it. Both are made when a script first +/// needs them. +pub fn attach_script_data(session: &mut vectorcraft_engine::Session) { + if let Some(dir) = store_dir("Script Data") { + session.attach_script_data(dir); + } +} + /// Take the saved PDF presets from the `PDF Presets` folder (#2168), and keep the ones saved from /// now on there. After the preferences were restored: the folder is the one place the presets live. pub fn attach_pdf_preset_store(session: &mut vectorcraft_engine::Session) { diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 0fccbcdecb..264581e3ed 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -67,8 +67,9 @@ log = { workspace = true } [target.'cfg(unix)'.dependencies] rustix = { workspace = true, features = ["std", "process"] } -# Whether a recovery area's lock file is still the one that was opened (`FolderStore::still_named`). -# Already in Cargo.lock (walkdir), so this adds no new crate. +# Whether a recovery area's lock file is still the one that was opened (`FolderStore::still_named`), +# and whether two paths a script names are one file (`script::files`). Already in Cargo.lock +# (walkdir), so this adds no new crate. [target.'cfg(windows)'.dependencies] same-file = "1.0.6" diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index f5edf1f91d..623ab8a87f 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -32,7 +32,7 @@ pub fn specs() -> Vec { "Run Script", [], None, - "{path?: a .js or .jsx file | source?: the script's text (exactly one of the two), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file being run (empty for text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; vc.args is args. Before anything runs, the script's preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine name runs the script in the named engine, whose globals and functions stay for the next run that names it until script.engine.drop drops it or the session ends (script.engines lists them; a name of letters, digits and _ not starting with a digit, or a quoted one of 1 to 64 bytes without control characters, matched as written; only in the script itself, once, before its code and #include lines; main, and a script without the line, get a new engine each run; a session keeps 8 named engines, a ninth name is refused, each has 64 MiB of heap, and an uncaught error, a limit or script.stop keeps the globals the run set while the documents go back; host functions kept in a global act for the run that calls them; an error in code an earlier run compiled is at that run's file, line and column, within 8 MiB of source maps kept for each engine, the oldest going first; not on the web); #engine is refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that leads out (a JSINCLUDE folder outside is passed over); a script given as text reads none. File(path) and Folder(path) name files and folders and read them in the same folders, and inside the automation read roots when they are set: exists, length, created, modified, getFiles(mask or function; at most 2048 entries), resolve, and open('r') with read, readln, readch, seek, tell and close; a path outside, a network or device path and a link that leads out give false or null with error \"Script file access denied\", a file is read whole at most 8 MiB (checked from its size first) and a run reads at most 32 MiB, and writing, the file dialogs and execute return false or null with error set. An error in another file is at that file's line and column; vc.api.version and vc.api.has(feature) describe the API. The run is one transaction: on success each changed document gets one undo step, Run Script, and each preference it changed keeps its value, and on an uncaught error, a limit or script.stop every open document and the session go back as they were; files a command wrote before that stay written and are named. While it runs, other commands that change anything end with a busy error. Commands that change anything outside the documents (script.*, except script.check, plugin.*, prefs.*, actionSet.*, shortcutSet.*, help.*, print.*, library.*, importMatches.*, edit.undoGroup.*, file.recovery.*, stroke.widthProfile.*, saving, importing or deleting a preset, text.addFontFiles, text.findFontFiles, text.rescanFonts, links.findFiles, file.place.queue, color.loadProfile, color.removeProfile, file.print, view.proofSetup, view.proofColors, view.overprintPreview, view.separationsPreview) throw. VectorCraft's own limits: 8 MiB of source a file and 32 MiB in all, 64 included or evaluated files 16 deep, 1024 paths looked up for them, 256 MiB of heap (128 MiB on the web), 2000000 host calls, 200000000 instructions without a pause, 64 levels, 16 MiB and 1048576 entries for a value crossing to or from a command, 10000 log entries and 4 MiB of log, 16 KiB of a dialog's message, 256 bytes of its title and 16 KiB of a prompt's preset (past these a RangeError), and 100000 objects and 512 MiB of new document data, past which a person is asked to continue or stop and a run with nobody to ask ends → {ok: true, name, changed: [document names], written: [paths], log: [values], fuelUsed, hostCalls, runTimeMs (the time the script ran, its commands included, waits between frames and for a person's answer left out; 0 without a clock), timingAvailable (false on the web), hostCallCounts: {vcRun, documentReads, commandListReads, vcLog, consoleWrites, fileCalls, fileExecutes}, slowestCommands: [{id, calls, totalMs, maxMs}] (at most 5, the longest in all first, then by id), console: {lines: [text], droppedLines, truncatedLines} (the run's own output, vc.log lines and error), dialogs: [{kind, message, title, errorIcon (alert), noAsDefault (confirm), preset (prompt), answer: \"ok\" | true | false | text | null | \"stop\" | \"missing\"}] (in the order they opened, at most 10000 and 1 MiB), dialogCount, dialogsTruncated}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport; a run that fails ends with its error, and its report there also has kind, message, line, column, file (when the error is in another file than the script, or in code an earlier run of its engine compiled), fuelLeft, fuelUsed, hostCalls and the fields above", + "{path?: a .js or .jsx file | source?: the script's text (exactly one of the two), name?: the name errors and the report use (default: the script's #script line, else the path's file name, or \"script\"), args?: {…} (at most 1 MiB as JSON; vc.args in the script), answers?: [{kind: alert|confirm|prompt, value: \"ok\" (alert) | true or false (confirm) | text or null (prompt)}] (for a run with nobody to ask: the answers to its dialogs, in order; at most 10000 and 1 MiB as JSON; refused in the app, where the person answers; an empty object is an empty list), maxFuel?: whole number from 1 to 100000000000 (instructions in all; default 1000000000)} run a JavaScript file against the open documents, through the vc object: vc.run(id, params) runs a command and returns its result, a failed command throws an error the script can catch and puts back the documents and the session state it changed, while any file it wrote stays written and is named; vc.document is a snapshot of the active document or null; vc.commands lists the commands a script may run; vc.log(value) adds to the report and the Script Console (script.console); $.write(...values) writes the values to the Script Console as String(value) gives them, and $.writeln(...values) does the same and ends the line; $.evalFile(path, timeout?) runs a file with the same globals and returns its last value (timeout, in milliseconds from 0, is taken and not waited on), $.fileName is the file being run (empty for text), $.includePath the #includepath list and $.engineName the engine's name (VectorCraft without #targetengine); alert(message[, title, errorIcon]), confirm(message[, noAsDflt, title]) and prompt(message, preset[, title]) open a dialog with a Stop button (default title \"Script Alert\"; message and preset as String(value) gives them; errorIcon and noAsDflt as Boolean(value) gives them; No is the default with noAsDflt): alert returns undefined, confirm true for Yes and false for No, prompt the field's text for OK and null for Cancel; in the app the run waits at the call for the person's answer and Stop ends it as script.stop does, a dialog cannot open inside a callback of a built-in, a getter, a conversion or a file $.evalFile runs and throws there (an #include file's code is the script's own and can), and a run with nobody to ask takes the next of answers, and ends when none is left or the next is for another kind of dialog, or when the script ends with answers unused; vc.args is args. Before anything runs, the script's preprocessor lines (# or //@ at the start of a line, outside strings and comments) are read: #include \"file\" and //@include put that file's text in place of the line, looked for beside the file that includes it, then in each #includepath folder in turn (separated by ;, relative to that file's folder; a later #includepath replaces the list), then in each JSINCLUDE folder; #script names the run; #target takes any value and changes nothing; #strict on makes an assignment to a read-only or getter-only property, or a new property on an object that is not extensible (preventExtensions, seal, freeze, vc, $), throw a TypeError, without the rest of ES5 strict mode, and #strict off turns that off (the last #strict line of the script and its includes sets the run; off without one; a $.evalFile file's own line holds for its code); #targetengine name runs the script in the named engine, whose globals and functions stay for the next run that names it until script.engine.drop drops it or the session ends (script.engines lists them; a name of letters, digits and _ not starting with a digit, or a quoted one of 1 to 64 bytes without control characters, matched as written; only in the script itself, once, before its code and #include lines; main, and a script without the line, get a new engine each run; a session keeps 8 named engines, a ninth name is refused, each has 64 MiB of heap, and an uncaught error, a limit or script.stop keeps the globals the run set while the documents go back; host functions kept in a global act for the run that calls them; an error in code an earlier run compiled is at that run's file, line and column, within 8 MiB of source maps kept for each engine, the oldest going first; not on the web); #engine is refused as unsupported, any other #name as unknown, and another //@name is a comment. A script run from a file reads its includes and $.evalFile's files only in that file's folder and the folders below it, refusing a path with a .. name or a link that leads out (a JSINCLUDE folder outside is passed over); a script given as text reads none. File(path) and Folder(path) name files and folders and read them in the same folders, and inside the automation read roots when they are set: exists, length, created, modified, getFiles(mask or function; at most 2048 entries), resolve, and open('r') with read, readln, readch, seek, tell and close; a path outside, a network or device path and a link that leads out give false or null with error \"Script file access denied\", a file is read whole at most 8 MiB (checked from its size first) and a run reads at most 32 MiB. A script writes only in Folder.temp (a folder for the run, deleted when it ends), Folder.userData (for a script run from a file, a folder of its own in the Script Data folder next to the settings, kept between runs; for text, one in Folder.temp) and what a person allowed it in a file dialog, inside the automation write roots when they are set, and never in the folder that holds the settings outside its own Folder.userData: open('w') empties or makes the file, open('e') opens a file that is there and open('a') opens it at its end; write(...values) and writeln(...values) (with lineFeed's line end: Windows CRLF, Macintosh CR, Unix LF) encode in the file's encoding (ASCII and ISO-8859-1 refuse a character they cannot hold, BINARY writes each character's low byte), and the file is written at close or when the run ends (a file that close could not write is written again then, and a run that would succeed fails when a file it left open cannot be written), at most 8 MiB a file and 32 MiB a run, which counts what setting length adds and what copy writes once for the file and once more for each object that has it open (write turns its values into text only for an open file and gives false with \"Script file exceeds 8 MiB\" past 16777216 UTF-16 code units); copy(target) replaces a file that is there, remove() deletes a file or an empty folder at once, rename(name) takes a name without a folder that is not in use, Folder.create() makes the folder and the folders above it, and none of them when one is outside the places the script writes, and setting length or readonly changes the file; setting hidden, createAlias and execute return false with error set. In the app, File.openDialog(prompt, filter, multiSelect), File.saveDialog(prompt, filter) and Folder.selectDialog(prompt), and the objects' openDlg, saveDlg and selectDlg, wait for the person, who picks and then allows the script that file or folder once, always (kept in Script Grants.json next to the settings for that script file with that text and the files it includes, by their SHA-256, and for the sources the run evaluated, files $.evalFile ran and strings given to eval and Function, so a later run loses the grant before it evaluates another source, or when its named engine holds code the grant was not kept for, and only while its path is still the real path that was allowed, not one a link now leads elsewhere; script.grants lists them and script.grants.revoke removes them), or denies it, which gives null (a string filter such as \"Text:*.txt;All files:*.*\" gives the file types the dialog shows, *.ext patterns and * or *.* for every file; a filter that is a function is called with a File for each file picked, and the files it gives a false value for are left out, null when none is left; multiSelect gives an array of the files picked, at most 2048); only the person at the keyboard allows a file or folder, and a control request or synthetic input that allows one is refused; an open grant reads the file, a save grant reads and writes it, and a folder grant reads and writes everything inside it; a run with nobody to ask gets null with error \"Script file dialogs need a person to answer them\", and a dialog inside a callback throws. Each file a script writes is in written, also after a run that failed, at most 4096 files, with writtenMore: true when it wrote more. A command vc.run runs reads and writes files only where the script's File and Folder objects may and in the files the open documents were opened from or saved to, and fails with \"Script file access denied\" elsewhere, saving into a user library of swatches, brushes, symbols or graphic styles included (reading the app's own libraries is allowed). An error in another file is at that file's line and column; vc.api.version and vc.api.has(feature) describe the API. The run is one transaction: on success each changed document gets one undo step, Run Script, and each preference it changed keeps its value, and on an uncaught error, a limit or script.stop every open document and the session go back as they were; files a command wrote before that stay written and are named. While it runs, other commands that change anything end with a busy error. Commands that change anything outside the documents (script.*, except script.check, plugin.*, prefs.*, actionSet.*, shortcutSet.*, help.*, print.*, library.*, importMatches.*, edit.undoGroup.*, file.recovery.*, stroke.widthProfile.*, saving, importing or deleting a preset, text.addFontFiles, text.findFontFiles, text.rescanFonts, links.findFiles, file.place.queue, color.loadProfile, color.removeProfile, file.print, view.proofSetup, view.proofColors, view.overprintPreview, view.separationsPreview) throw. VectorCraft's own limits: 8 MiB of source a file and 32 MiB in all, 64 included or evaluated files 16 deep, 1024 paths looked up for them, 256 MiB of heap (128 MiB on the web), 2000000 host calls, 200000000 instructions without a pause, 64 levels, 16 MiB and 1048576 entries for a value crossing to or from a command, 10000 log entries and 4 MiB of log, 16 KiB of a dialog's message, 256 bytes of its title and 16 KiB of a prompt's preset (past these a RangeError), and 100000 objects and 512 MiB of new document data, past which a person is asked to continue or stop and a run with nobody to ask ends → {ok: true, name, changed: [document names], written: [paths], writtenMore?: true, log: [values], fuelUsed, hostCalls, runTimeMs (the time the script ran, its commands included, waits between frames and for a person's answer left out; 0 without a clock), timingAvailable (false on the web), hostCallCounts: {vcRun, documentReads, commandListReads, vcLog, consoleWrites, fileCalls, fileExecutes}, slowestCommands: [{id, calls, totalMs, maxMs}] (at most 5, the longest in all first, then by id), console: {lines: [text], droppedLines, truncatedLines} (the run's own output, vc.log lines and error), dialogs: [{kind, message, title, errorIcon (alert), noAsDefault (confirm), preset (prompt), answer: \"ok\" | true | false | text | null | \"stop\" | \"missing\"}] (in the order they opened, at most 10000 and 1 MiB), dialogCount, dialogsTruncated}, or, in the app, {running: true, name} and the report later in ui.inspect's scriptReport; a run that fails ends with its error, and its report there also has kind, message, line, column, file (when the error is in another file than the script, or in code an earlier run of its engine compiled), fuelLeft, fuelUsed, hostCalls and the fields above", always, run ), @@ -90,6 +90,24 @@ pub fn specs() -> Vec { always, list_installed ), + cmd!( + query "script.grants", + "List Script File Permissions", + [], + None, + "{} the file access people allowed scripts with Always in a file dialog, kept in Script Grants.json next to the settings: each for one script file with one text and the files it includes (their SHA-256), so a changed or moved script, or a changed included file, has none, and with the SHA-256 of each source the run that kept it evaluated (files $.evalFile ran, strings given to eval and Function; at most 256), so a run loses it before it evaluates other code, or when its named engine holds code the grant was not kept for; at most 4096 → {grants: [{script: the script file's path, sha256, code: [SHA-256 of each evaluated source, of its UTF-16 code units in little-endian order], path: the file or folder allowed, write: it may be written, folder: the grant is a folder's, with everything in it (a file's grant is its own path only)}], file: the grants file's path | null (a session without a settings folder, and the web)}", + always, + grants + ), + cmd!( + query "script.grants.revoke", + "Revoke Script File Permissions", + [], + None, + "{script?: a script file's path, path?: an allowed file or folder's path, all?: true (exactly one of all and the other two)} remove the kept file access of that script, of that path, of both together, or every one; a path is matched as script.grants lists it, after its links are followed; refused with the busy error while a script runs, as the run keeps the grants it started with → {removed: how many}", + always, + grants_revoke + ), cmd!( query "script.check", "Check Script", @@ -228,6 +246,18 @@ impl Session { self.scripts_dir = Some(dir); } + /// Keep each script's data folder (`Folder.userData`) in the folder `dir`, and the file access + /// people allow scripts with Always in [`script::files::GRANTS_FILE`] beside it. The folders are + /// made when a script first needs them. + pub fn attach_script_data(&mut self, dir: std::path::PathBuf) { + self.script_data_dir = Some(dir); + } + + /// The folder of the scripts' data folders ([`Session::attach_script_data`]); none on the web. + pub fn script_data_dir(&self) -> Option<&std::path::Path> { + self.script_data_dir.as_deref().filter(|_| !cfg!(target_arch = "wasm32")) + } + /// The Scripts folder ([`Session::attach_scripts_dir`]); none on the web, which has no folders. pub fn scripts_dir(&self) -> Option<&std::path::Path> { self.scripts_dir.as_deref().filter(|_| !cfg!(target_arch = "wasm32")) @@ -308,6 +338,40 @@ fn list_installed(s: &mut Session, _: &Value) -> Result { Ok(json!({"folder": folder, "scripts": scripts, "truncated": listing.truncated, "unreadable": listing.unreadable})) } +fn grants(s: &mut Session, _: &Value) -> Result { + let Some(dir) = s.script_data_dir() else { return Ok(json!({"grants": [], "file": null})) }; + let file = dir.with_file_name(script::files::GRANTS_FILE); + Ok(json!({"grants": script::files::stored_grants(dir), "file": file.to_string_lossy()})) +} + +fn grants_revoke(s: &mut Session, p: &Value) -> Result { + const C: &str = "script.grants.revoke"; + let path_of = |key: &str| match p.get(key) { + None => Ok(None), + Some(Value::String(t)) if !t.is_empty() => { + Ok(Some(std::fs::canonicalize(t).map_or_else(|_| t.clone(), |real| crate::cmd::findfiles::plain(real).to_string_lossy().into_owned()))) + } + Some(_) => Err(bad(C, format!("`{key}` must be a path"))), + }; + let (script_path, path) = (path_of("script")?, path_of("path")?); + let all = match p.get("all") { + None => false, + Some(Value::Bool(true)) => true, + Some(_) => return Err(bad(C, "`all` must be true")), + }; + if all == (script_path.is_some() || path.is_some()) { + return Err(bad(C, "give `all`, or `script` and `path` or one of them")); + } + // A running script holds the grants it started with until it ends. + if s.script_running() { + return Err(EngineError::Busy); + } + let Some(dir) = s.script_data_dir() else { return Ok(json!({"removed": 0})) }; + let removed = script::files::revoke_grants(dir, script_path.as_deref(), path.as_deref()) + .map_err(|e| EngineError::Other(format!("the script file permissions could not be saved: {e}")))?; + Ok(json!({"removed": removed})) +} + /// The folder a script is in, which its included files are read from. struct Folder { dir: std::path::PathBuf, diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index 6ca724d810..9aaeb58dab 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -25,7 +25,9 @@ //! guard against other programs on the computer. //! //! [`ScriptScope`] holds the folders a running script's own files (its includes and `$.evalFile`) -//! are read from, inside the roots. +//! are read from, and the places its `File` and `Folder` objects read and write, inside the roots. +//! [`ScriptGate`] holds the same places for the commands the script runs with `vc.run`, with the +//! files of the open documents. use std::cell::RefCell; use std::ffi::OsString; @@ -185,22 +187,87 @@ pub fn unconfined(f: impl FnOnce() -> T) -> T { with_scope(Some(Scope::Unconfined), f) } -/// This thread's scope, to carry to work it hands to another thread ([`ScopeHandle::run`]). +/// This thread's scope, with the gate of the script command it runs, to carry to work it hands to +/// another thread ([`ScopeHandle::run`]). #[derive(Clone, Debug)] -pub struct ScopeHandle(Option); +pub struct ScopeHandle(Option, Option>); impl ScopeHandle { /// The scope of the calling thread. pub fn capture() -> Self { - Self(SCOPE.with(|s| s.borrow().clone())) + Self(SCOPE.with(|s| s.borrow().clone()), GATE.with(|g| g.borrow().clone())) } /// Run `f` in the captured scope. pub fn run(self, f: impl FnOnce() -> T) -> T { - with_scope(self.0, f) + let Self(scope, gate) = self; + with_gate(gate, || with_scope(scope, f)) } } +/// What a command a running script runs (`vc.run`) may read and write: the places the script's +/// `File` and `Folder` objects may ([`ScriptScope`]), and the files the documents open in the app +/// were opened from or saved to. The automation roots apply as well. A path refused by its name +/// alone ([`ScriptScope::refused_by_name`]) is refused here too. +#[derive(Clone, Debug)] +pub(crate) struct ScriptGate { + pub(crate) read: ScriptScope, + pub(crate) write: ScriptScope, + /// The paths of the open documents' files, as the documents hold them. + pub(crate) documents: Vec, +} + +impl ScriptGate { + fn check(&self, path: &str, access: Access) -> Result<(), String> { + let real = if ScriptScope::refused_by_name(Path::new(path)) { None } else { resolve(path).ok() }; + let allowed = real.is_some_and(|real| { + let scoped = match access { + Access::Read => self.read.allows(&real) || self.write.allows(&real), + Access::Write => self.write.allows(&real), + }; + scoped || self.documents.iter().any(|d| resolve(d).is_ok_and(|d| d == real)) + }); + if allowed { Ok(()) } else { Err(format!("Script file access denied: {path}")) } + } +} + +thread_local! { + /// The gate of the script command this thread runs ([`with_script_gate`]). + static GATE: RefCell>> = const { RefCell::new(None) }; +} + +/// Puts the gate it replaced back when dropped (also when `f` panics). +struct RestoreGate(Option>); + +impl Drop for RestoreGate { + fn drop(&mut self) { + let previous = self.0.take(); + GATE.with(|g| *g.borrow_mut() = previous); + } +} + +fn with_gate(gate: Option>, f: impl FnOnce() -> T) -> T { + let _restore = RestoreGate(GATE.with(|g| g.replace(gate))); + f() +} + +/// Runs `f`, a command a script runs, with `gate` in force on this thread: every path it reads or +/// writes must pass the gate as well as the automation roots. Reads of the app's own folders, +/// inside [`unconfined`], are not checked; writes there are, so a script's command does not save +/// into the app's libraries. +pub(crate) fn with_script_gate(gate: ScriptGate, f: impl FnOnce() -> T) -> T { + with_gate(Some(Arc::new(gate)), f) +} + +/// May `path` be read (or written) by the script command this thread runs? Always outside one, +/// and for a read inside [`unconfined`]. +fn check_gate(path: &str, access: Access) -> Result<(), String> { + if matches!(access, Access::Read) && SCOPE.with(|s| matches!(*s.borrow(), Some(Scope::Unconfined))) { + return Ok(()); + } + GATE.with(|g| g.borrow().clone()).map_or(Ok(()), |g| g.check(path, access)) +} + /// The roots in force on this thread, if any. pub fn current() -> Option> { match SCOPE.with(|s| s.borrow().clone()) { @@ -210,9 +277,11 @@ pub fn current() -> Option> { } } -/// May `path` be read here? Always, without roots in force. +/// May `path` be read here? Always, without roots in force and outside a script's command +/// ([`with_script_gate`]). pub fn check_read(path: &str) -> Result<(), String> { - current().map_or(Ok(()), |r| r.check(path, Access::Read)) + current().map_or(Ok(()), |r| r.check(path, Access::Read))?; + check_gate(path, Access::Read) } /// Is `path`, under a read root, written as an absolute path of another platform: outside Windows, one @@ -229,9 +298,11 @@ pub fn is_path_key(key: &str) -> bool { matches!(key, "path" | "paths" | "file" | "files" | "folder") || ["Path", "Paths", "File", "Files", "Folder"].iter().any(|end| key.ends_with(end)) } -/// May `path` be written here? Always, without roots in force. +/// May `path` be written here? Always, without roots in force and outside a script's command +/// ([`with_script_gate`]). pub fn check_write(path: &str) -> Result<(), String> { current().map_or(Ok(()), |r| r.check(path, Access::Write))?; + check_gate(path, Access::Write)?; WRITES.with(|w| { if let Some(paths) = w.borrow_mut().as_mut() && !paths.iter().any(|(p, _)| p == path) @@ -323,6 +394,12 @@ fn inside(path: &Path, root: &Path) -> bool { root.components().all(|r| path.next().is_some_and(|p| same_component(p, r))) } +/// Is `path` `root` or inside it, both with their links followed, compared as [`AutomationRoots`] +/// compares them? +pub(crate) fn path_inside(path: &Path, root: &Path) -> bool { + inside(path, root) +} + fn same_component(a: Component, b: Component) -> bool { if a == b { return true; @@ -374,10 +451,21 @@ fn windows_name_refusal(path: &str) -> Option<&'static str> { /// The file opened is the path with its links followed, and after reading, the path is followed /// again and must still lead to the same place: a process that changes the folders twice in between /// can still win that race. +/// +/// A scope can also be given more folders ([`ScriptScope::add`]) and single files +/// ([`ScriptScope::add_file`]), and folders it keeps out even inside a granted folder +/// ([`ScriptScope::fence`]), each but the places inside it that stay open. A granted file grants its +/// own path only, also when a folder later takes its place. #[derive(Clone, Debug, Default)] pub(crate) struct ScriptScope { /// The granted folders, made absolute with their links followed. roots: Vec, + /// The granted files, made absolute with their links followed. + files: Vec, + /// The folders kept out, with their links followed. + fenced: Vec, + /// The places inside a fenced folder that are not kept out. + open: Vec, } /// Why a script's file was not read. @@ -396,12 +484,62 @@ pub(crate) enum ScriptRead { impl ScriptScope { /// The scope of a script run from a file in folder `dir`: that folder. pub(crate) fn of_folder(dir: &Path) -> Self { - Self { roots: std::fs::canonicalize(dir).ok().into_iter().collect() } + Self { roots: std::fs::canonicalize(dir).ok().into_iter().collect(), ..Self::default() } + } + + /// Grants the folder `real`, a path with its links followed, with everything inside it. + pub(crate) fn add(&mut self, real: PathBuf) { + if !self.roots.contains(&real) { + self.roots.push(real); + } + } + + /// Grants the file `real`, a path with its links followed: that path and nothing below it. + pub(crate) fn add_file(&mut self, real: PathBuf) { + if !self.files.contains(&real) { + self.files.push(real); + } + } + + /// Takes back the grant of the folder (`folder`) or file `real` that [`ScriptScope::add`] or + /// [`ScriptScope::add_file`] gave. + pub(crate) fn remove(&mut self, real: &Path, folder: bool) { + if folder { self.roots.retain(|r| r != real) } else { self.files.retain(|r| r != real) } + } + + /// Is nothing granted? + fn is_empty(&self) -> bool { + self.roots.is_empty() && self.files.is_empty() + } + + /// Keeps the folder `real` (links followed) and everything in it out, but for `open` and the + /// places inside it. + pub(crate) fn fence(&mut self, real: PathBuf, open: &[PathBuf]) { + self.fenced.push(real); + self.open.extend(open.iter().cloned()); + } + + /// Leaves the place `real` (links followed) and everything in it open inside a fenced folder. + pub(crate) fn fence_open(&mut self, real: PathBuf) { + self.open.push(real); + } + + /// The granted folders, with their links followed. + pub(crate) fn roots(&self) -> &[PathBuf] { + &self.roots + } + + /// Is the real path `real` a granted file or inside a granted folder, and not kept out? A place + /// left open counts only inside the fenced folder: one that holds the fenced folder opens none of it. + pub(crate) fn allows(&self, real: &Path) -> bool { + (self.files.iter().any(|f| inside(real, f) && real.components().count() == f.components().count()) + || self.roots.iter().any(|r| inside(real, r))) + && !self.fenced.iter().any(|f| inside(real, f) && !self.open.iter().any(|o| inside(o, f) && inside(real, o))) } /// Is `path` refused by its name alone: a `..` component, a NUL, a Windows device name or /// stream, or a computer on the network? - fn refused_by_name(path: &Path) -> bool { + pub(crate) fn refused_by_name(path: &Path) -> bool { let text = path.to_string_lossy(); text.contains('\0') || path.components().any(|c| c == Component::ParentDir) @@ -411,7 +549,7 @@ impl ScriptScope { /// The real path of the file at `path` and its first `max` bytes, at most. pub(crate) fn read(&self, path: &Path, max: usize) -> Result<(PathBuf, Vec), ScriptRead> { use std::io::Read; - if self.roots.is_empty() || Self::refused_by_name(path) || check_read(&path.to_string_lossy()).is_err() { + if self.is_empty() || Self::refused_by_name(path) || check_read(&path.to_string_lossy()).is_err() { return Err(ScriptRead::Refused); } let real = match std::fs::canonicalize(path) { @@ -422,7 +560,7 @@ impl ScriptScope { } Err(e) => return Err(ScriptRead::Failed(e.to_string())), }; - if !self.roots.iter().any(|r| inside(&real, r)) { + if !self.allows(&real) { return Err(ScriptRead::Refused); } let file = std::fs::File::open(&real).map_err(|e| ScriptRead::Failed(e.to_string()))?; @@ -450,24 +588,24 @@ impl ScriptScope { self.roots.first().map(|r| crate::cmd::findfiles::plain(r.clone())) } - /// Does the absolute path `path` name a granted folder or a place inside one, by its names - /// alone, without regard to case? A path that does not is refused before the file system is - /// asked anything about it. + /// Does the absolute path `path` name a granted file, a granted folder or a place inside one, + /// by its names alone, without regard to case? A path that does not is refused before the file + /// system is asked anything about it. fn names_inside(&self, path: &Path) -> bool { let lower = |c: Component| c.as_os_str().to_string_lossy().to_lowercase(); - path.is_absolute() - && self.roots.iter().any(|r| { - let root = crate::cmd::findfiles::plain(r.clone()); - let mut names = path.components(); - root.components().all(|c| names.next().is_some_and(|n| lower(n) == lower(c))) - }) + let names_under = |r: &PathBuf| { + let root = crate::cmd::findfiles::plain(r.clone()); + let mut names = path.components(); + root.components().all(|c| names.next().is_some_and(|n| lower(n) == lower(c))) + }; + path.is_absolute() && (self.roots.iter().any(names_under) || self.files.iter().any(names_under)) } /// The real path of the file or folder at `path`, which must be absolute: refused as /// [`ScriptScope::read`] refuses a path, and also when its names alone place it outside every /// granted folder, in which case the file system is not asked about it. pub(crate) fn locate(&self, path: &Path) -> Result { - if self.roots.is_empty() || Self::refused_by_name(path) || !self.names_inside(path) { + if self.is_empty() || Self::refused_by_name(path) || !self.names_inside(path) { return Err(ScriptRead::Refused); } probed(); @@ -484,22 +622,72 @@ impl ScriptScope { } Err(e) => return Err(ScriptRead::Failed(e.to_string())), }; - if !self.roots.iter().any(|r| inside(&real, r)) { + if !self.allows(&real) { return Err(ScriptRead::Refused); } Ok(real) } - /// Is the missing `path` inside a granted folder: does the nearest folder above it that exists - /// lie inside one? On a file system where case matters, `MAIN/x` beside the granted `main` is - /// outside, whether `MAIN` exists or not. A link above it that leads to nothing is outside too, - /// so a script cannot tell whether the folder a link leads to exists. + /// The real path that writing to `path` writes: `path` with its links followed (the last + /// name's too only when `follow`), and for a path that does not exist yet, its nearest existing + /// folder's links followed and the rest appended. Refused as [`ScriptScope::locate`] refuses a + /// path, also when a link on the way leads nowhere, and when the automation write roots in force + /// ([`check_write`]) do not take it. + pub(crate) fn target(&self, path: &Path, follow: bool) -> Result { + if self.is_empty() || Self::refused_by_name(path) || !self.names_inside(path) { + return Err(ScriptRead::Refused); + } + probed(); + if check_write(&path.to_string_lossy()).is_err() { + return Err(ScriptRead::Refused); + } + let (Some(parent), Some(name)) = (path.parent(), path.file_name()) else { return Err(ScriptRead::Refused) }; + let real = match std::fs::symlink_metadata(path) { + Ok(_) if follow => std::fs::canonicalize(path).map_err(|_| ScriptRead::Refused)?, + Ok(m) => { + // Where case does not matter, the name given can differ in case from the name the + // file system keeps, so a file or folder that is not a link is checked under the + // kept name too. + if !m.file_type().is_symlink() && !std::fs::canonicalize(path).is_ok_and(|kept| self.allows(&kept)) { + return Err(ScriptRead::Refused); + } + std::fs::canonicalize(parent).map_err(|_| ScriptRead::Refused)?.join(name) + } + Err(e) if e.kind() == std::io::ErrorKind::NotFound => { + let mut missing = vec![name.to_os_string()]; + let mut at = parent; + loop { + match std::fs::symlink_metadata(at) { + Ok(_) => break, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => { + missing.push(at.file_name().ok_or(ScriptRead::Refused)?.to_os_string()); + at = at.parent().ok_or(ScriptRead::Refused)?; + } + Err(e) => return Err(ScriptRead::Failed(e.to_string())), + } + } + let mut real = std::fs::canonicalize(at).map_err(|_| ScriptRead::Refused)?; + real.extend(missing.iter().rev()); + real + } + Err(e) => return Err(ScriptRead::Failed(e.to_string())), + }; + // The automation write roots take the place written as well as the path named. + if !self.allows(&real) || check_write(&crate::cmd::findfiles::plain(real.clone()).to_string_lossy()).is_err() { + return Err(ScriptRead::Refused); + } + Ok(real) + } + + /// Is the missing `path` inside a granted place: with the links of the nearest folder above it + /// that exists followed, and the rest of its names appended, is it granted? On a file system + /// where case matters, `MAIN/x` beside the granted `main` is outside, whether `MAIN` exists or + /// not. A link above it that leads to nothing is outside too, so a script cannot tell whether + /// the folder a link leads to exists. fn missing_inside(&self, path: &Path) -> bool { - path.ancestors() - .skip(1) - .find(|a| std::fs::symlink_metadata(a).is_ok()) - .and_then(|a| std::fs::canonicalize(a).ok()) - .is_some_and(|real| self.roots.iter().any(|r| inside(&real, r))) + let Some(found) = path.ancestors().skip(1).find(|a| std::fs::symlink_metadata(a).is_ok()) else { return false }; + let (Ok(real), Ok(rest)) = (std::fs::canonicalize(found), path.strip_prefix(found)) else { return false }; + self.allows(&real.join(rest)) } /// What the file or folder at `path` is, located as [`ScriptScope::locate`] locates it. @@ -542,7 +730,7 @@ impl ScriptScope { continue; } let Ok(target) = std::fs::canonicalize(entry.path()) else { continue }; - if !self.roots.iter().any(|r| inside(&target, r)) || check_read(&entry.path().to_string_lossy()).is_err() { + if !self.allows(&target) || check_read(&entry.path().to_string_lossy()).is_err() { continue; } if out.len() >= max { diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 3c3460ecb2..ebf52fb27f 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -180,6 +180,10 @@ pub struct Session { /// The folder of the New Document profiles `file.new` starts documents from; `None`: none, /// every document starts with the defaults ([`Session::attach_new_doc_profiles`]). new_doc_profile_dir: Option, + /// The folder of each script's data folder (`Folder.userData`), beside which the grants file + /// keeps the file access people allowed scripts; `None`: no folder + /// ([`Session::attach_script_data`]). + script_data_dir: Option, /// A filter's output that a run made in the background handed in for `plugin.run` to apply /// ([`cmd::plugin::FilterRun::hand_in`]); the next `plugin.run` takes it. plugin_output: Option, diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index ec848a973e..37f3b93213 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -21,7 +21,8 @@ //! `File` for an existing file, only where the path may be read. //! - Opening reads the whole file, at most [`MAX_FILE_BYTES`], checked from its size before any of //! it is read; a run reads at most [`MAX_RUN_BYTES`] in all and ends past that, and has at most -//! [`MAX_OPEN`] files open at once. +//! [`MAX_OPEN`] files open at once. A file opened again after its objects closed counts only the +//! bytes it has grown by; a file open in another object counts again. //! - The encoding of an opened file is the one its byte order mark gives (UTF-8, UTF-16LE or //! UTF-16BE), otherwise the one the script set, otherwise UTF-8 when the bytes are valid UTF-8, //! otherwise CP1252. `read`, `readln` and `readch` count characters and `seek` and `tell` bytes; @@ -29,12 +30,45 @@ //! as `"\n"`. A character the encoding cannot decode fails the read with [`UNDECODABLE`] and //! leaves the position where it was. //! - `getFiles` lists at most [`MAX_ENTRIES`] entries, sorted by name, and looks at most -//! [`crate::file_access::MAX_LISTED`] names; a mask matches `*` and `?` without regard to case, -//! in at most [`MAX_MASK_STEPS`] steps for one listing. +//! [`crate::file_access::MAX_LISTED`] names; a mask matches `*` and `?`, without regard to case +//! on Windows and macOS, in at most [`MAX_MASK_STEPS`] steps for one listing. //! - A path longer than [`MAX_PATH_CHARS`] characters is refused before it is split into names. -//! - Writing (`open` with `w`, `e` or `a`, `write`, `copy`, `remove`, `rename`, `create` and the -//! property setters), the file and folder dialogs and `execute` are not available: they return -//! `false` or `null` and set `error`. `execute` is counted in the report's `fileExecutes`. +//! - A script writes only in its run's temporary folder (`Folder.temp`, made when it is first +//! named and deleted when the run ends), its own data folder (`Folder.userData`: for a script run +//! from a file a folder of its own beside the settings, kept between runs, and for a script given +//! as text a folder inside the temporary one), and the files and folders a person granted it. +//! Its own folder is only read. The automation write roots apply as well, and the folder that +//! holds the settings, with the Scripts and Plug-ins folders, is kept out of every grant but the +//! script's data folder. +//! - In the app, `File.openDialog`, `File.saveDialog`, `Folder.selectDialog` and the objects' +//! `openDlg`, `saveDlg` and `selectDlg` wait for the person, who picks a file or a folder and then +//! allows the script that one, once or always, or denies it ([`ScriptPicker`]). A picked file is +//! granted for reading (open) or for reading and writing (save), and a picked folder for reading +//! and writing with everything inside it. A `filter` that is a function is called with each file +//! picked, and the files it refuses are left out of what the dialog gives. Always keeps the grant in the grants file beside the +//! settings, for that script file with that text (its SHA-256): a changed or moved script has none, +//! and a kept grant whose path now leads elsewhere through a link is not used. +//! The grant also holds the SHA-256 of each source the run evaluated (a file `$.evalFile` ran, a +//! string given to `eval` or `Function`), up to the run's end: a later run that evaluates other +//! code, or whose named engine holds code its earlier runs compiled that the grant was not kept +//! for, loses the grant before that code runs. A run with nobody to ask gets `null` and +//! [`NO_PICKER`]. +//! - The commands a script runs with `vc.run` read and write only in the places above and in the +//! files of the open documents ([`crate::file_access::ScriptGate`]). +//! - `open('w')` empties the file at once; what a script writes is kept in memory, at most +//! [`MAX_FILE_BYTES`] a file, and written when it closes the file or the run ends; a run writes at +//! most [`MAX_RUN_BYTES`] in all and ends past that. `write` encodes in the file's encoding (an +//! ASCII or ISO-8859-1 file refuses a character it cannot hold, BINARY writes each character's low +//! byte) and `writeln` adds the `lineFeed`'s line end. `copy` replaces a file that is there, +//! `remove` deletes at once and takes a folder only when it is empty, `rename` takes a name without +//! a folder and refuses one in use, and `length` and `readonly` change a file (on Unix, clearing +//! `readonly` gives back the write bits the run cleared, or else the owner's). Each object that has +//! a file open holds its own bytes, so what `length` adds and what `copy` writes count once for the +//! file and once more for each such object. `write` joins its values only for an open file and +//! only up to twice [`MAX_FILE_BYTES`] UTF-16 code units. Each file written is named in the +//! report's `written` (at most [`super::MAX_WRITTEN`]), also after a run that failed. +//! - Hidden settings, aliases and `execute` are not available: they return `false` and set `error`. +//! `execute` is counted in the report's `fileExecutes`. //! - In a wasm build every lookup fails with [`NO_WEB`]. use std::collections::HashMap; @@ -49,6 +83,9 @@ use crate::file_access::{ScriptRead, ScriptScope}; /// The most bytes of one file a script opens. pub const MAX_FILE_BYTES: usize = 8 << 20; +/// The most files a run remembers the bytes counted for, so opening one again counts only what it +/// grew by; a file past them counts in full each time it is opened. +const MAX_CHARGED: usize = 4096; /// The most bytes of files one run opens, all of them counted together. pub const MAX_RUN_BYTES: usize = 32 << 20; /// The most entries `getFiles` gives. @@ -69,36 +106,659 @@ pub(crate) const NOT_FOUND: &str = "Script file does not exist"; pub(crate) const READ_FAILED: &str = "Script file could not be read"; pub(crate) const LISTING_TOO_LARGE: &str = "Script folder has more than 2,048 entries"; pub(crate) const BAD_MODE: &str = "Script file open mode must be r, w, e or a"; -pub(crate) const NO_WRITES: &str = "Script file writing is not available"; -pub(crate) const NO_PICKER: &str = "Script file dialogs are not available"; +pub(crate) const NO_PICKER: &str = "Script file dialogs need a person to answer them"; pub(crate) const NO_EXECUTE: &str = "Script files cannot be opened in another application"; pub(crate) const NO_WEB: &str = "Script file access is unavailable on the web"; pub(crate) const TOO_MANY_OPEN: &str = "Script has 256 files open"; pub(crate) const PATH_TOO_LONG: &str = "Script file path exceeds 32,767 characters"; pub(crate) const MASK_TOO_COSTLY: &str = "Script folder mask takes too many steps to match"; +pub(crate) const NOT_WRITABLE: &str = "Script file is not open for writing"; +pub(crate) const UNENCODABLE: &str = "Script file cannot encode the text"; +pub(crate) const WRITE_FAILED: &str = "Script file could not be written"; +pub(crate) const NOT_EMPTY: &str = "Script folder is not empty"; +pub(crate) const NAME_TAKEN: &str = "Script file name is already in use"; +pub(crate) const BAD_NAME: &str = "Script file name must be a name without a folder"; +pub(crate) const NO_ALIAS: &str = "Script files cannot make aliases"; +pub(crate) const NO_HIDDEN: &str = "Script file hidden setting cannot be changed"; +pub(crate) const PROTECTED: &str = "Script file access to the app's own folders is not allowed"; +pub(crate) const NOT_SAVED: &str = "Script file permission could not be saved"; +pub(crate) const NO_ALWAYS: &str = "Script file permission can be kept only for a script run from a file"; const OVER_RUN_BYTES: &str = "the script opened more file data than one run may open (32 MiB)"; +const OVER_RUN_WRITES: &str = "the script wrote more file data than one run may write (32 MiB)"; +/// The most grants the grants file keeps. +pub const MAX_STORED_GRANTS: usize = 4096; +/// The most bytes of the grants file that are read. +const MAX_STORE_BYTES: usize = 4 << 20; +/// The name of the grants file, beside the folder of the scripts' data folders. +pub const GRANTS_FILE: &str = "Script Grants.json"; +/// The most distinct sources a run evaluates whose SHA-256 is kept; past them no kept grant is in +/// force for the rest of the run, and the run's grants keep the sources counted before. +pub const MAX_RUN_CODE: usize = 256; + +/// The SHA-256 of `units`, source text a script evaluated, as UTF-16 code units in little-endian +/// order. +pub(crate) fn code_hash(units: &[u16]) -> String { + let bytes: Vec = units.iter().flat_map(|u| u.to_le_bytes()).collect(); + vectorcraft_plugins::permissions::sha256_hex(&bytes) +} /// The id of the next file a script opens. Ids are unique across runs, so a `File` that a named /// engine kept from an earlier run does not name a file a later run opened. static NEXT_HANDLE: AtomicU32 = AtomicU32::new(1); -/// The script's file state: its scope, where `Folder.current` starts, the files it has open and how -/// much it has read. +/// The number in the name of the next run's temporary folder. +static NEXT_TEMP: AtomicU32 = AtomicU32::new(1); + +/// Which file dialog a script opened. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum PickerKind { + /// `File.openDialog` and `openDlg`: a file to read. + Open, + /// `File.saveDialog` and `saveDlg`: a file to write, which may not exist yet. + Save, + /// `Folder.selectDialog` and `selectDlg`: a folder to read and write. + Folder, +} + +impl PickerKind { + /// The kind's name: `open`, `save` or `folder`. + pub fn id(self) -> &'static str { + match self { + Self::Open => "open", + Self::Save => "save", + Self::Folder => "folder", + } + } +} + +/// A file dialog a running script waits at: the person picks a file or a folder, then allows the +/// script that one, once or always, or denies it ([`PickAnswer`]). +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ScriptPicker { + pub kind: PickerKind, + /// The script's prompt, empty when it gave none. + pub prompt: String, + /// An open dialog that may pick more than one file. + pub multiple: bool, + /// The file or folder the dialog starts at, when the script's object gave one. + pub start: Option, + /// The file types the dialog shows, from the script's filter ([`dialog_filters`]): each one's + /// name and extensions (`*` for every file). Empty: every file. + pub filters: Vec<(String, Vec)>, + /// Whether the grant can be kept for later runs: the script was run from a file, and the app + /// has a settings folder for the grants file. + pub can_always: bool, +} + +/// The answer to a [`ScriptPicker`]. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum PickAnswer { + /// Cancel or Deny: the script gets `null`. + Deny, + /// The paths picked, allowed for this run, or with `always` for later runs of the same script too. + Allow { paths: Vec, always: bool }, +} + +/// What a run's `File` and `Folder` objects start with. +#[derive(Clone, Debug, Default)] +pub(crate) struct Setup { + /// The run is in the app, where a person answers its file dialogs. + pub framed: bool, + /// The file the script was read from. + pub script: Option, + /// The script's text with the files it includes, whose SHA-256 the grants it keeps are for. + pub source: String, + /// The folder that holds each script's data folder ([`crate::Session::attach_script_data`]). + pub data_dir: Option, + /// The code the run's named engine kept from its earlier runs: the SHA-256 of each source + /// ([`code_hash`] for evaluated code), and whether there was more than it keeps. + pub engine_code: (Vec, bool), +} + +/// A grant the grants file keeps that is in force for the run: the real path, whether it may be +/// written, whether it is a folder's, and the evaluated code the script ran in the run that kept it. +struct Stored { + path: std::path::PathBuf, + write: bool, + folder: bool, + code: std::collections::BTreeSet, +} + +/// The script's file state: where it reads and writes, where `Folder.current` starts, the files it +/// has open, how much it has read and written, and the file dialog it waits at. pub(crate) struct Disk { scope: ScriptScope, + /// Where the script writes: its temporary and data folders and what was granted for writing. + writes: ScriptScope, home: String, start: String, open: HashMap, temps: u32, bytes: usize, + /// The most bytes counted in `bytes` for each file read, by its real path ([`Disk::charge_read`]). + charged: HashMap, + written: usize, + framed: bool, + /// The script's file with its links followed, and the SHA-256 of its text. + script: Option<(std::path::PathBuf, String)>, + /// The SHA-256 of the script's text with the files it includes, also for a script given as + /// text, which its named engine keeps as code the engine holds. + own: String, + data_dir: Option, + /// The folder that holds the settings, with its links followed, which no grant reaches. + fenced: Option, + /// The run's temporary folder and the script's data folder, with their links followed, once made. + temp: Option, + user_data: Option, + /// The file dialog the script waits at. + pub(crate) picker: Option, + /// The error that ended the run when a dialog's answer could not reach the script. + pub(crate) failed: Option, + /// The files written since the host last took them ([`Disk::take_written`]). + wrote: Vec, + /// The places granted at the start (the script's own folder) and by the run itself (its + /// temporary and data folders and what a person allowed in a dialog), each with whether it + /// may be written and whether it is a folder: a withdrawn kept grant leaves these in force. + held: Vec<(std::path::PathBuf, bool, bool)>, + /// The kept grants in force: each is withdrawn once the run evaluates code it was not kept for. + stored: Vec, + /// The SHA-256 of each source other than the script itself that the run's code may run: what + /// it evaluated ([`code_hash`]) and what its named engine kept from earlier runs. + ran: std::collections::BTreeSet, + /// The run evaluated more distinct sources than [`MAX_RUN_CODE`]: no kept grant is in force. + ran_too_much: bool, + /// The grants this run kept with Always (path, write, folder), and how many sources `ran` held + /// when they were last written to the grants file. + kept: Vec<(std::path::PathBuf, bool, bool)>, + recorded: usize, + /// The write bits setting `readonly` cleared from each file in this run, by its device and + /// inode, which a rename keeps, at most [`MAX_ENTRIES`] files: clearing `readonly` gives them back. + #[cfg(unix)] + cleared: HashMap<(u64, u64), u32>, +} + +impl Drop for Disk { + fn drop(&mut self) { + // The run's end has flushed these already and reported what it could not write. + let _ = self.flush_all(); + if let Some(temp) = self.temp.take() { + let _ = std::fs::remove_dir_all(temp); + } + } } impl Disk { /// The state of a run whose own files are read in `scope`. - pub(crate) fn new(scope: &ScriptScope) -> Self { + pub(crate) fn new(scope: &ScriptScope, setup: Setup) -> Self { let home = home_folder(); let start = scope.folder().map_or_else(|| home.clone(), |p| p.to_string_lossy().into_owned()); - Self { scope: scope.clone(), home, start, open: HashMap::new(), temps: 0, bytes: 0 } + let web = cfg!(target_arch = "wasm32"); + let script = setup.script.as_deref().filter(|_| !web).and_then(|p| std::fs::canonicalize(p).ok()); + let own = vectorcraft_plugins::permissions::sha256_hex(setup.source.as_bytes()); + let script = script.map(|p| (p, own.clone())); + let fenced = setup.data_dir.as_deref().filter(|_| !web).and_then(Path::parent).and_then(real_or_planned); + let held = scope.roots().iter().map(|r| (r.clone(), false, true)).collect(); + let mut d = Self { + scope: scope.clone(), + writes: ScriptScope::default(), + home, + start, + open: HashMap::new(), + temps: 0, + bytes: 0, + charged: HashMap::new(), + written: 0, + framed: setup.framed, + script, + own, + data_dir: setup.data_dir, + fenced: fenced.clone(), + temp: None, + user_data: None, + picker: None, + failed: None, + wrote: Vec::new(), + held, + stored: Vec::new(), + ran: std::collections::BTreeSet::new(), + ran_too_much: setup.engine_code.1, + kept: Vec::new(), + recorded: 0, + #[cfg(unix)] + cleared: HashMap::new(), + }; + for hash in setup.engine_code.0 { + let _ = d.saw(hash); + } + if let Some(f) = fenced { + let own = d.scope.roots().to_vec(); + d.scope.fence(f.clone(), &own); + d.writes.fence(f, &[]); + } + if d.framed { + for g in d.stored() { + for (scope, granted) in [(&mut d.writes, g.write), (&mut d.scope, true)] { + match (granted, g.folder) { + (false, _) => {} + (true, true) => scope.add(g.path.clone()), + (true, false) => scope.add_file(g.path.clone()), + } + } + d.stored.push(g); + } + d.withdraw(); + } + d + } + + /// Notes that the run evaluates the source `units` (`eval`, `Function`, `$.evalFile`), before + /// it runs: the kept grants that were not kept for it are withdrawn. + pub(crate) fn saw_code(&mut self, units: &[u16]) { + if self.saw(code_hash(units)) { + self.withdraw(); + } + } + + /// Adds the source with SHA-256 `hash` to what the run's code may run. → whether it was new. + fn saw(&mut self, hash: String) -> bool { + if self.ran_too_much || self.ran.contains(&hash) || self.own == hash { + return false; + } + if self.ran.len() >= MAX_RUN_CODE { + self.ran_too_much = true; + } else { + self.ran.insert(hash); + } + true + } + + /// What the run's code may run, for its named engine to keep: each source's SHA-256 (the + /// script's own included, also for a script given as text) and whether there was more than + /// [`MAX_RUN_CODE`]. + pub(crate) fn code(&self) -> (Vec, bool) { + (std::iter::once(self.own.clone()).chain(self.ran.iter().cloned()).collect(), self.ran_too_much) + } + + /// Withdraws each kept grant whose run did not evaluate every source this run has: its place + /// is no longer read or written, unless the run holds it some other way, and files opened for + /// writing there are written now and take no more writes. + fn withdraw(&mut self) { + let (ran, all) = (&self.ran, self.ran_too_much); + let (stay, gone): (Vec, Vec) = std::mem::take(&mut self.stored).into_iter().partition(|g| !all && ran.is_subset(&g.code)); + self.stored = stay; + if gone.is_empty() { + return; + } + for g in &gone { + let held = |write: bool| { + self.held.iter().any(|(p, w, f)| *p == g.path && *f == g.folder && (*w || !write)) + || self.stored.iter().any(|s| s.path == g.path && s.folder == g.folder && (s.write || !write)) + }; + if !held(false) { + self.scope.remove(&g.path, g.folder); + } + if g.write && !held(true) { + self.writes.remove(&g.path, g.folder); + } + } + let ids: Vec = + self.open.iter().filter(|(_, o)| o.target.as_deref().is_some_and(|t| !self.writes.allows(t))).map(|(id, _)| *id).collect(); + for id in ids { + let written = self.flush(id).is_ok(); + if let Some(o) = self.open.get_mut(&id) { + // Changes that could not be written stay, so the run's end tries them again and + // reports the file when it still cannot. + o.withdrawn = true; + if written { + o.target = None; + } + } + } + } + + /// Writes the evaluated code this run ran into the grants it kept with Always, so a later run + /// of the same script that evaluates the same code keeps them in force. A grant that cannot be + /// updated keeps the code it was kept with. + pub(crate) fn record_code(&mut self) { + if self.kept.is_empty() || self.ran_too_much || self.ran.len() == self.recorded { + return; + } + let (Some((script, hash)), Some(store)) = (&self.script, self.store_path()) else { return }; + let (script, code) = (shown(script), self.ran.iter().cloned().collect::>()); + let mut grants = read_store(&store); + for g in &mut grants { + let ours = g["script"] == *script + && g["sha256"] == *hash + && self.kept.iter().any(|(p, w, f)| g["path"] == *shown(p) && g["write"] == *w && g["folder"] == *f); + if ours { + g["code"] = serde_json::json!(code); + } + } + if write_store(&store, grants).is_ok() { + self.recorded = self.ran.len(); + } + } + + /// The gate for a command the script runs: the places it reads and writes now, and the files of + /// the open documents, `documents`. + pub(crate) fn gate(&self, documents: Vec) -> crate::file_access::ScriptGate { + crate::file_access::ScriptGate { read: self.scope.clone(), write: self.writes.clone(), documents } + } + + /// The files written since this was last asked, to name in the report. + pub(crate) fn take_written(&mut self) -> Vec { + std::mem::take(&mut self.wrote) + } + + fn wrote(&mut self, real: &Path) { + let shown = crate::cmd::findfiles::plain(real.to_path_buf()).to_string_lossy().into_owned(); + if !self.wrote.contains(&shown) { + self.wrote.push(shown); + } + } + + /// Grants the real path `real`, a folder with everything in it (`folder`) or a file, for + /// reading, and with `write` for writing too. + fn grant(&mut self, real: std::path::PathBuf, write: bool, folder: bool) { + let scopes = if write { vec![&mut self.writes, &mut self.scope] } else { vec![&mut self.scope] }; + for scope in scopes { + if folder { scope.add(real.clone()) } else { scope.add_file(real.clone()) } + } + self.held.push((real, write, folder)); + } + + /// The run's temporary folder, made the first time it is asked for; `None` when it cannot be + /// made, when the automation write roots do not take it, and on the web. + fn temp_dir(&mut self) -> Option { + if cfg!(target_arch = "wasm32") { + return None; + } + if self.temp.is_none() { + let base = std::env::temp_dir(); + let made = (0..64).find_map(|_| { + let n = NEXT_TEMP.fetch_add(1, Ordering::Relaxed); + let dir = base.join(format!("VectorCraft Script {}-{n}", std::process::id())); + crate::file_access::check_write(&dir.to_string_lossy()).ok()?; + std::fs::create_dir(&dir).ok().and_then(|()| std::fs::canonicalize(&dir).ok()) + })?; + self.grant(made.clone(), true, true); + self.temp = Some(made); + } + self.temp.clone().map(crate::cmd::findfiles::plain) + } + + /// The script's data folder, made the first time it is asked for: for a script run from a file, + /// a folder named by the SHA-256 of its path in the data folder, and otherwise a folder in the + /// run's temporary folder. `None` when that folder is a link, cannot be made, or is outside the + /// automation write roots. + fn user_data_dir(&mut self) -> Option { + if cfg!(target_arch = "wasm32") { + return None; + } + if self.user_data.is_none() { + let dir = match (&self.script, &self.data_dir) { + (Some((path, _)), Some(data)) => { + let key = vectorcraft_plugins::permissions::sha256_hex(path.to_string_lossy().as_bytes()); + data.join(key.get(..16).unwrap_or(&key)) + } + _ => self.temp_dir()?.join("userData"), + }; + crate::file_access::check_write(&dir.to_string_lossy()).ok()?; + // Each missing folder above it that is made on the way must be inside the write roots too. + for missing in dir.ancestors().skip(1).take_while(|a| !a.as_os_str().is_empty() && std::fs::symlink_metadata(a).is_err()) { + crate::file_access::check_write(&missing.to_string_lossy()).ok()?; + } + // The data folder that holds the folder, and then the folder, are folders where they are + // named, not links; the folder is made only once the data folder is checked. + let direct = |d: &Path| -> Option { + let (parent, name) = (std::fs::canonicalize(d.parent()?).ok()?, d.file_name()?); + let real = std::fs::canonicalize(d).ok()?; + (real == parent.join(name) && std::fs::symlink_metadata(d).is_ok_and(|m| m.is_dir())).then_some(real) + }; + std::fs::create_dir_all(dir.parent()?).ok()?; + direct(dir.parent()?)?; + std::fs::create_dir_all(&dir).ok()?; + let real = direct(&dir)?; + self.scope.fence_open(real.clone()); + self.writes.fence_open(real.clone()); + self.grant(real.clone(), true, true); + self.user_data = Some(real); + } + self.user_data.clone().map(crate::cmd::findfiles::plain) + } + + /// The grants file, beside the scripts' data folders. + fn store_path(&self) -> Option { + self.data_dir.as_ref().map(|d| d.with_file_name(GRANTS_FILE)) + } + + /// The grants the grants file keeps for this script with this text: each path, whether it may + /// be written, whether it is a folder, and the evaluated code it was kept for. A grant whose + /// path no longer is its own real path is left out. + fn stored(&self) -> Vec { + let (Some((script, hash)), Some(store)) = (&self.script, self.store_path()) else { return Vec::new() }; + let script = shown(script); + read_store(&store) + .into_iter() + .filter(|g| g["script"] == *script && g["sha256"] == *hash) + .filter_map(|g| { + let code = g["code"].as_array()?.iter().map(|c| c.as_str().map(str::to_string)).collect::>()?; + let (write, folder) = (g["write"].as_bool()?, g["folder"].as_bool()?); + // The grant stays on the real path it was kept for: a path that now leads elsewhere, + // through a link put in its place or in a folder above it, is not granted. + let saved = g["path"].as_str()?; + let path = real_of(Path::new(saved)).filter(|real| shown(real) == saved)?; + Some(Stored { path, write, folder, code }) + }) + .filter(|g| self.fenced.as_ref().is_none_or(|f| !crate::file_access::path_inside(&g.path, f))) + .collect() + } + + /// Adds grants of `paths` (with `write`, folders when `folder`) for this script to the grants + /// file, with the code the run has evaluated so far, written whole to a file beside it that then + /// takes its place. + fn keep(&self, paths: &[std::path::PathBuf], write: bool, folder: bool) -> Result<(), &'static str> { + let (Some((script, hash)), Some(store)) = (&self.script, self.store_path()) else { return Err(NO_ALWAYS) }; + let mut grants = read_store(&store); + let script = shown(script); + let code: Vec<&String> = self.ran.iter().collect(); + for p in paths { + let path = shown(p); + grants + .retain(|g| !(g["script"] == *script && g["sha256"] == *hash && g["path"] == *path && g["write"] == write && g["folder"] == folder)); + grants.push(serde_json::json!({"script": script, "sha256": hash, "code": code, "path": path, "write": write, "folder": folder})); + } + if grants.len() > MAX_STORED_GRANTS { + return Err(NOT_SAVED); + } + write_store(&store, grants).map_err(|_| NOT_SAVED) + } + + /// The paths a person picked in the dialog the script waits at, allowed (`always`: kept for + /// later runs too), or denied; → what the dialog's call gives the script (a path, a list of + /// paths for an open dialog that picks more than one, `null`, or `{error}`), `None` when no + /// dialog waits. + pub(crate) fn answer(&mut self, answer: PickAnswer) -> Option { + let picker = self.picker.take()?; + let PickAnswer::Allow { paths, always } = answer else { return Some(Data::Null) }; + Some(self.allow(&picker, &paths, always).unwrap_or_else(error)) + } + + fn allow(&mut self, picker: &ScriptPicker, paths: &[String], always: bool) -> Result { + let wanted = if picker.multiple { paths.len().min(MAX_ENTRIES) } else { 1 }; + let mut reals = Vec::new(); + for p in paths.iter().take(wanted) { + reals.push(self.picked(picker.kind, p)?); + } + if reals.is_empty() { + return Ok(Data::Null); + } + let (write, folder) = (picker.kind != PickerKind::Open, picker.kind == PickerKind::Folder); + if always { + self.keep(&reals, write, folder)?; + self.kept.extend(reals.iter().map(|r| (r.clone(), write, folder))); + self.recorded = self.ran.len(); + } + let mut picked = Vec::new(); + for real in reals { + picked.push(Data::String(self.pathname(&shown(&real), &self.start, false).fs())); + self.grant(real, write, folder); + } + Ok(match picked.len() { + 1 if !picker.multiple => picked.swap_remove(0), + _ => Data::Array(picked), + }) + } + + /// The real path of `path`, which a person picked in a dialog of `kind`: a file that is there + /// (open), a folder that is there (folder), or a file whose folder is there (save). A network or + /// device path, and a place in the folder that holds the settings, are refused. + fn picked(&self, kind: PickerKind, path: &str) -> Result { + let p = self.checked(path)?; + if ScriptScope::refused_by_name(p) { + return Err(ACCESS_DENIED); + } + let real = match kind { + PickerKind::Save if std::fs::symlink_metadata(p).is_err() => { + let (Some(dir), Some(name)) = (p.parent(), p.file_name()) else { return Err(ACCESS_DENIED) }; + std::fs::canonicalize(dir).map_err(|_| NOT_FOUND)?.join(name) + } + _ => std::fs::canonicalize(p).map_err(|_| NOT_FOUND)?, + }; + match kind { + PickerKind::Folder if !real.is_dir() => return Err(NOT_FOUND), + PickerKind::Open if !real.is_file() => return Err(NOT_REGULAR), + PickerKind::Save if real.is_dir() => return Err(NOT_REGULAR), + _ => {} + } + if self.fenced.as_ref().is_some_and(|f| crate::file_access::path_inside(&real, f)) + && !self.user_data.as_ref().is_some_and(|u| crate::file_access::path_inside(&real, u)) + { + return Err(PROTECTED); + } + Ok(real) + } + + /// The real path writing to `path` writes, or why it may not ([`ScriptScope::target`]). + fn target(&self, path: &str, follow: bool) -> Result { + let p = self.checked(path)?; + match self.writes.target(p, follow) { + Ok(real) => Ok(real), + Err(ScriptRead::Failed(_)) => Err(WRITE_FAILED), + Err(_) => Err(ACCESS_DENIED), + } + } + + /// Counts `n` more bytes written in the run, which ends past [`MAX_RUN_BYTES`]. + fn charge_write(&mut self, n: usize) -> Result<(), HostError> { + self.written = self.written.saturating_add(n); + if self.written > MAX_RUN_BYTES { + return Err(HostError::Abort(OVER_RUN_WRITES.to_string())); + } + Ok(()) + } + + /// Opens the file at `path` for writing in `mode` (`w`, `e` or `a`). + fn open_write(&mut self, path: &str, encoding: &str, mode: &str) -> Result { + let fail = |m: &str| Err(HostError::Error(m.to_string())); + if self.open.len() >= MAX_OPEN { + return fail(TOO_MANY_OPEN); + } + let real = match self.target(path, true) { + Ok(real) => real, + Err(m) => return fail(m), + }; + let meta = std::fs::metadata(&real).ok(); + if meta.as_ref().is_some_and(|m| !m.is_file()) { + return fail(NOT_REGULAR); + } + if mode == "e" && meta.is_none() { + return fail(NOT_FOUND); + } + // Changes other open objects hold for the file are written before it is opened again, so + // they do not later replace what this one writes. + let ids: Vec = self.open.iter().filter(|(_, o)| o.target.as_deref() == Some(real.as_path())).map(|(id, _)| *id).collect(); + if let Err(m) = ids.iter().try_for_each(|id| self.flush(*id)) { + return fail(m); + } + let bytes = if mode == "w" || meta.is_none() { + // An encoding that is not one is refused before the file is emptied. + if Open::new(Vec::new(), encoding).is_none() { + return Err(HostError::Error(UNDECODABLE.to_string())); + } + if std::fs::File::create(&real).is_err() { + return fail(WRITE_FAILED); + } + self.wrote(&real); + Vec::new() + } else { + if meta.as_ref().is_some_and(|m| m.len() > MAX_FILE_BYTES as u64) { + return fail(TOO_LARGE); + } + // The bytes kept are read under the rules for reading. + let bytes = match self.scope.read(Path::new(path), MAX_FILE_BYTES) { + Ok((at, bytes)) if at == real => bytes, + Ok(_) | Err(ScriptRead::Refused) => return fail(ACCESS_DENIED), + Err(ScriptRead::TooLarge) => return fail(TOO_LARGE), + Err(ScriptRead::Missing) => return fail(NOT_FOUND), + Err(ScriptRead::Failed(_)) => return fail(READ_FAILED), + }; + if bytes.len() > MAX_FILE_BYTES { + return fail(TOO_LARGE); + } + self.charge_read(&real, bytes.len())?; + bytes + }; + let mut file = Open::new(bytes, encoding).ok_or_else(|| HostError::Error(UNDECODABLE.to_string()))?; + if mode == "a" { + file.pos = file.bytes.len(); + } + file.read_from = Some(real.clone()); + file.target = Some(real); + Ok(self.insert(file)) + } + + fn insert(&mut self, file: Open) -> u32 { + let mut id = NEXT_HANDLE.fetch_add(1, Ordering::Relaxed); + while id == 0 || self.open.contains_key(&id) { + id = NEXT_HANDLE.fetch_add(1, Ordering::Relaxed); + } + self.open.insert(id, file); + id + } + + /// Writes the open file `id`'s bytes to its file when it has changed. `Err` when it could not. + fn flush(&mut self, id: u32) -> Result<(), &'static str> { + let Some(file) = self.open.get_mut(&id) else { return Ok(()) }; + let Some(real) = file.target.clone().filter(|_| file.dirty) else { return Ok(()) }; + // A link put in the file's place, or in place of a folder above it, since it was opened is + // not written through. + let moved = real.parent().is_some_and(|p| std::fs::canonicalize(p).is_ok_and(|c| c != p)); + if moved || std::fs::symlink_metadata(&real).is_ok_and(|m| m.file_type().is_symlink()) { + return Err(ACCESS_DENIED); + } + // The file stays changed until its bytes are written, so the run's end tries it again. + std::fs::write(&real, &file.bytes).map_err(|_| WRITE_FAILED)?; + file.dirty = false; + self.wrote(&real); + Ok(()) + } + + /// Writes every open file that has changed: at the end of the run. → the files that could not + /// be written, as the report gives them. + pub(crate) fn flush_all(&mut self) -> Vec { + // In the order the files were opened, so the object opened last writes a file last. + let mut ids: Vec = self.open.keys().copied().collect(); + ids.sort_unstable(); + let mut failed = Vec::new(); + for id in ids { + if self.flush(id).is_err() + && let Some(real) = self.open.get(&id).and_then(|o| o.target.as_deref()) + { + failed.push(shown(real)); + } + } + failed } /// The path `text` names from the folder `base`, a platform path; `text`'s URI escapes are @@ -150,30 +810,131 @@ impl Disk { if entry.len > MAX_FILE_BYTES as u64 { return fail(TOO_LARGE); } - if self.bytes.saturating_add(entry.len as usize) > MAX_RUN_BYTES { - return Err(HostError::Abort(OVER_RUN_BYTES.to_string())); - } - let bytes = match self.scope.read(Path::new(path), MAX_FILE_BYTES) { - Ok((_, bytes)) => bytes, + let (real, bytes) = match self.scope.read(Path::new(path), MAX_FILE_BYTES) { + Ok(read) => read, Err(ScriptRead::TooLarge) => return fail(TOO_LARGE), Err(ScriptRead::Missing) => return fail(NOT_FOUND), Err(ScriptRead::Refused) => return fail(ACCESS_DENIED), Err(ScriptRead::Failed(_)) => return fail(READ_FAILED), }; - if self.bytes.saturating_add(bytes.len()) > MAX_RUN_BYTES { + self.charge_read(&real, bytes.len())?; + let mut file = Open::new(bytes, encoding).ok_or_else(|| HostError::Error(UNDECODABLE.to_string()))?; + file.read_from = Some(real); + Ok(self.insert(file)) + } + + /// Counts `n` bytes read from the file `real` in the run, which ends past [`MAX_RUN_BYTES`]. A + /// file opened again once no open object holds it counts only the bytes past the most read from + /// it before; while another object holds it, all of them count, as each holds its own copy. + fn charge_read(&mut self, real: &Path, n: usize) -> Result<(), HostError> { + let held = self.open.values().any(|o| o.read_from.as_deref() == Some(real)); + let before = if held { 0 } else { self.charged.get(real).copied().unwrap_or(0) }; + let more = n.saturating_sub(before); + if self.bytes.saturating_add(more) > MAX_RUN_BYTES { return Err(HostError::Abort(OVER_RUN_BYTES.to_string())); } - self.bytes += bytes.len(); - let file = Open::new(bytes, encoding).ok_or_else(|| HostError::Error(UNDECODABLE.to_string()))?; - let mut id = NEXT_HANDLE.fetch_add(1, Ordering::Relaxed); - while id == 0 || self.open.contains_key(&id) { - id = NEXT_HANDLE.fetch_add(1, Ordering::Relaxed); + self.bytes += more; + if !held && n > before && (self.charged.contains_key(real) || self.charged.len() < MAX_CHARGED) { + self.charged.insert(real.to_path_buf(), n); } - self.open.insert(id, file); - Ok(id) + Ok(()) } } +/// The real path `real` as the grants file and the report give it. +fn shown(real: &Path) -> String { + crate::cmd::findfiles::plain(real.to_path_buf()).to_string_lossy().into_owned() +} + +/// The path `p` with its links followed; for a missing file whose folder is there, that folder's +/// real path and the file's name. +fn real_of(p: &Path) -> Option { + std::fs::canonicalize(p).ok().or_else(|| Some(std::fs::canonicalize(p.parent()?).ok()?.join(p.file_name()?))) +} + +/// The path `p` with its links followed, also when it is not there yet: the real path of the +/// nearest folder above it that is there, and the names below that folder. +fn real_or_planned(p: &Path) -> Option { + let mut names = Vec::new(); + let mut at = p; + loop { + if let Ok(real) = std::fs::canonicalize(at) { + return Some(names.iter().rev().fold(real, |real, name| real.join(name))); + } + names.push(at.file_name()?); + at = at.parent()?; + } +} + +/// The first `max` bytes of the file at `real`, and one more when it has more. +fn read_head(real: &Path, max: usize) -> std::io::Result> { + use std::io::Read; + let mut bytes = Vec::new(); + std::fs::File::open(real)?.take(max as u64 + 1).read_to_end(&mut bytes)?; + Ok(bytes) +} + +/// The grants the grants file at `store` holds; none when it is missing or cannot be read. +fn read_store(store: &Path) -> Vec { + let Ok(bytes) = read_head(store, MAX_STORE_BYTES) else { return Vec::new() }; + if bytes.len() > MAX_STORE_BYTES { + return Vec::new(); + } + let Ok(v) = serde_json::from_slice::(&bytes) else { return Vec::new() }; + if v["version"] != 1 { + return Vec::new(); + } + let valid = |g: &serde_json::Value| { + g["script"].is_string() + && g["sha256"].is_string() + && g["code"].as_array().is_some_and(|c| c.iter().all(serde_json::Value::is_string)) + && g["path"].is_string() + && g["write"].is_boolean() + && g["folder"].is_boolean() + }; + v["grants"].as_array().map(|a| a.iter().filter(|g| valid(g)).take(MAX_STORED_GRANTS).cloned().collect()).unwrap_or_default() +} + +/// Writes `grants` as the grants file at `store`: to a file beside it, which then takes its place. +/// `Err`, with the file left as it was, when the grants take more than [`MAX_STORE_BYTES`]. +fn write_store(store: &Path, grants: Vec) -> std::io::Result<()> { + let text = serde_json::to_vec_pretty(&serde_json::json!({"version": 1, "grants": grants})).map_err(std::io::Error::other)?; + if text.len() > MAX_STORE_BYTES { + return Err(std::io::Error::other("the grants file would be too large")); + } + if let Some(dir) = store.parent() { + std::fs::create_dir_all(dir)?; + } + let part = store.with_extension("json.part"); + std::fs::write(&part, text)?; + // `rename` replaces a grants file that is there, on Windows too (`MOVEFILE_REPLACE_EXISTING`). + std::fs::rename(&part, store).inspect_err(|_| { + let _ = std::fs::remove_file(&part); + }) +} + +/// The grants the grants file beside the data folder `data_dir` keeps: each script, the SHA-256 of +/// its text, the path and whether it may be written (`script.grants`). +pub(crate) fn stored_grants(data_dir: &Path) -> Vec { + read_store(&data_dir.with_file_name(GRANTS_FILE)) +} + +/// Removes from the grants file beside `data_dir` the grants of the script `script` and of the path +/// `path`, of both when both are given and of every grant when neither is (`script.grants.revoke`). +/// → how many were removed. +pub(crate) fn revoke_grants(data_dir: &Path, script: Option<&str>, path: Option<&str>) -> std::io::Result { + let store = data_dir.with_file_name(GRANTS_FILE); + let grants = read_store(&store); + let before = grants.len(); + let kept: Vec = + grants.into_iter().filter(|g| !(script.is_none_or(|s| g["script"] == *s) && path.is_none_or(|p| g["path"] == *p))).collect(); + let removed = before - kept.len(); + if removed > 0 { + write_store(&store, kept)?; + } + Ok(removed) +} + /// Whether paths are read as Windows reads them. const WINDOWS: bool = cfg!(windows); @@ -188,21 +949,20 @@ fn home_folder() -> String { std::env::var(var).unwrap_or_else(|_| if WINDOWS { r"C:\".to_string() } else { "/".to_string() }) } -/// The folders `Folder.temp`, `Folder.desktop` and the others name, `null` where there is none. -/// On the web every one is `null`, and no platform folder is looked up. -fn locations(home: &str) -> Data { +/// The folders `Folder.temp`, `Folder.desktop` and the others name, `null` where there is none: +/// `temp` and `user_data` are the run's own. On the web every one is `null`, and no platform folder +/// is looked up. +fn locations(home: &str, temp: Option, user_data: Option) -> Data { if cfg!(target_arch = "wasm32") { return Data::Object(PLACES.iter().map(|k| (k.to_string(), Data::Null)).collect()); } let env = |k: &str| std::env::var(k).ok().filter(|v| !v.is_empty()); let join = |a: &str, b: &str| Path::new(a).join(b).to_string_lossy().into_owned(); let exe = std::env::current_exe().ok().and_then(|p| p.parent().map(|d| d.to_string_lossy().into_owned())); - let temp = temp_folder().to_string_lossy().into_owned(); - let (user_data, app_data, common, system, trash) = if WINDOWS { - (env("APPDATA"), env("PROGRAMDATA"), env("CommonProgramFiles"), env("SystemRoot"), None) + let (app_data, common, system, trash) = if WINDOWS { + (env("PROGRAMDATA"), env("CommonProgramFiles"), env("SystemRoot"), None) } else if cfg!(target_os = "macos") { ( - Some(join(home, "Library/Application Support")), Some("/Library/Application Support".to_string()), Some("/Library/Application Support".to_string()), Some("/System".to_string()), @@ -210,7 +970,7 @@ fn locations(home: &str) -> Data { ) } else { let data = env("XDG_DATA_HOME").unwrap_or_else(|| join(home, ".local/share")); - (Some(data.clone()), Some("/usr/share".to_string()), Some("/usr/share".to_string()), Some("/".to_string()), Some(join(&data, "Trash"))) + (Some("/usr/share".to_string()), Some("/usr/share".to_string()), Some("/".to_string()), Some(join(&data, "Trash"))) }; let s = |v: Option| v.map_or(Data::Null, Data::String); let places = vec![ @@ -221,7 +981,7 @@ fn locations(home: &str) -> Data { ("myDocuments", Some(join(home, "Documents"))), ("startup", exe), ("system", system), - ("temp", Some(temp)), + ("temp", temp), ("trash", trash), ("userData", user_data), ]; @@ -231,7 +991,8 @@ fn locations(home: &str) -> Data { /// The names [`locations`] gives. const PLACES: [&str; 10] = ["appData", "appPackage", "commonFiles", "desktop", "myDocuments", "startup", "system", "temp", "trash", "userData"]; -/// The folder for temporary files: the platform's, or on the web the root, where nothing is read. +/// The folder for temporary files when the run's own cannot be made: the platform's, or on the web +/// the root, where nothing is read. fn temp_folder() -> std::path::PathBuf { if cfg!(target_arch = "wasm32") { std::path::PathBuf::from("/") } else { std::env::temp_dir() } } @@ -395,31 +1156,44 @@ fn decode(s: &str) -> String { String::from_utf8(out).unwrap_or_else(|_| s.to_string()) } +/// Do file names match a mask without regard to case: on Windows and macOS, whose file systems +/// usually do not tell names apart by case. Elsewhere case matters. +const MASK_IGNORES_CASE: bool = cfg!(any(windows, target_os = "macos")); + /// A `getFiles` mask, where `*` stands for any run of characters and `?` for one, without regard -/// to case, read once for a whole listing. +/// to case where the file system does not tell names apart by case ([`MASK_IGNORES_CASE`]), read +/// once for a whole listing. struct Mask { - /// The mask in lower case, each run of `*` written as one. + /// The mask, in lower case when case does not matter, each run of `*` written as one. chars: Vec, /// How many of its characters are not `*`: a name with fewer characters does not match. fixed: usize, + /// Names are compared without regard to case. + fold: bool, } impl Mask { fn new(mask: &str) -> Self { + Self::with_case(mask, MASK_IGNORES_CASE) + } + + /// The mask `mask`, which compares names without regard to case when `fold`. + fn with_case(mask: &str, fold: bool) -> Self { let mut chars: Vec = Vec::new(); - for c in mask.to_lowercase().chars() { + let text = if fold { mask.to_lowercase() } else { mask.to_string() }; + for c in text.chars() { if !(c == '*' && chars.last() == Some(&'*')) { chars.push(c); } } let fixed = chars.iter().filter(|c| **c != '*').count(); - Self { chars, fixed } + Self { chars, fixed, fold } } /// Does `name` match, taking a step from `steps` for each character compared? `None` when the /// steps run out first. fn matches(&self, name: &str, steps: &mut usize) -> Option { - let n: Vec = name.to_lowercase().chars().collect(); + let n: Vec = if self.fold { name.to_lowercase().chars().collect() } else { name.chars().collect() }; if n.len() < self.fixed { return Some(false); } @@ -427,7 +1201,7 @@ impl Mask { } } -/// Does `n` match the lower-case mask `m`? `None` when `steps` run out first. +/// Does `n` match the mask `m`, both in the same case? `None` when `steps` run out first. fn matched(m: &[char], n: &[char], steps: &mut usize) -> Option { let (mut i, mut j, mut star, mut mark) = (0usize, 0usize, None, 0usize); while j < n.len() { @@ -488,6 +1262,30 @@ impl Encoding { }) } + /// `text` in this encoding; `None` when a character has no form in it. BINARY writes each + /// character's low byte. + fn encode(self, text: &str) -> Option> { + let mut out = Vec::with_capacity(text.len()); + for c in text.chars() { + let code = u32::from(c); + match self { + Self::Utf8 => out.extend_from_slice(c.encode_utf8(&mut [0; 4]).as_bytes()), + Self::Ascii if code < 0x80 => out.push(code as u8), + Self::Binary => out.push((code & 0xFF) as u8), + Self::Latin1 if code <= 0xFF => out.push(code as u8), + Self::Cp1252 if code < 0x80 || (0xA0..=0xFF).contains(&code) => out.push(code as u8), + Self::Cp1252 => out.push(0x80 + CP1252_HIGH.iter().position(|h| u32::from(*h) == code)? as u8), + Self::Utf16Le | Self::Utf16Be => { + for unit in c.encode_utf16(&mut [0; 2]) { + out.extend_from_slice(&if self == Self::Utf16Le { unit.to_le_bytes() } else { unit.to_be_bytes() }); + } + } + Self::Ascii | Self::Latin1 => return None, + } + } + Some(out) + } + fn name(self) -> &'static str { match self { Self::Utf8 => "UTF-8", @@ -501,12 +1299,20 @@ impl Encoding { } } -/// An opened file: its bytes, the byte position and the encoding it is read in. +/// An opened file: its bytes, the byte position and the encoding it is read in; for a file opened +/// for writing, the real path its bytes are written to and whether they changed since. struct Open { bytes: Vec, pos: usize, encoding: Encoding, name: String, + target: Option, + /// The real path of the file the object was opened on, whose bytes it holds. + read_from: Option, + dirty: bool, + /// The grant the file was opened under was withdrawn while its changes could not be written: + /// they are written again when the run ends, and the object takes no more writes. + withdrawn: bool, } impl Open { @@ -526,7 +1332,28 @@ impl Open { } else { (Encoding::Cp1252, 0) }; - Some(Self { bytes, pos, encoding, name: encoding.name().to_string() }) + Some(Self { bytes, pos, encoding, name: encoding.name().to_string(), target: None, read_from: None, dirty: false, withdrawn: false }) + } + + /// Writes `text` at the position, over what is there and past the end, when it takes at most + /// `left` bytes; → the bytes written. + fn write(&mut self, text: &str, left: usize) -> Result { + if self.target.is_none() || self.withdrawn { + return Err(NOT_WRITABLE); + } + let bytes = self.encoding.encode(text).ok_or(UNENCODABLE)?; + if bytes.len() > left { + return Err(OVER_RUN_WRITES); + } + let end = self.pos.saturating_add(bytes.len()); + if end.max(self.bytes.len()) > MAX_FILE_BYTES { + return Err(TOO_LARGE); + } + let over = end.min(self.bytes.len()); + self.bytes.splice(self.pos..over, bytes.iter().copied()); + self.pos = end; + self.dirty = true; + Ok(bytes.len()) } /// The character at byte `at` and its length in bytes; `Ok(None)` at the end, `Err` where the @@ -661,12 +1488,22 @@ fn call(link: &super::Link, f: fn(&Host, &[Data]) -> Result) -> HostItem::Function(Rc::new(move |a| { let h = super::current(&l)?; bump(&h.counts.file_calls); - let r = f(&h, &a)?; + let r = f(&h, &a); + h.note_written(h.disk.borrow_mut().take_written()); + let r = r?; h.charge_call(super::data_size(&r).saturating_add(a.iter().map(super::data_size).sum()))?; Ok(r) })) } +/// `Ok(true)`, or `{error}` for a failure. +fn done(r: Result<(), &'static str>) -> Data { + match r { + Ok(()) => Data::Bool(true), + Err(m) => error(m), + } +} + fn handle(a: &[Data]) -> u32 { arg_number(a, 0).filter(|n| n.is_finite() && *n >= 0.0 && *n <= f64::from(u32::MAX)).map_or(0, |n| n as u32) } @@ -720,16 +1557,384 @@ fn stat(host: &Host, a: &[Data]) -> Result { }) } +/// `open(path, encoding, mode)`: `r` reads, `w`, `e` and `a` write. fn open(host: &Host, a: &[Data]) -> Result { - match host.disk.borrow_mut().open_file(&arg_text(a, 0), &arg_text(a, 1)) { + let (path, encoding, mode) = (arg_text(a, 0), arg_text(a, 1), arg_text(a, 2)); + let mut disk = host.disk.borrow_mut(); + let opened = match mode.as_str() { + "w" | "e" | "a" => disk.open_write(&path, &encoding, &mode), + _ => disk.open_file(&path, &encoding), + }; + match opened { Ok(id) => Ok(Data::Object(vec![("id".into(), Data::Number(f64::from(id)))])), Err(HostError::Error(m)) => Ok(error(&m)), Err(e) => Err(e), } } +/// Closes the open file, writing what changed: `true`, `false` when it was not open, or `{error}` +/// when it could not be written. A file that could not be written is kept for the run's end to +/// write again. fn close(host: &Host, a: &[Data]) -> Result { - Ok(Data::Bool(host.disk.borrow_mut().open.remove(&handle(a)).is_some())) + let mut disk = host.disk.borrow_mut(); + let id = handle(a); + Ok(match disk.flush(id) { + Err(m) => error(m), + Ok(()) => Data::Bool(disk.open.remove(&id).is_some()), + }) +} + +/// `write(id, text)`. A write past the run's limit ends the run and leaves the file as it was. +fn write(host: &Host, a: &[Data]) -> Result { + let text = arg_text(a, 1); + let mut disk = host.disk.borrow_mut(); + let left = MAX_RUN_BYTES.saturating_sub(disk.written); + let r = match disk.open.get_mut(&handle(a)) { + Some(file) => file.write(&text, left), + None => Err(NOT_OPEN), + }; + match r { + Ok(n) => { + disk.charge_write(n)?; + Ok(Data::Bool(true)) + } + Err(OVER_RUN_WRITES) => Err(HostError::Abort(OVER_RUN_WRITES.to_string())), + Err(m) => Ok(error(m)), + } +} + +/// `copy(from, to)`: the file `from` to `to`, replacing a file that is there. +fn copy(host: &Host, a: &[Data]) -> Result { + let (from, to) = (arg_text(a, 0), arg_text(a, 1)); + let mut disk = host.disk.borrow_mut(); + let source = match disk.stat(&from) { + Ok(Some(e)) if e.file => disk.checked(&from).ok().and_then(|p| disk.scope.locate(p).ok()), + Ok(Some(_)) => return Ok(error(NOT_REGULAR)), + Ok(None) => return Ok(error(NOT_FOUND)), + Err(m) => return Ok(error(m)), + }; + let Some(source) = source else { return Ok(error(ACCESS_DENIED)) }; + let target = match disk.target(&to, true) { + Ok(t) => t, + Err(m) => return Ok(error(m)), + }; + if std::fs::metadata(&target).is_ok_and(|m| !m.is_file()) { + return Ok(error(NOT_REGULAR)); + } + // A file copied onto itself, by its own name or by another link to it, is already its copy once + // its open objects are written, and copying could empty it. + let one = |t: &std::fs::Metadata| std::fs::metadata(&source).is_ok_and(|s| same_file((&source, &s), (&target, t))); + let itself = real_of(&target).is_some_and(|t| t == source) || std::fs::metadata(&target).is_ok_and(|t| one(&t)); + // The source's open objects write what they hold first, so the copy has it. + let ids: Vec = disk.open.iter().filter(|(_, o)| o.target.as_deref() == Some(source.as_path())).map(|(id, _)| *id).collect(); + if let Err(m) = ids.iter().try_for_each(|id| disk.flush(*id)) { + return Ok(error(m)); + } + let n = std::fs::metadata(&source).map_or(0, |m| m.len()); + if n > MAX_FILE_BYTES as u64 { + return Ok(error(TOO_LARGE)); + } + // The target's open objects each take a copy of the bytes, which count as written too, as does + // the copy itself when it is written. + let holders = disk.open.values().filter(|o| o.target.as_deref() == Some(target.as_path())).count(); + disk.charge_write(usize::try_from(n).unwrap_or(usize::MAX).saturating_mul(holders.saturating_add(usize::from(!itself))))?; + let r = if itself { Ok(n) } else { std::fs::copy(&source, &target) }; + if !itself && (r.is_ok() || target.exists()) { + disk.wrote(&target); + } + // Open objects of the target hold the copy, so closing them does not write their older bytes. + if r.is_ok() && disk.open.values().any(|o| o.target.as_deref() == Some(target.as_path())) { + let copied = read_head(&target, MAX_FILE_BYTES).unwrap_or_default(); + for file in disk.open.values_mut().filter(|o| o.target.as_deref() == Some(target.as_path())) { + file.bytes.clone_from(&copied); + file.pos = file.pos.min(copied.len()); + file.dirty = false; + } + } + Ok(done(r.map(drop).map_err(|_| WRITE_FAILED))) +} + +/// `remove(path)`: the file, or the folder when it is empty; a link itself, never what it leads to. +fn remove(host: &Host, a: &[Data]) -> Result { + let mut disk = host.disk.borrow_mut(); + let target = match disk.target(&arg_text(a, 0), false) { + Ok(t) => t, + Err(m) => return Ok(error(m)), + }; + let r = match std::fs::symlink_metadata(&target) { + Err(_) => Err(NOT_FOUND), + Ok(m) if m.is_dir() => std::fs::remove_dir(&target) + .map_err(|_| if std::fs::read_dir(&target).is_ok_and(|mut d| d.next().is_some()) { NOT_EMPTY } else { WRITE_FAILED }), + Ok(m) => std::fs::remove_file(&target).map_err(|_| WRITE_FAILED).inspect(|()| { + // A file made later in its place, which may take its inode, gets none of its write bits. + #[cfg(unix)] + { + use std::os::unix::fs::MetadataExt; + if m.nlink() <= 1 { + disk.cleared.remove(&(m.dev(), m.ino())); + } + } + #[cfg(not(unix))] + let _ = m; + }), + }; + if r.is_ok() { + // Other open objects of the file drop their changes and take no more writes, so neither + // their close nor the run's end makes the file again. + for file in disk.open.values_mut().filter(|o| o.target.as_deref() == Some(target.as_path())) { + file.dirty = false; + file.target = None; + } + disk.wrote(&target); + } + Ok(done(r)) +} + +/// `rename(path, name)`: the file or folder named `name` in the same folder; → `{fs}`, its new path. +fn rename(host: &Host, a: &[Data]) -> Result { + let (path, name) = (arg_text(a, 0), arg_text(a, 1)); + let bad = name.is_empty() || name == "." || name == ".." || name.contains('/') || (WINDOWS && (name.contains('\\') || name.contains(':'))); + if bad || name.contains('\0') { + return Ok(error(BAD_NAME)); + } + let Some(new) = Path::new(&path).parent().map(|p| p.join(&name).to_string_lossy().into_owned()) else { return Ok(error(ACCESS_DENIED)) }; + let mut disk = host.disk.borrow_mut(); + let (from, to) = match (disk.target(&path, false), disk.target(&new, false)) { + (Ok(f), Ok(t)) => (f, t), + (Err(m), _) | (_, Err(m)) => return Ok(error(m)), + }; + let Ok(was) = std::fs::symlink_metadata(&from) else { return Ok(error(NOT_FOUND)) }; + // A folder that holds the settings folder is not moved, also when its name is given in another + // case where case does not matter. + let holds = |f: &Path| std::fs::canonicalize(&from).map_or(true, |kept| crate::file_access::path_inside(f, &kept)); + if was.is_dir() && disk.fenced.as_deref().is_some_and(holds) { + return Ok(error(ACCESS_DENIED)); + } + // A name that differs in case alone may name the same file, which then takes the new name. + if let Ok(there) = std::fs::symlink_metadata(&to) + && !(from.to_string_lossy().eq_ignore_ascii_case(&to.to_string_lossy()) && same_file((&from, &was), (&to, &there))) + { + return Ok(error(NAME_TAKEN)); + } + if std::fs::rename(&from, &to).is_err() { + return Ok(error(WRITE_FAILED)); + } + // Open objects of the file, or of files in the folder, write to the new path. + for file in disk.open.values_mut() { + if let Some(rest) = file.target.as_deref().and_then(|t| t.strip_prefix(&from).ok()) { + file.target = Some(if rest.as_os_str().is_empty() { to.clone() } else { to.join(rest) }); + } + } + disk.wrote(&to); + Ok(Data::Object(vec![("fs".into(), Data::String(new))])) +} + +/// Do the paths `a` and `b`, with their metadata, name one file? On Unix by device and inode; on +/// Windows by volume and file index, with links followed; elsewhere by the paths with their links +/// followed, which give the name as the file system keeps it. +fn same_file(a: (&Path, &std::fs::Metadata), b: (&Path, &std::fs::Metadata)) -> bool { + #[cfg(unix)] + { + use std::os::unix::fs::MetadataExt; + a.1.dev() == b.1.dev() && a.1.ino() == b.1.ino() + } + #[cfg(windows)] + { + ::same_file::is_same_file(a.0, b.0).unwrap_or(false) + } + #[cfg(not(any(unix, windows)))] + { + matches!((std::fs::canonicalize(a.0), std::fs::canonicalize(b.0)), (Ok(x), Ok(y)) if x == y) + } +} + +/// `create(path)`: the folder, with the folders above it that are missing. +fn create(host: &Host, a: &[Data]) -> Result { + let disk = host.disk.borrow(); + let target = match disk.target(&arg_text(a, 0), true) { + Ok(t) => t, + Err(m) => return Ok(error(m)), + }; + // Each missing folder above it that is made on the way must be a place the script may write too. + let outside = target.ancestors().skip(1).take_while(|a| !a.as_os_str().is_empty() && std::fs::symlink_metadata(a).is_err()).any(|a| { + !disk.writes.allows(a) || crate::file_access::check_write(&crate::cmd::findfiles::plain(a.to_path_buf()).to_string_lossy()).is_err() + }); + if outside { + return Ok(error(ACCESS_DENIED)); + } + Ok(done(std::fs::create_dir_all(&target).map_err(|_| WRITE_FAILED))) +} + +/// `setLength(path, length)`: the file cut or padded with zero bytes to `length` bytes. +fn set_length(host: &Host, a: &[Data]) -> Result { + let n = arg_number(a, 1).filter(|n| n.is_finite() && *n >= 0.0).map_or(0, |n| n as u64); + if n > MAX_FILE_BYTES as u64 { + return Ok(error(TOO_LARGE)); + } + let mut disk = host.disk.borrow_mut(); + let target = match disk.target(&arg_text(a, 0), true) { + Ok(t) => t, + Err(m) => return Ok(error(m)), + }; + let r = match std::fs::metadata(&target) { + Err(_) => Err(NOT_FOUND), + Ok(m) if !m.is_file() => Err(NOT_REGULAR), + Ok(m) => { + // Each open object of the file holds its own bytes, so what each one grows by counts too. + let len = usize::try_from(n).unwrap_or(usize::MAX); + let held = disk + .open + .values() + .filter(|o| o.target.as_deref() == Some(target.as_path())) + .fold(0usize, |sum, o| sum.saturating_add(len.saturating_sub(o.bytes.len()))); + disk.charge_write(usize::try_from(n.saturating_sub(m.len())).unwrap_or(usize::MAX).saturating_add(held))?; + // The file's open objects write what they hold first, and then hold the new length. + let ids: Vec = disk.open.iter().filter(|(_, o)| o.target.as_deref() == Some(target.as_path())).map(|(id, _)| *id).collect(); + ids.iter() + .try_for_each(|id| disk.flush(*id)) + .and_then(|()| std::fs::OpenOptions::new().write(true).open(&target).and_then(|f| f.set_len(n)).map_err(|_| WRITE_FAILED)) + } + }; + if r.is_ok() { + let len = usize::try_from(n).unwrap_or(usize::MAX); + for file in disk.open.values_mut().filter(|o| o.target.as_deref() == Some(target.as_path())) { + file.bytes.resize(len, 0); + file.pos = file.pos.min(len); + } + disk.wrote(&target); + } + Ok(done(r)) +} + +/// `setReadonly(path, readonly)`. +fn set_readonly(host: &Host, a: &[Data]) -> Result { + let on = matches!(a.get(1), Some(Data::Bool(true))); + let mut disk = host.disk.borrow_mut(); + let target = match disk.target(&arg_text(a, 0), true) { + Ok(t) => t, + Err(m) => return Ok(error(m)), + }; + let r = std::fs::metadata(&target).map_err(|_| NOT_FOUND).and_then(|m| { + let mut p = m.permissions(); + // On Unix setting it clears every write bit; clearing it gives back the bits this run + // cleared from the file, or else the owner's write bit. + #[cfg(unix)] + let (back, file) = { + use std::os::unix::fs::{MetadataExt, PermissionsExt}; + let (mode, file) = (p.mode(), (m.dev(), m.ino())); + // Saved bits are given back only to a file that is still without write bits. + let saved = disk.cleared.get(&file).copied().filter(|_| mode & 0o222 == 0); + let back = if on { mode & 0o222 } else { saved.unwrap_or(0o200) }; + p.set_mode(if on { mode & !0o222 } else { mode | back }); + (back, file) + }; + #[cfg(not(unix))] + p.set_readonly(on); + std::fs::set_permissions(&target, p).map_err(|_| WRITE_FAILED)?; + #[cfg(unix)] + if !on { + disk.cleared.remove(&file); + } else if back != 0 && (disk.cleared.len() < MAX_ENTRIES || disk.cleared.contains_key(&file)) { + disk.cleared.insert(file, back); + } + Ok(()) + }); + if r.is_ok() { + disk.wrote(&target); + } + Ok(done(r)) +} + +/// `pick(kind, prompt, multiple, start)`: the file dialog of `kind` (`open`, `save` or `folder`), +/// which the run waits at in the app; elsewhere `{error}`. +fn pick(host: &Host, a: &[Data]) -> Result { + let kind = match arg_text(a, 0).as_str() { + "open" => PickerKind::Open, + "save" => PickerKind::Save, + _ => PickerKind::Folder, + }; + if cfg!(target_arch = "wasm32") { + return Ok(error(NO_WEB)); + } + let mut disk = host.disk.borrow_mut(); + if !disk.framed { + return Ok(error(NO_PICKER)); + } + if !host.can_wait.get() { + let name = match kind { + PickerKind::Open => "File.openDialog", + PickerKind::Save => "File.saveDialog", + PickerKind::Folder => "Folder.selectDialog", + }; + return Err(HostError::Error(format!( + "{name}: a file dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code" + ))); + } + let prompt = super::dialogs::cut_to(&arg_text(a, 1), super::dialogs::MAX_MESSAGE_BYTES).to_string(); + let start = Some(arg_text(a, 3)).filter(|s| !s.is_empty() && !too_long(s)); + let can_always = disk.script.is_some() && disk.data_dir.is_some(); + let multiple = kind == PickerKind::Open && matches!(a.get(2), Some(Data::Bool(true))); + let filters = if kind == PickerKind::Folder { Vec::new() } else { dialog_filters(&arg_text(a, 4)) }; + disk.picker = Some(ScriptPicker { kind, prompt, multiple, start, filters, can_always }); + Err(HostError::Wait) +} + +/// The most file types a dialog's filter gives, and the most extensions of one. +const MAX_FILTERS: usize = 32; +/// The most characters of a dialog's filter that are read. +const MAX_FILTER_CHARS: usize = 4096; + +/// The file types of a dialog's `filter`, a string such as `"JavaScript:*.jsx;All files:*.*"`: +/// each `name:pattern` starts a type, a pattern without a name adds to the type before it (the +/// first one starts a type named by the patterns), and patterns are separated by `,` or `;`. A +/// `*.ext` pattern gives the extension `ext`, and `*` and `*.*` give `*`, every file; other patterns +/// are left out, and so is a type left without extensions. Only types that give every file: none +/// (every file). +pub(crate) fn dialog_filters(filter: &str) -> Vec<(String, Vec)> { + let filter: String = filter.chars().take(MAX_FILTER_CHARS).collect(); + let mut out: Vec<(String, Vec)> = Vec::new(); + // Whether the last type was started by a pattern without a name, and is named by its patterns. + let mut unnamed = false; + for piece in filter.split([',', ';']).map(str::trim).filter(|p| !p.is_empty()) { + let (name, pattern) = match piece.split_once(':') { + Some((n, p)) => (Some(n.trim()), p.trim()), + None => (None, piece), + }; + let ext = match pattern { + "*" | "*.*" => Some("*".to_string()), + p => p + .strip_prefix("*.") + .filter(|e| !e.is_empty() && e.len() <= 32 && e.chars().all(|c| c.is_alphanumeric() || matches!(c, '_' | '-' | '.'))) + .map(str::to_string), + }; + match (name, out.last_mut()) { + (Some(n), _) => { + out.push((if n.is_empty() { pattern.to_string() } else { n.to_string() }, Vec::new())); + unnamed = false; + } + (None, None) => { + out.push((pattern.to_string(), Vec::new())); + unnamed = true; + } + (None, Some((name, _))) if unnamed && ext.is_some() && name.len() < 256 => { + name.push(';'); + name.push_str(pattern); + } + (None, Some(_)) => {} + } + if let (Some(ext), Some((_, exts))) = (ext, out.last_mut()) + && exts.len() < MAX_FILTERS + && !exts.contains(&ext) + { + exts.push(ext); + } + } + out.retain(|(_, exts)| !exts.is_empty()); + out.truncate(MAX_FILTERS); + if out.iter().all(|(_, exts)| exts.iter().all(|e| e == "*")) { + return Vec::new(); + } + out } fn read(host: &Host, a: &[Data]) -> Result { @@ -849,15 +2054,24 @@ fn execute(host: &Host, _: &[Data]) -> Result { Ok(error(NO_EXECUTE)) } +/// A name for a new file in the run's temporary folder. fn temp_name(host: &Host, _: &[Data]) -> Result { let mut disk = host.disk.borrow_mut(); disk.temps += 1; let name = format!("vc{:05}.tmp", disk.temps); - Ok(Data::String(temp_folder().join(name).to_string_lossy().into_owned())) + let dir = disk.temp_dir().unwrap_or_else(temp_folder); + Ok(Data::String(dir.join(name).to_string_lossy().into_owned())) } -fn locations_of(host: &Host, _: &[Data]) -> Result { - Ok(locations(&host.disk.borrow().home)) +/// `locations(place)`: the folders [`locations`] gives. The run's temporary folder and the script's +/// data folder are made only when `place` names them. +fn locations_of(host: &Host, a: &[Data]) -> Result { + let place = arg_text(a, 0); + let mut disk = host.disk.borrow_mut(); + let shown = |p: Option| p.map(|p| p.to_string_lossy().into_owned()); + let temp = if place == "temp" { shown(disk.temp_dir()) } else { None }; + let user_data = if place == "userData" { shown(disk.user_data_dir()) } else { None }; + Ok(locations(&disk.home, temp, user_data)) } fn encode_text(_: &Host, a: &[Data]) -> Result { @@ -890,9 +2104,10 @@ pub(super) fn install(realm: &mut Realm, link: &super::Link) -> Result<(), RunEr let value = |s: &str| HostItem::Value(Data::String(s.to_string())); let text = HostItem::Object(vec![ ("notOpen".into(), value(NOT_OPEN)), - ("noWrites".into(), value(NO_WRITES)), - ("noPicker".into(), value(NO_PICKER)), ("badMode".into(), value(BAD_MODE)), + ("noAlias".into(), value(NO_ALIAS)), + ("noHidden".into(), value(NO_HIDDEN)), + ("tooLarge".into(), value(TOO_LARGE)), ]); let system = if WINDOWS { "Windows" @@ -903,6 +2118,7 @@ pub(super) fn install(realm: &mut Realm, link: &super::Link) -> Result<(), RunEr }; let items = vec![ ("text".into(), text), + ("maxWrite".into(), HostItem::Value(Data::Number(MAX_FILE_BYTES as f64))), ("system".into(), value(system)), ("lineFeed".into(), value(if WINDOWS { "Windows" } else { "Unix" })), ("current".into(), unchecked(start_folder)), @@ -927,6 +2143,14 @@ pub(super) fn install(realm: &mut Realm, link: &super::Link) -> Result<(), RunEr ("list".into(), call(link, list)), ("resolve".into(), call(link, resolve)), ("execute".into(), call(link, execute)), + ("write".into(), call(link, write)), + ("copy".into(), call(link, copy)), + ("remove".into(), call(link, remove)), + ("rename".into(), call(link, rename)), + ("create".into(), call(link, create)), + ("setLength".into(), call(link, set_length)), + ("setReadonly".into(), call(link, set_readonly)), + ("pick".into(), call(link, pick)), ]; realm.define_file_classes(items) } @@ -985,7 +2209,7 @@ mod tests { #[test] fn masks_match_stars_and_question_marks_without_case() { - let matches = |mask: &str, name: &str| Mask::new(mask).matches(name, &mut { usize::MAX }) == Some(true); + let matches = |mask: &str, name: &str| Mask::with_case(mask, true).matches(name, &mut { usize::MAX }) == Some(true); assert!(matches("*.JSX", "a.jsx")); assert!(matches("a?c*", "abcdef")); assert!(!matches("*.txt", "a.jsx")); @@ -995,6 +2219,17 @@ mod tests { assert!(!matches("?", "")); } + #[test] + fn masks_match_case_where_the_file_system_tells_names_apart_by_case() { + let matches = |mask: &str, name: &str| Mask::with_case(mask, false).matches(name, &mut { usize::MAX }) == Some(true); + assert!(!matches("*.JSX", "a.jsx")); + assert!(matches("*.JSX", "a.JSX")); + assert!(matches("A?c*", "Abcdef")); + assert!(!matches("A?c*", "abcdef")); + assert_eq!(MASK_IGNORES_CASE, cfg!(any(windows, target_os = "macos"))); + assert_eq!(Mask::new("*.JSX").matches("a.jsx", &mut { usize::MAX }), Some(MASK_IGNORES_CASE)); + } + #[test] fn masks_stop_when_their_steps_run_out() { let mask = Mask::new(&format!("*{}b", "a".repeat(100))); diff --git a/crates/engine/src/script/mod.rs b/crates/engine/src/script/mod.rs index 53f6e18f75..8b4a0294d2 100644 --- a/crates/engine/src/script/mod.rs +++ b/crates/engine/src/script/mod.rs @@ -37,7 +37,8 @@ //! `alert`, `confirm` and `prompt` open dialogs ([`dialogs`]): in the app the run waits for the //! person's answer, and a run with nobody to ask takes its answers from `script.run`'s `answers`. //! -//! `File` and `Folder` read files inside the script's own folder ([`files`]). +//! `File` and `Folder` read files inside the script's own folder, and write in the run's temporary +//! folder, the script's data folder and what a person allowed it in a file dialog ([`files`]). //! //! A script with `#targetengine name` runs in that named engine, which the session keeps with the //! globals its runs leave, at most [`MAX_ENGINES`] of them with [`ENGINE_HEAP_BYTES`] of heap each @@ -102,6 +103,31 @@ pub const MAX_ARGS_BYTES: usize = 1 << 20; 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 most files a run's report names in `written`; past them the report has `writtenMore`. +pub const MAX_WRITTEN: usize = 4096; + +/// The files a run wrote, as its report names them: at most [`MAX_WRITTEN`], each once, in the +/// order they were first written, and whether it wrote more. +#[derive(Default)] +struct Written { + paths: Vec, + seen: std::collections::HashSet, + more: bool, +} + +impl Written { + fn add(&mut self, path: String) { + if self.seen.contains(&path) { + return; + } + if self.paths.len() >= MAX_WRITTEN { + self.more = true; + return; + } + self.seen.insert(path.clone()); + self.paths.push(path); + } +} /// The version `vc.api.version` gives. pub const API_VERSION: &str = "1.0"; @@ -255,9 +281,29 @@ struct KeptMap { struct KeptMaps { maps: std::collections::VecDeque, bytes: usize, + /// The SHA-256 of each source the engine's runs compiled (their scripts and what they + /// evaluated), at most [`MAX_ENGINE_CODE`], and whether there were more: a later run's kept file + /// grants are in force only for code they were kept for ([`files::Disk`]). + code: std::collections::BTreeSet, + code_full: bool, } +/// The most sources whose SHA-256 a named engine keeps. +pub const MAX_ENGINE_CODE: usize = 1024; + impl KeptMaps { + /// Adds the sources `code` (and whether a run had more than it counted) to the engine's code. + fn keep_code(&mut self, (code, more): (Vec, bool)) { + self.code_full |= more; + for hash in code { + if self.code.len() >= MAX_ENGINE_CODE && !self.code.contains(&hash) { + self.code_full = true; + } else { + self.code.insert(hash); + } + } + } + fn keep(&mut self, tag: u32, map: include::SourceMap, script: Option>) { let bytes = map.bytes() + script.as_ref().map_or(0, |s| s.len()); let limit = kept_map_bytes(); @@ -696,7 +742,7 @@ struct Host { waiting: Cell, log: RefCell>, log_bytes: Cell, - written: RefCell>, + written: RefCell, /// The run's number in its session, and the script's name, which its console lines carry. run: u64, name: Arc, @@ -813,6 +859,7 @@ impl Host { return; } let mut kept = kept.borrow_mut(); + kept.keep_code(self.disk.borrow().code()); kept.keep(tag, std::mem::take(&mut *self.script_map.borrow_mut()), Some(self.report_name.clone())); for (n, map) in std::mem::take(&mut *self.eval_maps.borrow_mut()).into_iter().enumerate() { match u32::try_from(n + 1).ok().and_then(|n| tag.checked_add(n)).filter(|t| *t != vectorcraft_js::UNKNOWN_SOURCE) { @@ -884,6 +931,35 @@ impl Host { Some(left) } + /// Adds `paths`, files the script's `File` and `Folder` objects wrote, to the report's `written`. + fn note_written(&self, paths: Vec) { + let mut written = self.written.borrow_mut(); + for path in paths { + written.add(path); + } + } + + /// Adds `writtenMore: true` to `report` when the run wrote more files than its `written` names. + fn more_written(&self, report: &mut Value) { + if self.written.borrow().more + && let Some(o) = report.as_object_mut() + { + o.insert("writtenMore".into(), json!(true)); + } + } + + /// Writes the files the script left open and adds every file written to the report's `written`. + /// → the files it could not write. + fn flush_files(&self) -> Vec { + let mut disk = self.disk.borrow_mut(); + let failed = disk.flush_all(); + disk.record_code(); + let paths = disk.take_written(); + drop(disk); + self.note_written(paths); + failed + } + fn over(&self, limit: &str) -> HostError { HostError::Abort(limit.to_string()) } @@ -1100,13 +1176,13 @@ fn step(s: &mut Session, host: &Host, id: &str, params: &Value) -> Result<(Value 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); + // The command reads and writes only where the script's own files may, and the open documents' files. + let gate = host.disk.borrow().gate(s.docs.iter().filter_map(|d| d.path.clone()).collect()); + let r = crate::file_access::with_script_gate(gate, || 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); - } + written.add(path); } drop(written); match r { @@ -1664,6 +1740,32 @@ impl Session { with_job(k, |j| j.host.dialogs.answer(&mut j.realm, answer)).unwrap_or(false) } + /// The file dialog (`File.openDialog`, `File.saveDialog`, `Folder.selectDialog` and the objects' + /// `openDlg`, `saveDlg` and `selectDlg`) the running script waits at. A run asked to stop no + /// longer waits. + pub fn script_picker(&self) -> Option { + if self.script_stop.is_set() { + return None; + } + self.script_key.as_ref().and_then(|k| with_job(k, |j| j.host.disk.borrow().picker.clone())).flatten() + } + + /// Gives the file dialog the running script waits at its answer: the paths the person picked + /// and allowed, or a denial. The next [`Session::script_pump`] goes on from the call. → false + /// when no file dialog waits. + pub fn script_pick(&mut self, answer: files::PickAnswer) -> bool { + let Some(k) = self.script_key.as_ref().filter(|_| !self.script_stop.is_set()) else { return false }; + with_job(k, |j| { + let Some(data) = j.host.disk.borrow_mut().answer(answer) else { return false }; + j.host.note_written(j.host.disk.borrow_mut().take_written()); + if let Err(e) = j.realm.answer(data) { + j.host.disk.borrow_mut().failed = Some(e); + } + true + }) + .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())) @@ -1790,7 +1892,17 @@ impl Session { realm.set_limits(limits); realm } - None => Realm::with_options(options, limits), + None => { + let mut realm = Realm::with_options(options, limits); + // Code the run evaluates withdraws the kept file grants not kept for it, before it runs. + let l = link.clone(); + realm.observe_code(move |units| { + if let Ok(h) = current(&l) { + h.disk.borrow_mut().saw_code(units); + } + }); + realm + } }; realm.share_interrupt(&self.script_stop); realm.set_data_limits(DataLimits::default()); @@ -1810,7 +1922,7 @@ impl Session { waiting: Cell::new(false), log: RefCell::new(Vec::new()), log_bytes: Cell::new(0), - written: RefCell::new(Vec::new()), + written: RefCell::new(Written::default()), run: self.script_runs, name: console::line_name(&name), console: RefCell::default(), @@ -1819,7 +1931,20 @@ impl Session { commands: RefCell::default(), run_nanos: Cell::new(0), dialogs: dialogs::Dialogs::new(self.script_frames, &realm, request.answers), - disk: RefCell::new(files::Disk::new(files.scope())), + disk: RefCell::new(files::Disk::new( + files.scope(), + files::Setup { + framed: self.script_frames, + script: request.file.clone(), + // The text with its included files, so a changed included file asks again. + source: expanded.as_ref().map_or_else(|_| request.source.clone(), |e| e.source.clone()), + data_dir: self.script_data_dir.clone(), + engine_code: kept_maps.as_ref().map_or_else(Default::default, |m| { + let m = m.borrow(); + (m.code.iter().cloned().collect(), m.code_full) + }), + }, + )), files: RefCell::new(files), script_map: RefCell::default(), eval_maps: RefCell::default(), @@ -1902,14 +2027,16 @@ impl Session { self.script_gone(key, console::Ending::Internal); return Some(Err(EngineError::Other(JOB_GONE.to_string()))); }; - if let Some(e) = job.host.dialogs.take_failure() { + let picker_failed = job.host.disk.borrow_mut().failed.take(); + if let Some(e) = job.host.dialogs.take_failure().or(picker_failed) { return Some(self.script_failed(job, &e)); } // A canceled request ends a sleep or a wait at this pump. if vectorcraft_doc::cancel::check().is_err() { self.script_stop.set(); } - if (job.host.waiting.get() || job.host.asleep().is_some() || job.host.dialogs.is_waiting()) && !self.script_stop.is_set() { + let picking = job.host.disk.borrow().picker.is_some(); + if (job.host.waiting.get() || job.host.asleep().is_some() || job.host.dialogs.is_waiting() || picking) && !self.script_stop.is_set() { JOBS.with(|jobs| jobs.borrow_mut().insert(key.id, job)); self.script_key = Some(key); return None; @@ -1949,6 +2076,9 @@ impl Session { fn script_failed(&mut self, job: Job, e: &RunError) -> Result { job.host.dialogs.stopped(); + job.host.disk.borrow_mut().picker = None; + // The run fails already; a file it could not write is left out of `written`. + let _ = job.host.flush_files(); let fuel_left = job.realm.fuel_left(); let (e, file) = located(&job.host, &job.realm, e); let mut report = failure_report(&job.name, &e, file.as_deref(), &job.host, fuel_left, job.realm.limits().fuel.saturating_sub(fuel_left)); @@ -1966,6 +2096,12 @@ impl Session { /// 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 { + let unwritten = job.host.flush_files(); + if !unwritten.is_empty() { + let message = format!("{UNWRITTEN_FILES}: {}", unwritten.join(", ")); + let e = RunError { kind: RunErrorKind::Thrown, message, line: 0, column: 0 }; + return self.script_failed(job, &e); + } // 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); @@ -2029,11 +2165,12 @@ impl Session { "ok": true, "name": job.name, "changed": changed_names, - "written": *host.written.borrow(), + "written": host.written.borrow().paths, "log": *host.log.borrow(), "fuelUsed": job.realm.limits().fuel - job.realm.fuel_left(), "hostCalls": host.calls.get(), }); + host.more_written(&mut report); close_run(self, host, &mut report, console::Ending::Finished); self.end_job(job, false); self.script_report = Some(report.clone()); @@ -2060,6 +2197,7 @@ impl Session { const OPEN_EDIT: &str = "a drag or an undo group is open; finish it before running a script"; const INVALID_RESULT: &str = "the script left a document that cannot be kept"; +const UNWRITTEN_FILES: &str = "Error: the script left open files that could not be written"; const JOB_GONE: &str = "the script's run is no longer available"; 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. @@ -2088,12 +2226,13 @@ fn failure_report(name: &str, e: &RunError, file: Option<&str>, host: &Host, fue "name": name, "line": e.line, "column": e.column, - "written": *host.written.borrow(), + "written": host.written.borrow().paths, "log": *host.log.borrow(), "fuelLeft": fuel_left, "fuelUsed": fuel_used, "hostCalls": host.calls.get(), }); + host.more_written(&mut report); if let (Some(file), Some(o)) = (file, report.as_object_mut()) { o.insert("file".into(), json!(file)); } diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 3e9ae56423..865d822652 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -90,6 +90,7 @@ impl Session { plugin_dir: None, scripts_dir: None, new_doc_profile_dir: None, + script_data_dir: None, plugin_output: None, plugin_install_approval: None, plugin_grants_from_requests: false, diff --git a/crates/engine/src/tests/script_io.rs b/crates/engine/src/tests/script_io.rs index e056ea2f7c..0d09bd2796 100644 --- a/crates/engine/src/tests/script_io.rs +++ b/crates/engine/src/tests/script_io.rs @@ -1,6 +1,7 @@ //! `File` and `Folder` in a script: their classes and names, reading inside the script's own folder, -//! the paths refused before anything is looked up, the read limits, and the parts that write, which -//! are not available. +//! the paths refused before anything is looked up, the read limits, writing in the run's temporary +//! folder, the script's data folder and what a person allowed in a file dialog, and the grants kept +//! for a script. use std::path::{Path, PathBuf}; @@ -267,10 +268,12 @@ fn script_file_oversize_refused_before_read() { #[test] fn script_files_read_at_most_32_mib_in_a_run() { let base = folder("total"); - write(&base.join("main/seven.bin"), &vec![b'a'; 7 << 20]); + for i in 0..5 { + write(&base.join(format!("main/seven{i}.bin")), &vec![b'a'; 7 << 20]); + } let mut s = Session::new(); let main = base.join("main/main.jsx"); - write(&main, b"var f = new File('seven.bin'); for (var i = 0; i < 5; i++) { f.open('r'); vc.log(i); }"); + write(&main, b"for (var i = 0; i < 5; i++) { new File('seven' + i + '.bin').open('r'); vc.log(i); }"); let e = s.execute("script.run", &json!({"path": main.to_string_lossy()})); assert!(e.is_err(), "the fifth open passes 32 MiB"); let report = s.script_report().unwrap(); @@ -279,6 +282,23 @@ fn script_files_read_at_most_32_mib_in_a_run() { let _ = std::fs::remove_dir_all(base); } +/// A file opened again once its objects closed counts only once toward the 32 MiB a run reads, and +/// a file open in two objects at once counts for each. +#[test] +fn script_file_opened_again_counts_once_toward_the_run_limit() { + let base = folder("reopencount"); + write(&base.join("main/seven.bin"), &vec![b'a'; 7 << 20]); + let mut s = Session::new(); + let main = base.join("main/main.jsx"); + write(&main, b"var f = new File('seven.bin'); for (var i = 0; i < 8; i++) { f.open('r'); f.close(); } vc.log('again');"); + let r = s.execute("script.run", &json!({"path": main.to_string_lossy()})).unwrap(); + assert_eq!(r["log"], json!(["again"])); + write(&main, b"for (var i = 0; i < 5; i++) { new File('seven.bin').open('r'); vc.log(i); }"); + assert!(s.execute("script.run", &json!({"path": main.to_string_lossy()})).is_err(), "five objects hold five copies"); + assert_eq!(s.script_report().unwrap()["log"], json!([0, 1, 2, 3])); + let _ = std::fs::remove_dir_all(base); +} + #[test] fn script_files_have_at_most_256_open() { let base = folder("open"); @@ -311,7 +331,9 @@ fn script_folder_getfiles_stays_inside_scope() { try { d.getFiles(function () { throw new Error('stop'); }); } catch (e) { vc.log(e.message); }\n\ vc.log([new Folder('nope').getFiles(), d.getFiles('*.jsx')[0] instanceof File]);", ); - assert_eq!(log, json!([["C.JSX", "a.jsx", "main.jsx"], ["sub"], [["b.txt"], 5, null, DENIED], "stop", [null, true]])); + // Where case does not matter to the file system, the mask matches without regard to case. + let jsx = if cfg!(any(windows, target_os = "macos")) { json!(["C.JSX", "a.jsx", "main.jsx"]) } else { json!(["a.jsx", "main.jsx"]) }; + assert_eq!(log, json!([jsx, ["sub"], [["b.txt"], 5, null, DENIED], "stop", [null, true]])); let many = base.join("main/many"); for i in 0..=crate::script::files::MAX_ENTRIES { write(&many.join(format!("{i:04}.txt")), b""); @@ -393,23 +415,28 @@ fn script_file_encoding_binary_ascii() { let _ = std::fs::remove_dir_all(base); } +/// A script's own folder is only read: writing there, and anywhere it was not given, is refused, +/// and with nobody to ask its file dialogs give `null`. Aliases and `execute` are not available. #[test] -fn script_file_writes_dialogs_and_execute_are_not_available() { +fn script_file_writes_outside_its_places_and_headless_dialogs_are_refused() { let base = folder("writes"); write(&base.join("main/keep.txt"), b"keep"); + let outside = base.join("outside.txt").to_string_lossy().into_owned(); let r = run( &base, - "var f = new File('keep.txt'); var n = new File('new.txt');\n\ - var out = [n.open('w'), n.error, f.open('a'), f.open('e'), f.open('x'), f.error, f.write('x'), f.remove(), f.copy('c.txt'), f.rename('r.txt')];\n\ - out.push(new Folder('made').create(), f.openDlg(), f.error, File.openDialog(), Folder.selectDialog(), f.execute(), f.error);\n\ - f.hidden = true; out.push(f.error, f.hidden); f.error = ''; out.push(f.error);\n\ - vc.log(out);", + &format!( + "var f = new File('keep.txt'); var n = new File('new.txt'); var o = new File({outside:?});\n\ + var out = [n.open('w'), n.error, f.open('a'), f.open('e'), f.open('x'), f.error, f.remove(), f.copy('c.txt'), f.rename('r.txt'), o.open('w')];\n\ + out.push(new Folder('made').create(), f.openDlg(), f.error, File.openDialog(), Folder.selectDialog(), f.execute(), f.error);\n\ + f.hidden = true; out.push(f.error, f.hidden, f.createAlias('l'), f.error); f.error = ''; out.push(f.error);\n\ + vc.log(out);" + ), ); assert_eq!( r["log"], json!([[ false, - "Script file writing is not available", + DENIED, false, false, false, @@ -420,20 +447,1222 @@ fn script_file_writes_dialogs_and_execute_are_not_available() { false, false, null, - "Script file dialogs are not available", + "Script file dialogs need a person to answer them", null, null, false, "Script files cannot be opened in another application", - "Script file writing is not available", + "Script file hidden setting cannot be changed", false, + false, + "Script files cannot make aliases", "" ]]) ); assert_eq!(r["hostCallCounts"]["fileExecutes"], 1); - assert!(r["hostCallCounts"]["fileCalls"].as_u64().unwrap() > 0); + assert_eq!(r["written"], json!([])); assert_eq!(std::fs::read(base.join("main/keep.txt")).unwrap(), b"keep"); assert!(!base.join("main/new.txt").exists() && !base.join("main/made").exists() && !base.join("main/c.txt").exists()); + assert!(!Path::new(&outside).exists()); + let _ = std::fs::remove_dir_all(base); +} + +/// A session whose scripts keep their data folders in `base/settings/Script Data`. +fn with_data(base: &Path) -> Session { + let mut s = Session::new(); + s.attach_script_data(base.join("settings/Script Data")); + s +} + +/// Runs `main/main.jsx` in `base` with the text `text` in `s`. +fn run_in(s: &mut Session, base: &Path, text: &str) -> Result { + let main = base.join("main/main.jsx"); + write(&main, text.as_bytes()); + s.execute("script.run", &json!({"path": main.to_string_lossy()})) +} + +/// `Folder.userData` is the script's own folder, kept between runs, and `Folder.temp` the run's, +/// deleted when it ends. `write` joins its values, `writeln` adds the `lineFeed`'s line end, and a +/// byte order mark is written as the script writes it. +#[test] +fn script_files_write_in_the_temporary_and_data_folders() { + let base = folder("userdata"); + let mut s = with_data(&base); + let r = run_in( + &mut s, + &base, + "var out = [], u = new File(Folder.userData.fsName + '/notes.txt');\n\ + out.push(u.open('w'), u.write('a', 1, true), u.writeln('b'), u.close());\n\ + u.lineFeed = 'Windows'; out.push(u.open('a'), u.writeln('c'), u.close());\n\ + u.open('r'); out.push(u.read()); u.close();\n\ + var t = new File(Folder.temp.fsName + '/t.txt'); out.push(t.open('w'), t.write('\\uFEFFx'), t.close(), t.length);\n\ + var m = new File(); out.push(m.open('w'), m.parent.fsName === Folder.temp.fsName);\n\ + vc.log(out); vc.log(u.fsName); vc.log(Folder.temp.fsName);", + ) + .unwrap(); + assert_eq!(r["log"][0], json!([true, true, true, true, true, true, true, "a1trueb\nc\r\n", true, true, true, 4, true, true])); + let notes = PathBuf::from(r["log"][1].as_str().unwrap()); + let temp = PathBuf::from(r["log"][2].as_str().unwrap()); + assert_eq!(std::fs::read(¬es).unwrap(), b"a1trueb\nc\r\n"); + assert!(notes.starts_with(std::fs::canonicalize(base.join("settings/Script Data")).unwrap()), "{notes:?}"); + assert!(!temp.exists(), "the run's temporary folder is deleted when it ends"); + let written: Vec<&str> = r["written"].as_array().unwrap().iter().filter_map(Value::as_str).collect(); + assert!(written.contains(¬es.to_string_lossy().as_ref()), "{written:?}"); + let again = run_in(&mut s, &base, "var u = new File(Folder.userData.fsName + '/notes.txt'); u.open('r'); vc.log(u.read());").unwrap(); + assert_eq!(again["log"], json!(["a1trueb\nc\r\n"]), "a script's data folder is kept between runs"); + let _ = std::fs::remove_dir_all(base); +} + +/// The open modes, the encodings that cannot hold a character, `copy` over a file, `remove` of a +/// folder only when it is empty, `rename` refusing a name in use, `create`, and setting `length` and +/// `readonly`. +#[test] +fn script_file_modes_encodings_and_changes() { + let base = folder("changes"); + let r = run( + &base, + "var d = Folder.temp.fsName, out = [];\n\ + var e = new File(d + '/missing.txt'); out.push(e.open('e'), e.error);\n\ + var a = new File(d + '/a.txt'); a.encoding = 'ASCII'; out.push(a.open('w'), a.write('caf\\u00e9'), a.error, a.write('cafe'), a.close(), a.length);\n\ + var b = new File(d + '/b.bin'); b.encoding = 'BINARY'; b.open('w'); b.write('\\u0141B'); b.close();\n\ + b.encoding = 'BINARY'; b.open('r'); out.push(b.read()); b.close();\n\ + out.push(a.copy(d + '/b.bin'), new File(d + '/b.bin').length);\n\ + var f = new Folder(d + '/x/y'); out.push(f.create(), f.exists);\n\ + var x = new Folder(d + '/x'); out.push(x.remove(), x.error, f.remove(), f.exists);\n\ + out.push(a.rename('b.bin'), a.error, a.rename('c.txt'), a.name, a.exists, new File(d + '/a.txt').exists);\n\ + a.length = 2; out.push(a.length); a.length = 6; out.push(a.length);\n\ + a.readonly = true; out.push(a.readonly); a.readonly = false; out.push(a.readonly);\n\ + out.push(a.remove(), a.exists);\n\ + vc.log(out);", + ); + assert_eq!( + r["log"], + json!([[ + false, + "Script file does not exist", + true, + false, + "Script file cannot encode the text", + true, + true, + 4, + "AB", + true, + 4, + true, + true, + false, + "Script folder is not empty", + true, + false, + false, + "Script file name is already in use", + true, + "c.txt", + true, + false, + 2, + 6, + true, + false, + true, + false + ]]) + ); + let _ = std::fs::remove_dir_all(base); +} + +/// Setting `length` while the file is open changes what the open file holds, so closing it keeps +/// the new length. +#[test] +fn script_file_length_changes_reach_an_open_file() { + let base = folder("openlength"); + let r = run( + &base, + "var o = new File(Folder.temp.fsName + '/l.txt'); o.open('w'); o.write('abc');\n\ + new File(o.fsName).length = 1; o.write('d'); o.close();\n\ + o.open('r'); vc.log([o.read(), o.length]); o.close();", + ); + assert_eq!(r["log"], json!([["ad", 2]])); + let _ = std::fs::remove_dir_all(base); +} + +/// A file is kept as it was when `open('w')` is given an encoding that is not one and when it is +/// copied onto itself, and the changes an open file holds stay to be written when writing them fails. +#[test] +fn script_file_writes_keep_what_they_cannot_change() { + let base = folder("keeps"); + let r = run( + &base, + "var d = Folder.temp.fsName, out = [];\n\ + var k = new File(d + '/k.txt'); k.open('w'); k.write('keep'); k.close();\n\ + k.encoding = 'nope'; out.push(k.open('w'), k.error);\n\ + k.encoding = 'UTF-8'; k.open('r'); out.push(k.read()); k.close();\n\ + out.push(k.copy(k.fsName), k.length);\n\ + var w = new File(d + '/w.txt'); w.open('w'); w.write('abc'); new File(w.fsName).readonly = true;\n\ + var q = new File(w.fsName); q.length = 1; out.push(q.error);\n\ + new File(w.fsName).readonly = false; out.push(w.close()); w.open('r'); out.push(w.read()); w.close();\n\ + vc.log(out);", + ); + assert_eq!(r["log"], json!([[false, "Script file cannot be decoded", "keep", true, 4, "Script file could not be written", true, "abc"]])); + let _ = std::fs::remove_dir_all(base); +} + +/// A file whose `close` could not write it stays to be written when the run ends. +#[test] +fn script_file_close_that_cannot_write_keeps_the_changes() { + let base = folder("closefail"); + let mut s = with_data(&base); + let r = run_in( + &mut s, + &base, + "var u = new File(Folder.userData.fsName + '/c.txt'); u.open('w'); u.write('kept');\n\ + new File(u.fsName).readonly = true; var out = [u.close(), u.error]; new File(u.fsName).readonly = false;\n\ + vc.log(out); vc.log(u.fsName);", + ) + .unwrap(); + assert_eq!(r["log"][0], json!([false, "Script file could not be written"])); + assert_eq!(std::fs::read(r["log"][1].as_str().unwrap()).unwrap(), b"kept"); + let _ = std::fs::remove_dir_all(base); +} + +/// `changePath` on an object whose changes could not be written gives false with `error` set, and +/// the object keeps its path. +#[test] +fn script_file_change_path_that_cannot_write_keeps_the_path() { + let base = folder("changepathfail"); + let mut s = with_data(&base); + let r = run_in( + &mut s, + &base, + "var u = new File(Folder.userData.fsName + '/p.txt'); u.open('w'); u.write('kept'); var was = u.fsName;\n\ + new File(was).readonly = true; var out = [u.changePath(Folder.userData.fsName + '/q.txt'), u.error, u.fsName == was];\n\ + new File(was).readonly = false; vc.log(out);", + ) + .unwrap(); + assert_eq!(r["log"][0], json!([false, "Script file could not be written", true])); + let _ = std::fs::remove_dir_all(base); +} + +/// A file opened again after a `close` that could not write it keeps what was written after it was +/// opened again, and the earlier changes do not replace it when the run ends. +#[test] +fn script_file_opened_again_after_a_failed_close_keeps_the_later_text() { + let base = folder("reopen"); + let mut s = with_data(&base); + let r = run_in( + &mut s, + &base, + "var u = new File(Folder.userData.fsName + '/r.txt'); u.open('w'); u.write('old');\n\ + new File(u.fsName).readonly = true; var out = [u.close()]; new File(u.fsName).readonly = false;\n\ + out.push(u.open('w'), u.write('new'), u.close()); vc.log(out); vc.log(u.fsName);", + ) + .unwrap(); + assert_eq!(r["log"][0], json!([false, true, true, true])); + assert_eq!(std::fs::read(r["log"][1].as_str().unwrap()).unwrap(), b"new"); + let _ = std::fs::remove_dir_all(base); +} + +/// A write that would pass the run's 32 MiB of writing ends the run, and its text is not written. +#[test] +fn script_file_write_past_the_run_limit_is_not_written() { + let base = folder("runlimit"); + let mut s = with_data(&base); + let r = run_in( + &mut s, + &base, + "var t = 'x'; while (t.length < 4194304) t += t;\n\ + var f = new File(Folder.userData.fsName + '/f.bin'); f.encoding = 'UTF-16';\n\ + for (var k = 0; k < 4; k++) { f.open('w'); f.write(t); f.close(); }\n\ + var g = new File(Folder.userData.fsName + '/g.txt'); vc.log(g.fsName); g.open('w'); g.write('over');", + ); + assert!(r.is_err()); + let report = s.script_report().unwrap(); + assert!(report["message"].as_str().unwrap().contains("32 MiB"), "{report}"); + assert_eq!(std::fs::read(report["log"][0].as_str().unwrap()).unwrap(), b"", "{report}"); + let _ = std::fs::remove_dir_all(base); +} + +/// `remove` and `rename` of a file that is open elsewhere: a removed file is not written again when +/// the run ends, a renamed one is written under its new name, and an object whose own changes could +/// not be written does not remove or rename its file. +#[test] +fn script_file_remove_and_rename_of_an_open_file() { + let base = folder("openmove"); + let mut s = with_data(&base); + let r = run_in( + &mut s, + &base, + "var d = Folder.userData.fsName, out = [];\n\ + var a = new File(d + '/a.txt'); a.open('w'); a.write('a'); out.push(new File(a.fsName).remove());\n\ + var b = new File(d + '/b.txt'); b.open('w'); b.write('b'); var c = new File(b.fsName); out.push(c.rename('c.txt'), b.close());\n\ + var e = new File(d + '/e.txt'); e.open('w'); e.write('e'); new File(e.fsName).readonly = true;\n\ + out.push(e.remove(), e.error, e.exists); new File(e.fsName).readonly = false;\n\ + vc.log(out); vc.log(d);", + ) + .unwrap(); + assert_eq!(r["log"][0], json!([true, true, true, false, "Script file could not be written", true])); + let d = PathBuf::from(r["log"][1].as_str().unwrap()); + assert!(!d.join("a.txt").exists() && !d.join("b.txt").exists()); + assert_eq!(std::fs::read(d.join("c.txt")).unwrap(), b"b"); + assert_eq!(std::fs::read(d.join("e.txt")).unwrap(), b"e", "the run's end writes the changes the failed close kept"); + let _ = std::fs::remove_dir_all(base); +} + +/// `copy` of a file that is open copies what the open file holds, and an object that has the target +/// open then holds the copy. +#[test] +fn script_file_copy_of_an_open_file_has_its_changes() { + let base = folder("copyopen"); + let r = run( + &base, + "var d = Folder.temp.fsName, f = new File(d + '/f.txt'); f.open('w'); f.write('new');\n\ + var out = [f.copy(d + '/g.txt')]; var g = new File(d + '/g.txt'); g.open('r'); out.push(g.read()); g.close(); vc.log(out);", + ); + assert_eq!(r["log"], json!([[true, "new"]])); + let r = run( + &base, + "var d = Folder.temp.fsName, s = new File(d + '/s.txt'); s.open('w'); s.write('copied'); s.close();\n\ + var t = new File(d + '/t.txt'); t.open('w'); t.write('old'); var out = [s.copy(t.fsName), t.close()];\n\ + t.open('r'); out.push(t.read()); t.close(); vc.log(out);", + ); + assert_eq!(r["log"], json!([[true, true, "copied"]]), "an open target holds the copy"); + let _ = std::fs::remove_dir_all(base); +} + +/// A grant that would make the grants file larger than it may be read is not kept, and the grants +/// file keeps the grants it had. +#[test] +fn script_file_grants_file_stays_within_its_size_limit() { + let base = folder("bigstore"); + let out = base.join("picked/out.txt"); + std::fs::create_dir_all(out.parent().unwrap()).unwrap(); + let store = base.join("settings/Script Grants.json"); + let grants = + |path: String| json!({"version": 1, "grants": [{"script": "x", "sha256": "y", "code": [], "path": path, "write": false, "folder": false}]}); + let empty = serde_json::to_vec_pretty(&grants(String::new())).unwrap().len(); + let full = serde_json::to_vec_pretty(&grants("p".repeat((4 << 20) - 64 - empty))).unwrap(); + write(&store, &full); + let mut s = with_data(&base); + assert_eq!(s.execute("script.grants", &json!({})).unwrap()["grants"].as_array().unwrap().len(), 1); + start_framed(&mut s, &base, "var f = File.saveDialog('p'); vc.log(f === null ? null : f.fsName);"); + assert!(pump_to_picker(&mut s).is_none()); + assert!(s.script_pick(crate::script::files::PickAnswer::Allow { paths: vec![out.to_string_lossy().into_owned()], always: true })); + let _ = pump_to_picker(&mut s).unwrap(); + assert_eq!(std::fs::read(&store).unwrap(), full, "the grants file is left as it was"); + assert_eq!(s.execute("script.grants", &json!({})).unwrap()["grants"].as_array().unwrap().len(), 1); + let _ = std::fs::remove_dir_all(base); +} + +/// `copy` of a file over 8 MiB is refused, as opening one is. +#[test] +fn script_file_copy_is_held_to_the_file_limit() { + let base = folder("bigcopy"); + write(&base.join("main/big.bin"), &vec![0u8; 8 * 1024 * 1024 + 1]); + let r = run(&base, "var b = new File('big.bin'); vc.log([b.copy(Folder.temp.fsName + '/b.bin'), b.error]);"); + assert_eq!(r["log"], json!([[false, "Script file exceeds 8 MiB"]])); + let _ = std::fs::remove_dir_all(base); +} + +/// The run's 32 MiB of writes counts what setting `length` adds to each object the file is open in, +/// as each holds its own bytes. +#[test] +fn script_file_length_counts_the_growth_of_every_open_object() { + let base = folder("lengthheld"); + let mut s = Session::new(); + let main = base.join("main/main.jsx"); + write( + &main, + b"var p = Folder.temp.fsName + '/l.bin'; var w = new File(p); w.open('w'); w.close();\n\ + var all = []; for (var i = 0; i < 5; i++) { var f = new File(p); f.open('e'); all.push(f); }\n\ + vc.log('open'); new File(p).length = 7 * 1024 * 1024; vc.log('grown');", + ); + assert!(s.execute("script.run", &json!({"path": main.to_string_lossy()})).is_err(), "five objects grow by 7 MiB each"); + let report = s.script_report().unwrap(); + assert_eq!(report["log"], json!(["open"])); + assert!(report["message"].as_str().unwrap().contains("32 MiB"), "{report}"); + let _ = std::fs::remove_dir_all(base); +} + +/// `copy` onto another name of the same file, a hard link, keeps the file's bytes, and what the +/// source's open object holds is in the file when `copy` returns. +#[test] +fn script_file_copy_onto_a_hard_link_of_itself_keeps_the_file() { + let base = folder("copylink"); + let picked = base.join("picked"); + write(&picked.join("a.txt"), b"keep"); + std::fs::hard_link(picked.join("a.txt"), picked.join("b.txt")).unwrap(); + let mut s = Session::new(); + start_framed( + &mut s, + &base, + "var p = Folder.selectDialog('p'); var a = new File(p.fsName + '/a.txt'), b = new File(p.fsName + '/b.txt');\n\ + a.open('w'); a.write('new'); var out = [a.copy(b.fsName)]; b.open('r'); out.push(b.read()); b.close(); a.close(); vc.log(out);", + ); + assert!(pump_to_picker(&mut s).is_none()); + assert!(s.script_pick(crate::script::files::PickAnswer::Allow { paths: vec![picked.to_string_lossy().into_owned()], always: false })); + let r = pump_to_picker(&mut s).unwrap().unwrap(); + assert_eq!(r["log"], json!([[true, "new"]])); + assert_eq!(std::fs::read(picked.join("a.txt")).unwrap(), b"new"); + assert_eq!(std::fs::read(picked.join("b.txt")).unwrap(), b"new"); + let _ = std::fs::remove_dir_all(base); +} + +/// The run's 32 MiB of writes counts the copy each open object of `copy`'s target takes. +#[test] +fn script_file_copy_counts_the_bytes_each_open_object_of_the_target_takes() { + let base = folder("copyheld"); + write(&base.join("main/seven.bin"), &vec![b'a'; 7 << 20]); + let mut s = Session::new(); + let main = base.join("main/main.jsx"); + write( + &main, + b"var t = Folder.temp.fsName + '/t.bin'; var w = new File(t); w.open('w'); w.close();\n\ + var all = []; for (var i = 0; i < 5; i++) { var f = new File(t); f.open('e'); all.push(f); }\n\ + vc.log('open'); vc.log(new File('seven.bin').copy(t));", + ); + assert!(s.execute("script.run", &json!({"path": main.to_string_lossy()})).is_err(), "five objects take 7 MiB each"); + let report = s.script_report().unwrap(); + assert_eq!(report["log"], json!(["open"])); + assert!(report["message"].as_str().unwrap().contains("32 MiB"), "{report}"); + let _ = std::fs::remove_dir_all(base); +} + +/// `write` joins its values only for an open file, and stops joining once the text is longer than +/// any file a script writes: the values after that are not turned into text. +#[test] +fn script_file_write_stops_joining_past_the_file_limit() { + let base = folder("writejoin"); + let r = run( + &base, + "var seen = 0, late = { toString: function () { seen++; return 'x'; } };\n\ + var f = new File(Folder.temp.fsName + '/j.txt'); var closed = [f.write(late), seen];\n\ + var s = new Array((1 << 20) + 1).join('x'), a = []; for (var k = 0; k < 17; k++) a.push(s); a.push(late);\n\ + f.open('w'); var big = f.write.apply(f, a); vc.log([closed, big, f.error, seen, f.write('ok'), f.close(), f.length]);", + ); + assert_eq!(r["log"], json!([[[false, 0], false, "Script file exceeds 8 MiB", 0, true, true, 2]])); + let _ = std::fs::remove_dir_all(base); +} + +/// The report names at most 4,096 files a run wrote, each once, and says when it wrote more. +#[test] +fn script_reports_name_at_most_4096_written_files() { + let base = folder("manywritten"); + let r = run( + &base, + "var d = Folder.temp.fsName; for (var k = 0; k < 4100; k++) { var f = new File(d + '/' + k + '.txt'); f.open('w'); f.close(); f.open('w'); f.close(); }", + ); + let written = r["written"].as_array().unwrap(); + assert_eq!(written.len(), crate::script::MAX_WRITTEN, "{}", written.len()); + assert_eq!(written.iter().filter_map(Value::as_str).collect::>().len(), written.len()); + assert_eq!(r["writtenMore"], true); + let few = run(&base, "var f = new File(Folder.temp.fsName + '/one.txt'); f.open('w'); f.close();"); + assert_eq!((few["written"].as_array().map(Vec::len), few.get("writtenMore")), (Some(1), None)); + let _ = std::fs::remove_dir_all(base); +} + +/// A kept grant stays on the real path it was kept for: when a link to another folder takes the +/// granted folder's place, the next run is not granted the folder the link leads to. +#[cfg(unix)] +#[test] +fn script_file_grants_do_not_follow_a_link_put_in_the_granted_place() { + let base = folder("grantlink"); + let granted = base.join("picked/granted"); + write(&granted.join("s.txt"), b"mine"); + write(&base.join("away/s.txt"), b"secret"); + let text = format!( + "var t = new File({:?}), u = new File({:?});\n\ + if (t.open('r')) vc.log(['kept', t.read()]); else if (u.open('r')) vc.log(['away', u.read()]);\n\ + else vc.log(Folder.selectDialog('p') ? 'asked' : null);", + granted.join("s.txt").to_string_lossy(), + base.join("away/s.txt").to_string_lossy() + ); + let mut s = with_data(&base); + start_framed(&mut s, &base, &text); + assert!(pump_to_picker(&mut s).is_none()); + assert!(s.script_pick(crate::script::files::PickAnswer::Allow { paths: vec![granted.to_string_lossy().into_owned()], always: true })); + assert_eq!(pump_to_picker(&mut s).unwrap().unwrap()["log"], json!(["asked"])); + start_framed(&mut s, &base, &text); + assert_eq!(pump_to_picker(&mut s).unwrap().unwrap()["log"], json!([["kept", "mine"]])); + std::fs::rename(&granted, base.join("picked/moved")).unwrap(); + std::os::unix::fs::symlink(base.join("away"), &granted).unwrap(); + start_framed(&mut s, &base, &text); + assert!(pump_to_picker(&mut s).is_none(), "the run asks again instead of reading where the link leads"); + s.script_pick(crate::script::files::PickAnswer::Deny); + let _ = pump_to_picker(&mut s); + let _ = std::fs::remove_dir_all(base); +} + +/// A folder granted in a file dialog cannot have a folder in it renamed when that folder holds the +/// settings folder. +#[test] +fn script_file_rename_does_not_move_the_settings_folder() { + let base = folder("moveup"); + let mut s = Session::new(); + s.attach_script_data(base.join("cfg/settings/Script Data")); + std::fs::create_dir_all(base.join("cfg/settings")).unwrap(); + start_framed(&mut s, &base, "var p = Folder.selectDialog('p'); var c = new Folder(p.fsName + '/cfg'); vc.log([c.rename('cfg2'), c.error]);"); + assert!(pump_to_picker(&mut s).is_none()); + assert!(s.script_pick(crate::script::files::PickAnswer::Allow { paths: vec![base.to_string_lossy().into_owned()], always: false })); + let r = pump_to_picker(&mut s).unwrap().unwrap(); + assert_eq!(r["log"], json!([[false, DENIED]])); + assert!(base.join("cfg/settings").is_dir()); + let _ = std::fs::remove_dir_all(base); +} + +/// Where case does not matter, a folder named in another case is still the folder that holds the +/// settings folder, or the settings folder itself: it is not renamed or removed. +#[cfg(any(windows, target_os = "macos"))] +#[test] +fn script_file_rename_does_not_move_the_settings_folder_named_in_another_case() { + let base = folder("moveupcase"); + let mut s = Session::new(); + s.attach_script_data(base.join("cfg/settings/Script Data")); + std::fs::create_dir_all(base.join("cfg/settings")).unwrap(); + start_framed( + &mut s, + &base, + "var p = Folder.selectDialog('p'); var c = new Folder(p.fsName + '/CFG'), d = new Folder(p.fsName + '/cfg/SETTINGS');\n\ + vc.log([c.rename('cfg2'), c.error, d.rename('s2'), d.error, d.remove(), d.error]);", + ); + assert!(pump_to_picker(&mut s).is_none()); + assert!(s.script_pick(crate::script::files::PickAnswer::Allow { paths: vec![base.to_string_lossy().into_owned()], always: false })); + let r = pump_to_picker(&mut s).unwrap().unwrap(); + assert_eq!(r["log"], json!([[false, DENIED, false, DENIED, false, DENIED]])); + assert!(base.join("cfg/settings").is_dir()); + let _ = std::fs::remove_dir_all(base); +} + +/// Where case matters, a rename to a name that differs in case alone does not replace the other file. +#[cfg(target_os = "linux")] +#[test] +fn script_file_rename_keeps_a_file_that_differs_in_case() { + let base = folder("casename"); + let r = run( + &base, + "var d = Folder.temp.fsName, a = new File(d + '/a.txt'), b = new File(d + '/A.txt');\n\ + a.open('w'); a.write('a'); a.close(); b.open('w'); b.write('B'); b.close();\n\ + var out = [a.rename('A.txt'), a.error]; b.open('r'); out.push(b.read()); b.close(); vc.log(out);", + ); + assert_eq!(r["log"], json!([[false, "Script file name is already in use", "B"]])); + let _ = std::fs::remove_dir_all(base); +} + +/// A script's data folder that is a link is not used: the folder it leads to is not granted. +#[cfg(unix)] +#[test] +fn script_data_folder_that_is_a_link_is_not_granted() { + let base = folder("datalink"); + let mut s = with_data(&base); + let r = run_in(&mut s, &base, "vc.log(Folder.userData.fsName);").unwrap(); + let data = PathBuf::from(r["log"][0].as_str().unwrap()); + std::fs::remove_dir(&data).unwrap(); + std::fs::create_dir_all(base.join("away")).unwrap(); + std::os::unix::fs::symlink(base.join("away"), &data).unwrap(); + let text = format!( + "var d = Folder.userData; var w = new File({:?}); vc.log([d === null, w.open('w'), w.error]);", + base.join("away/x.txt").to_string_lossy() + ); + let r = run_in(&mut s, &base, &text).unwrap(); + assert_eq!(r["log"], json!([[true, false, DENIED]])); + assert!(!base.join("away/x.txt").exists()); + let _ = std::fs::remove_dir_all(base); +} + +/// A data folder that is a link is not used: no script's `Folder.userData` is made in the folder it +/// leads to. +#[cfg(unix)] +#[test] +fn script_data_folders_in_a_data_folder_that_is_a_link_are_not_granted() { + let base = folder("datadirlink"); + let mut s = with_data(&base); + let r = run_in(&mut s, &base, "vc.log(Folder.userData.fsName);").unwrap(); + let key = PathBuf::from(r["log"][0].as_str().unwrap()).file_name().unwrap().to_owned(); + let data = base.join("settings/Script Data"); + std::fs::remove_dir_all(&data).unwrap(); + std::fs::create_dir_all(base.join("away")).unwrap(); + std::os::unix::fs::symlink(base.join("away"), &data).unwrap(); + let text = format!( + "var d = Folder.userData; var w = new File({:?}); vc.log([d === null, w.open('w'), w.error]);", + base.join("away").join(&key).join("x.txt").to_string_lossy() + ); + let r = run_in(&mut s, &base, &text).unwrap(); + assert_eq!(r["log"], json!([[true, false, DENIED]])); + assert!(!base.join("away").join(&key).exists()); + let _ = std::fs::remove_dir_all(base); +} + +/// An open file whose folder was replaced by a link before it was written is not written through +/// the link. +#[cfg(unix)] +#[test] +fn script_files_are_not_written_through_a_link_put_in_place_of_their_folder() { + let base = folder("parentlink"); + let mut s = with_data(&base); + std::fs::create_dir_all(base.join("away")).unwrap(); + // The run opens and changes `sub/f.txt` in its data folder and waits on a file dialog, while + // another program puts a link to `away` in place of `sub`. + start_framed( + &mut s, + &base, + "var d = Folder.userData.fsName, f = new File(d + '/sub/f.txt');\n\ + var before = [new Folder(d + '/sub').create(), f.open('w'), f.write('x')];\n\ + File.openDialog('p'); vc.log([before, f.close(), f.error]);", + ); + assert!(pump_to_picker(&mut s).is_none()); + let data = std::fs::read_dir(base.join("settings/Script Data")).unwrap().next().unwrap().unwrap().path(); + std::fs::rename(data.join("sub"), data.join("old")).unwrap(); + std::os::unix::fs::symlink(base.join("away"), data.join("sub")).unwrap(); + assert!(s.script_pick(crate::script::files::PickAnswer::Deny)); + // The file stays unwritten, so the run's end fails the run as for any file it could not write. + let e = pump_to_picker(&mut s).unwrap().unwrap_err().to_string(); + assert!(e.contains("left open files that could not be written"), "{e}"); + assert!(!base.join("away/f.txt").exists()); + let _ = std::fs::remove_dir_all(base); +} + +/// On Unix, `readonly` clears the write bits and clearing it gives the file the bits it had. +#[cfg(unix)] +#[test] +fn script_file_readonly_keeps_the_other_permissions() { + use std::os::unix::fs::PermissionsExt; + let base = folder("modes"); + let mut s = with_data(&base); + let r = run_in(&mut s, &base, "var u = new File(Folder.userData.fsName + '/m.txt'); u.open('w'); u.close(); vc.log(u.fsName);").unwrap(); + let path = PathBuf::from(r["log"][0].as_str().unwrap()); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o640)).unwrap(); + let text = format!( + "Folder.userData; var u = new File({:?}); u.readonly = true; var a = u.readonly; u.readonly = false; vc.log([a, u.readonly]);", + path.to_string_lossy() + ); + let r = run_in(&mut s, &base, &text).unwrap(); + assert_eq!(r["log"], json!([[true, false]])); + assert_eq!(std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o640); + let _ = std::fs::remove_dir_all(base); +} + +/// Clearing `readonly` gives back every write bit that setting it cleared in the run, also after a +/// rename, and only the owner's write bit for a file that was read-only before the run. +#[cfg(unix)] +#[test] +fn script_file_readonly_gives_back_the_write_bits_it_cleared() { + use std::os::unix::fs::PermissionsExt; + let base = folder("modesback"); + let mut s = with_data(&base); + let r = run_in(&mut s, &base, "var u = new File(Folder.userData.fsName + '/m.txt'); u.open('w'); u.close(); vc.log(u.fsName);").unwrap(); + let path = PathBuf::from(r["log"][0].as_str().unwrap()); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o662)).unwrap(); + let toggle = format!( + "Folder.userData; var u = new File({:?}); u.readonly = true; var a = u.readonly; var b = u.rename('n.txt');\n\ + u.readonly = false; vc.log([a, b, u.readonly]); u.rename('m.txt');", + path.to_string_lossy() + ); + let r = run_in(&mut s, &base, &toggle).unwrap(); + assert_eq!(r["log"], json!([[true, true, false]])); + assert_eq!(std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o662); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o444)).unwrap(); + let clear = format!("Folder.userData; var u = new File({:?}); u.readonly = false;", path.to_string_lossy()); + run_in(&mut s, &base, &clear).unwrap(); + assert_eq!(std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o644); + let _ = std::fs::remove_dir_all(base); +} + +/// Opening a file to append or edit reads it, so the automation read roots apply as well as the +/// write roots. +#[test] +fn script_file_append_and_edit_need_the_read_roots() { + let base = folder("appendroots"); + let mut s = with_data(&base); + std::fs::create_dir_all(base.join("main")).unwrap(); + let roots = AutomationRoots::new(&[&base.join("main")], &[&base]).unwrap(); + let r = confine(roots.as_ref(), || { + run_in( + &mut s, + &base, + "var u = new File(Folder.userData.fsName + '/w.txt'), out = [u.open('w'), u.write('kept'), u.close()];\n\ + out.push(u.open('a'), u.error, u.open('e'), u.error); vc.log(out);", + ) + }) + .unwrap(); + assert_eq!(r["log"], json!([[true, true, true, false, DENIED, false, DENIED]])); + let _ = std::fs::remove_dir_all(base); +} + +/// A script run from a folder that holds the settings folder reads its own files there, but no file +/// in the settings folder. +#[test] +fn script_files_in_a_folder_above_the_settings_folder_do_not_reach_it() { + let base = folder("above"); + let mut s = Session::new(); + s.attach_script_data(base.join("main/settings/Script Data")); + write(&base.join("main/settings/Script Grants.json"), b"{\"version\": 1, \"grants\": []}"); + write(&base.join("main/own.txt"), b"own"); + let r = run_in( + &mut s, + &base, + "var a = new File('own.txt'), g = new File('settings/Script Grants.json');\n\ + var out = [a.open('r'), a.read()]; a.close(); out.push(g.open('r'), g.error, g.exists); vc.log(out);", + ) + .unwrap(); + assert_eq!(r["log"], json!([[true, "own", false, DENIED, false]])); + let _ = std::fs::remove_dir_all(base); +} + +/// The settings folder is kept out of every grant also before it has been made. +#[test] +fn script_file_grants_never_reach_a_settings_folder_not_made_yet() { + let base = folder("unmade"); + let mut s = with_data(&base); + assert!(!base.join("settings").exists()); + start_framed(&mut s, &base, "var o = new Folder(Folder.userData.parent.parent.fsName); var f = o.selectDlg('p'); vc.log([f, o.error]);"); + assert!(pump_to_picker(&mut s).is_none()); + let settings = base.join("settings").to_string_lossy().into_owned(); + assert!(s.script_pick(crate::script::files::PickAnswer::Allow { paths: vec![settings], always: true })); + let r = pump_to_picker(&mut s).unwrap().unwrap(); + assert_eq!(r["log"], json!([[null, "Script file access to the app's own folders is not allowed"]])); + assert_eq!(s.execute("script.grants", &json!({})).unwrap()["grants"], json!([])); + let _ = std::fs::remove_dir_all(base); +} + +/// Files left open are written when the run ends in the order they were opened, so of two objects +/// that hold the same file, the one opened last decides what it holds. +#[test] +fn script_files_left_open_are_written_in_the_order_they_were_opened() { + let base = folder("flushorder"); + let mut s = with_data(&base); + let text = "var p = Folder.userData.fsName + '/two.txt'; var a = new File(p), b = new File(p);\n\ + a.open('w'); b.open('w'); a.write('first'); b.write('second'); vc.log(p);"; + for _ in 0..16 { + let r = run_in(&mut s, &base, text).unwrap(); + let path = PathBuf::from(r["log"][0].as_str().unwrap_or_default()); + assert_eq!(std::fs::read(&path).unwrap(), b"second", "{r}"); + } + let _ = std::fs::remove_dir_all(base); +} + +/// Removing a file leaves the other objects that have it open without the file: they take no more +/// writes, and closing them does not make it again. +#[test] +fn script_file_remove_detaches_the_other_open_objects() { + let base = folder("removeopen"); + let mut s = with_data(&base); + let text = "var p = Folder.userData.fsName + '/gone.txt'; var a = new File(p), b = new File(p);\n\ + a.open('w'); a.write('x'); a.close(); b.open('e');\n\ + var removed = a.remove(); var w = b.write('y'); var e = b.error; b.close();\n\ + vc.log([removed, w, e, new File(p).exists]);"; + let r = run_in(&mut s, &base, text).unwrap(); + assert_eq!(r["log"], json!([[true, false, "Script file is not open for writing", false]]), "{r}"); + let _ = std::fs::remove_dir_all(base); +} + +/// A run that ends with a changed file open that cannot be written fails and names the file. +#[test] +fn script_files_left_open_that_cannot_be_written_fail_the_run() { + let base = folder("unwritten"); + let mut s = with_data(&base); + let r = run_in( + &mut s, + &base, + "var u = new File(Folder.userData.fsName + '/ro.txt'); u.open('w'); u.write('x'); new File(u.fsName).readonly = true; vc.log(u.fsName);", + ); + let report = s.script_report().unwrap(); + let path = PathBuf::from(report["log"][0].as_str().unwrap_or_default()); + if let Ok(m) = std::fs::metadata(&path) { + let mut p = m.permissions(); + #[allow(clippy::permissions_set_readonly_false)] + p.set_readonly(false); + let _ = std::fs::set_permissions(&path, p); + } + assert!(r.is_err(), "{report}"); + let message = report["message"].as_str().unwrap(); + assert!(message.contains("the script left open files that could not be written") && message.contains("ro.txt"), "{report}"); + assert_eq!(std::fs::read(&path).unwrap(), b"", "{report}"); + let _ = std::fs::remove_dir_all(base); +} + +/// The automation write roots apply to the run's own folders too: outside them `Folder.temp` and +/// `Folder.userData` are `null` and are not made. +#[test] +fn script_files_write_only_inside_the_automation_write_roots() { + let base = folder("writeroots"); + std::fs::create_dir_all(base.join("out")).unwrap(); + let roots = AutomationRoots::new(&[&base], &[&base.join("out")]).unwrap(); + let mut s = with_data(&base); + let r = confine(roots.as_ref(), || run_in(&mut s, &base, "vc.log([Folder.temp === null, Folder.userData === null]);")).unwrap(); + assert_eq!(r["log"], json!([[true, true]])); + assert!(!base.join("settings/Script Data").exists(), "the data folder is not made"); + let _ = std::fs::remove_dir_all(base); +} + +/// The run's temporary folder is checked against the write roots by its own name: a write root named +/// `VectorCraft Script` in the temporary folder does not take the run's folder beside it. +#[test] +fn script_temporary_folder_is_checked_by_its_own_name() { + let base = folder("tempname"); + let named = std::env::temp_dir().join("VectorCraft Script"); + let made = std::fs::create_dir(&named).is_ok(); + let roots = AutomationRoots::new(&[&base], &[&named]).unwrap(); + let mut s = with_data(&base); + let r = confine(roots.as_ref(), || run_in(&mut s, &base, "vc.log(Folder.temp === null);")); + if made { + let _ = std::fs::remove_dir(&named); + } + assert_eq!(r.unwrap()["log"], json!([true])); + let _ = std::fs::remove_dir_all(base); +} + +/// The folders made above a script's data folder are inside the write roots too: with a write root +/// that names the data folder after the folders above it were removed, none of them is made again. +#[test] +fn script_data_folder_makes_no_folder_outside_the_write_roots() { + let base = folder("dataparent"); + let mut s = with_data(&base); + let r = run_in(&mut s, &base, "vc.log(Folder.userData.fsName);").unwrap(); + let data = PathBuf::from(r["log"][0].as_str().unwrap()); + let roots = AutomationRoots::new(&[&base], &[&data]).unwrap(); + std::fs::remove_dir_all(base.join("settings")).unwrap(); + let r = confine(roots.as_ref(), || run_in(&mut s, &base, "vc.log(Folder.userData === null);")).unwrap(); + assert_eq!(r["log"], json!([true])); + assert!(!base.join("settings").exists(), "no folder above the write root is made"); + let _ = std::fs::remove_dir_all(base); +} + +/// `create` makes no folder outside the places the script may write: when the folders above its data +/// folder were removed during the run, a folder in the data folder is not made, and neither are they. +#[test] +fn script_folder_create_makes_no_folder_outside_the_grants() { + let base = folder("createabove"); + let mut s = with_data(&base); + start_framed(&mut s, &base, "var d = Folder.userData.fsName; File.openDialog('p'); var f = new Folder(d + '/a'); vc.log([f.create(), f.error]);"); + assert!(pump_to_picker(&mut s).is_none()); + std::fs::remove_dir_all(base.join("settings")).unwrap(); + assert!(s.script_pick(crate::script::files::PickAnswer::Deny)); + let r = pump_to_picker(&mut s).unwrap().unwrap(); + assert_eq!(r["log"], json!([[false, DENIED]])); + assert!(!base.join("settings").exists(), "no folder above the data folder is made"); + let _ = std::fs::remove_dir_all(base); +} + +/// A file a script wrote stays written after its run fails, and the report names it. +#[test] +fn script_files_written_before_a_failure_are_named() { + let base = folder("failwrite"); + let mut s = with_data(&base); + let r = run_in(&mut s, &base, "var u = new File(Folder.userData.fsName + '/left.txt'); u.open('w'); u.write('left'); throw new Error('late');"); + assert!(r.is_err()); + let report = s.script_report().unwrap(); + let written: Vec = report["written"].as_array().unwrap().iter().filter_map(Value::as_str).map(PathBuf::from).collect(); + assert_eq!(written.len(), 1, "{report}"); + assert_eq!(std::fs::read(&written[0]).unwrap(), b"left", "the open file is written when the run ends"); + let _ = std::fs::remove_dir_all(base); +} + +/// Pumps the run in the app until it ends or waits at a file dialog (`None`). +fn pump_to_picker(s: &mut Session) -> Option> { + for _ in 0..10_000 { + if s.script_picker().is_some() { + return None; + } + if let Some(r) = s.script_pump() { + return Some(r); + } + } + panic!("the run neither ended nor waited"); +} + +/// Starts `main/main.jsx` in `base` with the text `text`, in the app. +fn start_framed(s: &mut Session, base: &Path, text: &str) { + s.script_frames = true; + let main = base.join("main/main.jsx"); + write(&main, text.as_bytes()); + assert_eq!(s.execute("script.run", &json!({"path": main.to_string_lossy()})).unwrap()["running"], true); +} + +/// The filter of an open or save dialog gives the file types the dialog shows; an open dialog with +/// `multiSelect` takes every file picked and gives them as a list. +#[test] +fn script_file_dialogs_show_the_filters_file_types_and_open_several_files() { + use crate::script::files::dialog_filters; + let f = |types: &[(&str, &[&str])]| -> Vec<(String, Vec)> { + types.iter().map(|(n, e)| (n.to_string(), e.iter().map(|e| e.to_string()).collect())).collect() + }; + assert_eq!(dialog_filters("JavaScript files:*.jsx;All files:*.*"), f(&[("JavaScript files", &["jsx"]), ("All files", &["*"])])); + assert_eq!(dialog_filters("Images:*.png,*.JPG , Text:*.txt"), f(&[("Images", &["png", "JPG"]), ("Text", &["txt"])])); + assert_eq!(dialog_filters("*.svg;*.ai"), f(&[("*.svg;*.ai", &["svg", "ai"])])); + assert_eq!(dialog_filters("All files:*.*"), f(&[]), "every file"); + assert_eq!(dialog_filters("Odd:a*b.txt;Bad:*.a/b;Text:*.txt"), f(&[("Text", &["txt"])]), "patterns that are not *.ext are left out"); + assert_eq!(dialog_filters(""), f(&[])); + + let base = folder("pickfilter"); + for name in ["a.txt", "b.txt"] { + write(&base.join("picked").join(name), b"x"); + } + let mut s = with_data(&base); + start_framed(&mut s, &base, "var f = File.openDialog('Pick', 'Text:*.txt;All files:*.*', true); vc.log([f.length, f[0].name, f[1].name]);"); + assert!(pump_to_picker(&mut s).is_none()); + let picker = s.script_picker().unwrap(); + assert!(picker.multiple); + assert_eq!(picker.filters, f(&[("Text", &["txt"]), ("All files", &["*"])])); + let paths = ["a.txt", "b.txt"].iter().map(|n| base.join("picked").join(n).to_string_lossy().into_owned()).collect(); + assert!(s.script_pick(crate::script::files::PickAnswer::Allow { paths, always: false })); + let r = pump_to_picker(&mut s).unwrap().unwrap(); + assert_eq!(r["log"], json!([[2, "a.txt", "b.txt"]])); + let _ = std::fs::remove_dir_all(base); +} + +/// A dialog's `filter` that is a function is called with each file picked, and the files it gives a +/// false value for are left out: a list keeps the rest, and one file, or a list left empty, gives +/// `null`. The dialog shows every file. A save dialog takes the same filter. +#[test] +fn script_file_dialogs_leave_out_the_files_a_filter_function_refuses() { + let base = folder("pickfilterfn"); + for name in ["a.txt", "b.svg", "c.txt"] { + write(&base.join("picked").join(name), b"x"); + } + let paths = |names: &[&str]| -> Vec { names.iter().map(|n| base.join("picked").join(n).to_string_lossy().into_owned()).collect() }; + let text = "var seen = [];\n\ + function txt(f) { seen.push(f instanceof File ? f.name : null); return f.name.slice(-4) === '.txt'; }\n\ + var many = File.openDialog('Pick', txt, true);\n\ + vc.log([many.length, many[0].name, many[1].name]);\n\ + vc.log(File.openDialog('Pick one', txt));\n\ + vc.log(File.openDialog('Pick svg', txt, true));\n\ + var saved = File.saveDialog('Save', txt);\n\ + vc.log(saved && saved.name);\n\ + vc.log(new File('x.txt').saveDlg('Save svg', txt));\n\ + vc.log(seen);"; + let mut s = with_data(&base); + start_framed(&mut s, &base, text); + for picked in [&["a.txt", "b.svg", "c.txt"][..], &["b.svg"], &["b.svg"], &["c.txt"], &["b.svg"]] { + assert!(pump_to_picker(&mut s).is_none()); + assert_eq!(s.script_picker().unwrap().filters, Vec::<(String, Vec)>::new(), "every file is shown"); + assert!(s.script_pick(crate::script::files::PickAnswer::Allow { paths: paths(picked), always: false })); + } + let r = pump_to_picker(&mut s).unwrap().unwrap(); + let seen = ["a.txt", "b.svg", "c.txt", "b.svg", "b.svg", "c.txt", "b.svg"]; + assert_eq!(r["log"], json!([[2, "a.txt", "c.txt"], null, null, "c.txt", null, seen])); + let _ = std::fs::remove_dir_all(base); +} + +/// A file a person allows always is kept for that script with that text: a later run reads it +/// without asking, and a run of changed text asks again. A file allowed once is not kept. +#[test] +fn script_file_dialog_grants_are_kept_for_the_same_script_text() { + let base = folder("grants"); + let out = base.join("picked/out.txt"); + std::fs::create_dir_all(out.parent().unwrap()).unwrap(); + let text = format!( + "var target = new File({:?});\n\ + if (target.open('r')) {{ vc.log(['kept', target.read()]); target.close(); }}\n\ + else {{ vc.log(['asked', target.error]); var f = File.saveDialog('Save it'); if (f) {{ f.open('w'); f.write('hi'); vc.log(f.close()); }} else vc.log(null); }}", + out.to_string_lossy() + ); + let mut s = with_data(&base); + start_framed(&mut s, &base, &text); + assert!(pump_to_picker(&mut s).is_none()); + let picker = s.script_picker().unwrap(); + assert_eq!((picker.kind, picker.prompt.as_str(), picker.can_always), (crate::script::files::PickerKind::Save, "Save it", true)); + assert!(s.script_pick(crate::script::files::PickAnswer::Allow { paths: vec![out.to_string_lossy().into_owned()], always: true })); + let r = pump_to_picker(&mut s).unwrap().unwrap(); + assert_eq!(r["log"], json!([["asked", DENIED], true])); + assert_eq!(std::fs::read(&out).unwrap(), b"hi"); + let grants = s.execute("script.grants", &json!({})).unwrap(); + assert_eq!(grants["grants"].as_array().unwrap().len(), 1, "{grants}"); + assert_eq!(grants["grants"][0]["write"], true); + + start_framed(&mut s, &base, &text); + let r = pump_to_picker(&mut s).unwrap().unwrap(); + assert_eq!(r["log"], json!([["kept", "hi"]]), "the same script text keeps its grant"); + + start_framed(&mut s, &base, &format!("{text}\n// changed")); + assert!(pump_to_picker(&mut s).is_none(), "changed text has no grant, so it asks"); + assert!(s.script_pick(crate::script::files::PickAnswer::Deny)); + let r = pump_to_picker(&mut s).unwrap().unwrap(); + assert_eq!(r["log"], json!([["asked", DENIED], null])); + + let once = "var g = File.openDialog('Read it'); vc.log(g.fsName === null ? null : g.open('r') && g.read());"; + start_framed(&mut s, &base, once); + assert!(pump_to_picker(&mut s).is_none()); + assert!(s.script_pick(crate::script::files::PickAnswer::Allow { paths: vec![out.to_string_lossy().into_owned()], always: false })); + let r = pump_to_picker(&mut s).unwrap().unwrap(); + assert_eq!(r["log"], json!(["hi"])); + assert_eq!(s.execute("script.grants", &json!({})).unwrap()["grants"].as_array().unwrap().len(), 1, "a file allowed once is not kept"); + + // A run that waits at a dialog keeps the grants it started with, so they are not revoked under it. + start_framed(&mut s, &base, once); + assert!(pump_to_picker(&mut s).is_none()); + let busy = s.execute("script.grants.revoke", &json!({"all": true})); + assert!(matches!(busy, Err(crate::EngineError::Busy)), "{busy:?}"); + assert_eq!(s.execute("script.grants", &json!({})).unwrap()["grants"].as_array().unwrap().len(), 1); + assert!(s.script_pick(crate::script::files::PickAnswer::Deny)); + assert!(pump_to_picker(&mut s).is_some(), "the run ends"); + + let removed = s.execute("script.grants.revoke", &json!({"path": out.to_string_lossy()})).unwrap(); + assert_eq!(removed["removed"], 1); + assert_eq!(s.execute("script.grants", &json!({})).unwrap()["grants"], json!([])); + assert!(s.execute("script.grants.revoke", &json!({})).is_err()); + assert!(!base.join("settings/Script Grants.json.part").exists()); + let _ = std::fs::remove_dir_all(base); +} + +/// A grant is kept for the script's text with the files it includes: a changed included file asks +/// again. +#[test] +fn script_file_grants_are_kept_for_the_included_files_too() { + let base = folder("grantinclude"); + let out = base.join("picked/out.txt"); + std::fs::create_dir_all(out.parent().unwrap()).unwrap(); + write(&out, b"hi"); + write(&base.join("main/lib.jsxinc"), b"var lib = 1;\n"); + let text = format!( + "#include \"lib.jsxinc\"\nvar t = new File({:?});\nif (t.open('r')) vc.log('kept'); else vc.log(File.openDialog('p') ? 'asked' : null);", + out.to_string_lossy() + ); + let mut s = with_data(&base); + start_framed(&mut s, &base, &text); + assert!(pump_to_picker(&mut s).is_none()); + assert!(s.script_pick(crate::script::files::PickAnswer::Allow { paths: vec![out.to_string_lossy().into_owned()], always: true })); + assert_eq!(pump_to_picker(&mut s).unwrap().unwrap()["log"], json!(["asked"])); + start_framed(&mut s, &base, &text); + assert_eq!(pump_to_picker(&mut s).unwrap().unwrap()["log"], json!(["kept"])); + write(&base.join("main/lib.jsxinc"), b"var lib = 2;\n"); + start_framed(&mut s, &base, &text); + assert!(pump_to_picker(&mut s).is_none(), "a changed included file has no grant, so it asks"); + assert!(s.script_pick(crate::script::files::PickAnswer::Deny)); + assert_eq!(pump_to_picker(&mut s).unwrap().unwrap()["log"], json!([null])); + let _ = std::fs::remove_dir_all(base); +} + +/// A kept grant is in force only while the run evaluates code the run that kept it evaluated: a +/// file `$.evalFile` runs, or a string given to `eval` or `Function`, that differs withdraws it +/// before that code runs. +#[test] +fn script_file_grants_are_kept_for_the_code_the_script_evaluates() { + let base = folder("granteval"); + let out = base.join("picked/out.txt"); + write(&out, b"hi"); + write(&base.join("main/lib.jsxinc"), b"var lib = 1;"); + write(&base.join("main/code.txt"), b"new File(p).open('r')"); + let text = format!( + "var p = {:?};\n$.evalFile('lib.jsxinc');\n\ + var c = new File('code.txt'); c.open('r'); var src = c.read(); c.close();\n\ + var one = Function('return 1')();\n\ + var before = new File(p).open('r');\n\ + var during = eval(src) && one === 1;\n\ + if (before) vc.log(['kept', during]); else vc.log(['asked', !!File.openDialog('p')]);", + out.to_string_lossy() + ); + let mut s = with_data(&base); + let picked = || crate::script::files::PickAnswer::Allow { paths: vec![out.to_string_lossy().into_owned()], always: true }; + start_framed(&mut s, &base, &text); + assert!(pump_to_picker(&mut s).is_none()); + assert!(s.script_pick(picked())); + assert_eq!(pump_to_picker(&mut s).unwrap().unwrap()["log"], json!([["asked", true]])); + start_framed(&mut s, &base, &text); + assert_eq!(pump_to_picker(&mut s).unwrap().unwrap()["log"], json!([["kept", true]]), "the same code keeps the grant"); + write(&base.join("main/code.txt"), b"new File(p).open('r') && true"); + start_framed(&mut s, &base, &text); + assert_eq!(pump_to_picker(&mut s).unwrap().unwrap()["log"], json!([["kept", false]]), "changed eval code runs without the grant"); + write(&base.join("main/code.txt"), b"new File(p).open('r')"); + write(&base.join("main/lib.jsxinc"), b"var lib = 2;"); + start_framed(&mut s, &base, &text); + assert!(pump_to_picker(&mut s).is_none(), "a changed $.evalFile file has no grant, so it asks"); + assert!(s.script_pick(crate::script::files::PickAnswer::Deny)); + assert_eq!(pump_to_picker(&mut s).unwrap().unwrap()["log"], json!([["asked", false]])); + write(&base.join("main/lib.jsxinc"), b"var lib = 1;"); + start_framed(&mut s, &base, &text); + assert_eq!(pump_to_picker(&mut s).unwrap().unwrap()["log"], json!([["kept", true]])); + let grants = s.execute("script.grants", &json!({})).unwrap(); + assert_eq!(grants["grants"][0]["code"].as_array().map(Vec::len), Some(3), "{grants}"); + let _ = std::fs::remove_dir_all(base); +} + +/// A file's grant covers that path only: a folder the script makes in the file's place, in the run +/// that was allowed the file and in later runs that keep its grant, is not read or written inside. +#[test] +fn script_file_grants_do_not_reach_into_a_folder_in_the_files_place() { + let base = folder("grantfileplace"); + let out = base.join("picked/out.txt"); + write(&out, b"hi"); + let text = "var p = File.saveDialog('p').fsName;\n\ + var gone = new File(p).remove(); var made = new Folder(p).create();\n\ + var w = new File(p + '/x.txt'); vc.log([gone, made, w.open('w'), w.error]);"; + let mut s = with_data(&base); + start_framed(&mut s, &base, text); + assert!(pump_to_picker(&mut s).is_none()); + assert!(s.script_pick(crate::script::files::PickAnswer::Allow { paths: vec![out.to_string_lossy().into_owned()], always: true })); + assert_eq!(pump_to_picker(&mut s).unwrap().unwrap()["log"], json!([[true, true, false, DENIED]])); + assert!(out.is_dir() && !out.join("x.txt").exists()); + let grants = s.execute("script.grants", &json!({})).unwrap(); + assert_eq!(grants["grants"][0]["folder"], false, "{grants}"); + + let later = format!("var w = new File({:?}); vc.log([w.open('w'), w.error]);", out.join("y.txt").to_string_lossy()); + let main = base.join("main/main.jsx"); + write(&main, later.as_bytes()); + let real = std::fs::canonicalize(&main).unwrap(); + let hash = vectorcraft_plugins::permissions::sha256_hex(later.as_bytes()); + let out_real = crate::cmd::findfiles::plain(std::fs::canonicalize(&out).unwrap()); + let kept = json!({"version": 1, "grants": [{"script": crate::cmd::findfiles::plain(real).to_string_lossy(), "sha256": hash, "code": [], "path": out_real.to_string_lossy(), "write": true, "folder": false}]}); + write(&base.join("settings/Script Grants.json"), kept.to_string().as_bytes()); + start_framed(&mut s, &base, &later); + assert_eq!(pump_to_picker(&mut s).unwrap().unwrap()["log"], json!([[false, DENIED]]), "a kept file grant does not reach inside either"); + assert!(!out.join("y.txt").exists()); + let _ = std::fs::remove_dir_all(base); +} + +/// The code a run evaluates after a person allowed it a file always is kept with the grant when +/// the run ends, so the next run of the same script that evaluates it keeps the grant. +#[test] +fn script_file_grants_keep_the_code_evaluated_after_the_dialog() { + let base = folder("grantlater"); + let out = base.join("picked/out.txt"); + write(&out, b"hi"); + let text = format!( + "var t = new File({:?}); var kept = t.open('r');\n\ + if (!kept) File.openDialog('p');\n\ + vc.log([kept, eval('new File(t.fsName).open(\"r\")')]);", + out.to_string_lossy() + ); + let mut s = with_data(&base); + start_framed(&mut s, &base, &text); + assert!(pump_to_picker(&mut s).is_none()); + assert!(s.script_pick(crate::script::files::PickAnswer::Allow { paths: vec![out.to_string_lossy().into_owned()], always: true })); + assert_eq!(pump_to_picker(&mut s).unwrap().unwrap()["log"], json!([[false, true]])); + start_framed(&mut s, &base, &text); + assert_eq!(pump_to_picker(&mut s).unwrap().unwrap()["log"], json!([[true, true]])); + let _ = std::fs::remove_dir_all(base); +} + +/// Code another script left in a named engine withdraws a script's kept grants in that engine. +#[test] +fn script_file_grants_are_withdrawn_by_code_another_script_left_in_the_engine() { + let base = folder("grantengine"); + let out = base.join("picked/out.txt"); + write(&out, b"hi"); + let text = format!( + "#targetengine shared\nvar t = new File({:?});\nif (t.open('r')) vc.log('kept'); else vc.log(File.openDialog('p') ? 'asked' : null);", + out.to_string_lossy() + ); + let mut s = with_data(&base); + start_framed(&mut s, &base, &text); + assert!(pump_to_picker(&mut s).is_none()); + assert!(s.script_pick(crate::script::files::PickAnswer::Allow { paths: vec![out.to_string_lossy().into_owned()], always: true })); + assert_eq!(pump_to_picker(&mut s).unwrap().unwrap()["log"], json!(["asked"])); + start_framed(&mut s, &base, &text); + assert_eq!(pump_to_picker(&mut s).unwrap().unwrap()["log"], json!(["kept"]), "the engine holds only this script's code"); + let other = base.join("main/other.jsx"); + write(&other, b"#targetengine shared\nvar otherWasHere = 1;"); + s.script_frames = false; + s.execute("script.run", &json!({"path": other.to_string_lossy()})).unwrap(); + start_framed(&mut s, &base, &text); + assert!(pump_to_picker(&mut s).is_none(), "another script's code is in the engine, so it asks"); + assert!(s.script_pick(crate::script::files::PickAnswer::Deny)); + assert_eq!(pump_to_picker(&mut s).unwrap().unwrap()["log"], json!([null])); + let _ = std::fs::remove_dir_all(base); +} + +/// Code a script given as text left in a named engine withdraws a script's kept grants in that +/// engine, as a file script's code does. +#[test] +fn script_file_grants_are_withdrawn_by_code_a_text_script_left_in_the_engine() { + let base = folder("grantenginetext"); + let out = base.join("picked/out.txt"); + write(&out, b"hi"); + let text = format!( + "#targetengine shared\nvar t = new File({:?});\nif (t.open('r')) vc.log('kept'); else vc.log(File.openDialog('p') ? 'asked' : null);", + out.to_string_lossy() + ); + let mut s = with_data(&base); + start_framed(&mut s, &base, &text); + assert!(pump_to_picker(&mut s).is_none()); + assert!(s.script_pick(crate::script::files::PickAnswer::Allow { paths: vec![out.to_string_lossy().into_owned()], always: true })); + assert_eq!(pump_to_picker(&mut s).unwrap().unwrap()["log"], json!(["asked"])); + s.script_frames = false; + s.execute("script.run", &json!({"source": "#targetengine shared\nvar textWasHere = 1;"})).unwrap(); + start_framed(&mut s, &base, &text); + assert!(pump_to_picker(&mut s).is_none(), "a text script's code is in the engine, so it asks"); + assert!(s.script_pick(crate::script::files::PickAnswer::Deny)); + assert_eq!(pump_to_picker(&mut s).unwrap().unwrap()["log"], json!([null])); + let _ = std::fs::remove_dir_all(base); +} + +/// A file opened for writing under a kept grant that new code withdraws takes no more writes, and +/// changes that cannot be written then fail the run when it ends. +#[test] +fn script_files_open_under_a_withdrawn_grant_keep_their_unwritten_changes() { + let base = folder("grantwithdrawn"); + let dir = base.join("picked"); + std::fs::create_dir_all(&dir).unwrap(); + let out = dir.join("out.txt"); + let text = format!( + "var f = new File({:?});\n\ + if (!f.open('w')) vc.log(['asked', !!Folder.selectDialog('p')]);\n\ + else {{ f.write('a'); new File(f.fsName).readonly = true; eval('1'); vc.log(['wrote', f.write('b'), f.error]); }}", + out.to_string_lossy() + ); + let mut s = with_data(&base); + start_framed(&mut s, &base, &text); + assert!(pump_to_picker(&mut s).is_none()); + assert!(s.script_pick(crate::script::files::PickAnswer::Allow { paths: vec![dir.to_string_lossy().into_owned()], always: true })); + assert_eq!(pump_to_picker(&mut s).unwrap().unwrap()["log"], json!([["asked", true]])); + start_framed(&mut s, &base, &text); + let r = pump_to_picker(&mut s).unwrap(); + let report = s.script_report().unwrap(); + if let Ok(m) = std::fs::metadata(&out) { + let mut p = m.permissions(); + #[allow(clippy::permissions_set_readonly_false)] + p.set_readonly(false); + let _ = std::fs::set_permissions(&out, p); + } + assert!(r.is_err(), "{report}"); + assert_eq!(report["log"], json!([["wrote", false, "Script file is not open for writing"]]), "{report}"); + let message = report["message"].as_str().unwrap(); + assert!(message.contains("the script left open files that could not be written") && message.contains("out.txt"), "{report}"); + let _ = std::fs::remove_dir_all(base); +} + +/// The folder that holds the settings is kept out of every grant: a pick there gives `null` with the +/// error, a grant written into the grants file for it is not taken, and the script cannot write the +/// grants file through its data folder. +#[test] +fn script_file_grants_never_reach_the_settings_folder() { + let base = folder("protected"); + let mut s = with_data(&base); + std::fs::create_dir_all(base.join("settings/Scripts")).unwrap(); + let inside = base.join("settings/Scripts/x.txt"); + write(&inside, b"secret"); + let text = format!( + "var o = new File('x.txt'); var f = o.saveDlg('p'); vc.log([f, o.error]);\n\ + var g = new File(Folder.userData.parent.parent.fsName + '/Script Grants.json'); vc.log([g.open('w'), g.error]);\n\ + var h = new File({:?}); vc.log([h.open('r'), h.error]);", + inside.to_string_lossy() + ); + let main = base.join("main/main.jsx"); + write(&main, text.as_bytes()); + let real = std::fs::canonicalize(&main).unwrap(); + let hash = vectorcraft_plugins::permissions::sha256_hex(text.as_bytes()); + let settings = crate::cmd::findfiles::plain(std::fs::canonicalize(base.join("settings")).unwrap()); + let forged = json!({"version": 1, "grants": [{"script": crate::cmd::findfiles::plain(real).to_string_lossy(), "sha256": hash, "code": [], "path": settings.to_string_lossy(), "write": true, "folder": true}]}); + write(&base.join("settings/Script Grants.json"), forged.to_string().as_bytes()); + start_framed(&mut s, &base, &text); + assert!(pump_to_picker(&mut s).is_none()); + assert!(s.script_pick(crate::script::files::PickAnswer::Allow { paths: vec![inside.to_string_lossy().into_owned()], always: true })); + let r = pump_to_picker(&mut s).unwrap().unwrap(); + let protected = "Script file access to the app's own folders is not allowed"; + assert_eq!(r["log"], json!([[null, protected], [false, DENIED], [false, DENIED]])); + assert_eq!(std::fs::read(&inside).unwrap(), b"secret"); + let _ = std::fs::remove_dir_all(base); +} + +/// A file dialog inside a built-in's callback throws in the app, where it cannot wait. +#[test] +fn script_file_dialog_in_a_callback_throws() { + let base = folder("callback"); + let mut s = Session::new(); + start_framed(&mut s, &base, "[1].forEach(function () { File.openDialog(); });"); + let r = pump_to_picker(&mut s).unwrap(); + assert!(r.is_err()); + let report = s.script_report().unwrap(); + assert!(report["message"].as_str().unwrap().contains("File.openDialog: a file dialog cannot open inside a callback"), "{report}"); let _ = std::fs::remove_dir_all(base); } diff --git a/crates/engine/src/tests/script_run.rs b/crates/engine/src/tests/script_run.rs index d272fea167..0a4037a0d8 100644 --- a/crates/engine/src/tests/script_run.rs +++ b/crates/engine/src/tests/script_run.rs @@ -245,10 +245,46 @@ fn files_are_checked_before_they_are_read() { let _ = std::fs::remove_dir_all(&dir); } +/// A new empty folder for test `name`. +fn fresh_folder(name: &str) -> std::path::PathBuf { + let dir = std::env::temp_dir().join(format!("vc-script-run-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir +} + +/// Starts `source` in the app after a folder dialog it opens first, and allows the script the folder +/// `dir` there once. +fn start_allowed(s: &mut Session, dir: &std::path::Path, source: &str) { + s.script_frames = true; + assert_eq!(run(s, &format!("Folder.selectDialog('Folder');\n{source}")).unwrap()["running"], true); + for _ in 0..10_000 { + if s.script_picker().is_some() { + let paths = vec![dir.to_string_lossy().into_owned()]; + assert!(s.script_pick(crate::script::files::PickAnswer::Allow { paths, always: false })); + return; + } + assert!(s.script_pump().is_none(), "the run waits at its folder dialog"); + } + panic!("the run did not open its folder dialog"); +} + +/// Runs `source` in the app as [`start_allowed`] starts it, to its end. +fn run_allowed(s: &mut Session, dir: &std::path::Path, source: &str) -> Result { + start_allowed(s, dir, source); + let r = loop { + if let Some(r) = s.script_pump() { + break r; + } + }; + s.script_frames = false; + r +} + #[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 dir = fresh_folder("batch"); + let path = dir.join("out.svg"); let p = path.to_string_lossy().into_owned(); let mut s = two_docs(); let source = format!( @@ -257,24 +293,90 @@ fn a_failed_batch_puts_back_the_session_and_names_a_file_it_wrote() { {{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(); + let r = run_allowed(&mut s, &dir, &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); + let _ = std::fs::remove_dir_all(&dir); } #[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 dir = fresh_folder("no-folder"); + let path = dir.join("missing").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(); + let r = run_allowed(&mut s, &dir, &source).unwrap(); assert_eq!(r["log"], json!(["Error"]), "{r}"); assert!(!path.exists()); assert_eq!(r["written"], json!([]), "{r}"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// The commands a script runs read and write only where its `File` and `Folder` objects may (its +/// temporary folder and what a person allowed it, here), and the files of the open documents. +#[test] +fn a_scripts_commands_reach_only_its_own_places_and_the_open_documents() { + let dir = fresh_folder("gate"); + let (inside, outside) = (dir.join("in"), dir.join("out")); + std::fs::create_dir_all(&inside).unwrap(); + std::fs::create_dir_all(&outside).unwrap(); + let call = |id: &str, path: &std::path::Path| { + let p = path.to_string_lossy().into_owned(); + let format = if id == "document.export" { ", format: 'svg'" } else { "" }; + format!( + "try {{ vc.run('{id}', {{path: {p:?}{format}}}); vc.log('ok'); }} catch (e) {{ vc.log(String(e.message).indexOf('Script file access denied') >= 0 ? 'denied' : e.message); }}\n" + ) + }; + let mut s = two_docs(); + let r = run(&mut s, &call("document.export", &outside.join("a.svg"))).unwrap(); + assert_eq!(r["log"], json!(["denied"]), "a script given as text writes nowhere: {r}"); + assert!(!outside.join("a.svg").exists()); + let source = format!("{}{}", call("document.export", &inside.join("b.svg")), call("document.export", &outside.join("c.svg"))); + let r = run_allowed(&mut s, &inside, &source).unwrap(); + assert_eq!(r["log"], json!(["ok", "denied"]), "{r}"); + assert!(inside.join("b.svg").exists() && !outside.join("c.svg").exists()); + let r = run(&mut s, "var t = Folder.temp.fsName + '/t.svg'; vc.run('document.export', {path: t, format: 'svg'}); vc.log(new File(t).exists);") + .unwrap(); + assert_eq!(r["log"], json!([true]), "the run's temporary folder: {r}"); + let own = outside.join("own.svg"); + s.execute("document.save", &json!({"path": own.to_string_lossy()})).unwrap(); + std::fs::copy(&own, outside.join("copy.svg")).unwrap(); + let source = format!( + "vc.run('shape.rectangle', {{x: 1, y: 1, width: 1, height: 1}});\n{}{}{}{}", + call("document.save", &own), + call("document.open", &own), + call("document.open", &outside.join("copy.svg")), + call("document.save", &outside.join("other.svg")) + ); + let r = run(&mut s, &source).unwrap(); + assert_eq!(r["log"], json!(["ok", "ok", "denied", "denied"]), "an open document's own file, and no other: {r}"); + assert!(!outside.join("other.svg").exists()); + std::fs::remove_file(&own).unwrap(); + let r = run(&mut s, &call("document.save", &own)).unwrap(); + assert_eq!(r["log"], json!(["ok"]), "a document's own file that was removed is made again: {r}"); + assert!(own.exists()); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A command a script runs does not save into the app's own libraries; the same command run +/// outside a script does. +#[test] +fn a_scripts_commands_do_not_save_into_the_apps_libraries() { + let dir = fresh_folder("gate-library"); + let user = dir.join("user"); + let mut s = two_docs(); + s.swatch_libraries.set_user_dir(Some(user.to_string_lossy().into_owned())); + let source = "try { vc.run('swatch.library.save', {user: true, name: 'Mine'}); vc.log('ok'); } \ + catch (e) { vc.log(String(e.message).indexOf('Script file access denied') >= 0 ? 'denied' : e.message); }"; + let r = run(&mut s, source).unwrap(); + assert_eq!(r["log"], json!(["denied"]), "{r}"); + assert!(std::fs::read_dir(&user).map_or(true, |mut d| d.next().is_none()), "nothing is written in the user library folder"); + s.execute("swatch.library.save", &json!({"user": true, "name": "Mine"})).unwrap(); + assert_eq!(std::fs::read_dir(&user).unwrap().count(), 1); + let _ = std::fs::remove_dir_all(&dir); } #[test] @@ -341,17 +443,18 @@ fn a_command_whose_result_cannot_cross_is_put_back() { #[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 dir = fresh_folder("abandon"); + let path = dir.join("out.svg"); 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"); + start_allowed(&mut s, &dir, &format!("vc.run('document.export', {{path: {p:?}, format: 'svg'}}); while (true) {{}}")); + assert!(s.script_pump().is_none()); + assert!(path.exists(), "the slice after the dialog 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); + let _ = std::fs::remove_dir_all(&dir); } #[test] @@ -881,19 +984,19 @@ fn a_run_waiting_to_grow_stops_at_the_next_slice_once_its_work_is_canceled() { #[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 dir = fresh_folder("save"); + let path = dir.join("out.svg"); 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(); + let e = run_allowed(&mut s, &dir, &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); + let _ = std::fs::remove_dir_all(&dir); } /// A run in the app's frames keeps the file-access scope its `script.run` came in, whatever scope @@ -918,16 +1021,13 @@ fn a_framed_run_keeps_the_file_access_scope_it_started_in() { } }; let mut s = two_docs(); - s.script_frames = true; let confined_target = outside.join("confined.svg"); - let started = crate::file_access::confine(Some(&roots), || run(&mut s, &export(&confined_target))).unwrap(); - assert_eq!(started["running"], true); + crate::file_access::confine(Some(&roots), || start_allowed(&mut s, &dir, &export(&confined_target))); let r = crate::file_access::unconfined(|| finish(&mut s)).unwrap(); assert_eq!(r["log"], json!(["Error"]), "a confined caller's run stays confined: {r}"); assert!(!confined_target.exists()); let user_target = outside.join("user.svg"); - let started = crate::file_access::unconfined(|| run(&mut s, &export(&user_target))).unwrap(); - assert_eq!(started["running"], true); + crate::file_access::unconfined(|| start_allowed(&mut s, &dir, &export(&user_target))); let r = crate::file_access::confine(Some(&roots), || finish(&mut s)).unwrap(); assert_eq!(r["log"], json!(["ok"]), "a run the person started is not confined by a later caller: {r}"); assert!(user_target.exists()); diff --git a/crates/js/src/builtins.rs b/crates/js/src/builtins.rs index 301b1235a4..92db4e6502 100644 --- a/crates/js/src/builtins.rs +++ b/crates/js/src/builtins.rs @@ -478,6 +478,7 @@ fn function_ctor(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsRe units.extend(MID.encode_utf16()); units.extend_from_slice(&body.flat()); units.extend(TAIL.encode_utf16()); + interp.observe_code(&units); interp.source_units = interp.source_units.saturating_add(units.len()); let remaining = interp.options.max_source_units.saturating_sub(interp.source_units.saturating_sub(units.len())); let options = crate::Options { strict: false, max_source_units: remaining, ..interp.options.clone() }; @@ -557,6 +558,7 @@ fn eval(interp: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult JsResult> { Ok((this_run && matches!(h, Value::Number(n) if n >= 0.0)).then_some(h)) } -/// Closes the object's open file, if it has one. -fn close_open(i: &mut Interp, o: ObjId) -> JsResult<()> { +/// Closes the object's open file, if it has one, which writes what the script wrote to it. → false +/// after setting `error` when that could not be written. +fn close_open(i: &mut Interp, o: ObjId) -> JsResult { + let mut written = true; if let Some(h) = is_open(i, o)? { - host(i, "close", &[h])?; + let r = host(i, "close", &[h])?; + written = outcome(i, o, &r)?; } - set_slot(i, o, HANDLE, Value::Number(-1.0)) + set_slot(i, o, HANDLE, Value::Number(-1.0))?; + Ok(written) } fn date(i: &mut Interp, ms: Value) -> JsResult { @@ -375,7 +385,10 @@ fn get_relative_uri(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsR fn change_path(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { let (o, _) = this_path(i, &this, "changePath")?; - close_open(i, o)?; + // An object whose changes could not be written keeps its path; `error` says why. + if !close_open(i, o)? { + return Ok(Value::Bool(false)); + } let p = parse(i, &arg(args, 0))?; let fs = i.rooted(std::slice::from_ref(&p), |i| field(i, &p, "fs"))?; set_slot(i, o, PATH, fs)?; @@ -409,30 +422,282 @@ fn to_string(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult JsResult { - let (o, _) = this_path(i, &this, "write")?; - let m = message(i, "noWrites")?; +/// Whether the host's answer `r` is not `{error}`; when it is, the object's `error` is set to it. +fn outcome(i: &mut Interp, o: ObjId, r: &Value) -> JsResult { + let error = i.rooted(std::slice::from_ref(r), |i| field(i, r, "error"))?; + if matches!(error, Value::String(_)) { + set_slot(i, o, ERROR, error)?; + return Ok(false); + } + Ok(true) +} + +/// Calls the host function `name` with the object's path and `args`. → whether it did the work. +fn path_call(i: &mut Interp, this: &Value, what: &str, name: &str, args: &[Value]) -> JsResult { + let (o, path) = this_path(i, this, what)?; + let mut all = vec![path]; + all.extend_from_slice(args); + let r = i.rooted(&all, |i| host(i, name, &all))?; + Ok(Value::Bool(outcome(i, o, &r)?)) +} + +/// `createAlias`: not available, so it sets `error` and returns `false`. +fn create_alias(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let (o, _) = this_path(i, &this, "createAlias")?; + let m = message(i, "noAlias")?; set_slot(i, o, ERROR, m)?; Ok(Value::Bool(false)) } -/// A setter that writes: it sets `error` and changes nothing. -fn no_writes_setter(i: &mut Interp, this: Value, args: &[Value], construct: bool) -> JsResult { - no_writes(i, this, args, construct)?; +/// Setting `hidden`: not available, so it sets `error` and changes nothing. +fn set_hidden(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let (o, _) = this_path(i, &this, "hidden")?; + let m = message(i, "noHidden")?; + set_slot(i, o, ERROR, m)?; Ok(Value::Undefined) } -/// A dialog method: it sets `error` and returns `null`. -fn no_picker(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { - let (o, _) = this_path(i, &this, "dialog")?; - let m = message(i, "noPicker")?; - set_slot(i, o, ERROR, m)?; - Ok(Value::Null) +/// `remove()`: the file, or the folder when it is empty, deleted at once. +fn remove(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + let (o, _) = this_path(i, &this, "remove")?; + // A file whose changes could not be written is not removed; `error` says why. + if !close_open(i, o)? { + return Ok(Value::Bool(false)); + } + path_call(i, &this, "remove", "remove", &[]) } -fn null_static(_: &mut Interp, _: Value, _: &[Value], _: bool) -> JsResult { - Ok(Value::Null) +/// `rename(name)`: the object's file or folder named `name`, in the same folder; the object takes +/// the new path. +fn rename(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + let (o, path) = this_path(i, &this, "rename")?; + let name = Value::String(i.to_str(&arg(args, 0))?); + if !close_open(i, o)? { + return Ok(Value::Bool(false)); + } + let r = i.rooted(&[path.clone(), name.clone()], |i| host(i, "rename", &[path.clone(), name.clone()]))?; + if !outcome(i, o, &r)? { + return Ok(Value::Bool(false)); + } + let fs = i.rooted(std::slice::from_ref(&r), |i| field(i, &r, "fs"))?; + set_slot(i, o, PATH, fs)?; + Ok(Value::Bool(true)) +} + +/// `copy(target)`: the file copied to `target`, a path or a `File`, replacing a file there. +fn copy(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + this_path(i, &this, "copy")?; + let p = parse(i, &arg(args, 0))?; + let fs = i.rooted(std::slice::from_ref(&p), |i| field(i, &p, "fs"))?; + i.rooted(std::slice::from_ref(&fs), |i| path_call(i, &this, "copy", "copy", std::slice::from_ref(&fs))) +} + +/// `Folder.prototype.create()`: the folder, with the folders above it that are missing. +fn create(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { + path_call(i, &this, "create", "create", &[]) +} + +/// Setting `length`: the file cut, or filled with zero bytes, to that many bytes. +fn set_length(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + this_path(i, &this, "length")?; + let n = i.to_number(&arg(args, 0))?; + if !n.is_finite() || n < 0.0 { + return Err(i.throw(ErrorType::Range, "File.length: the length must be a finite number, 0 or more")); + } + path_call(i, &this, "length", "setLength", &[Value::Number(n.floor())])?; + Ok(Value::Undefined) +} + +/// Setting `readonly`. +fn set_readonly(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + this_path(i, &this, "readonly")?; + let on = arg(args, 0).truthy(); + path_call(i, &this, "readonly", "setReadonly", &[Value::Bool(on)])?; + Ok(Value::Undefined) +} + +/// The line end the object's `lineFeed` names: CRLF for `Windows`, CR for `Macintosh` and LF for +/// anything else, without regard to case. +fn line_end(i: &Interp, o: ObjId) -> JsResult<&'static str> { + Ok(match slot(i, o, LINE_FEED)? { + Value::String(s) => match s.to_rust_string().to_ascii_lowercase().as_str() { + "windows" => "\r\n", + "macintosh" => "\r", + _ => "\n", + }, + _ => "\n", + }) +} + +/// `write(...values)` and, with `line`, `writeln(...values)`: the values as `String(value)` gives +/// them, written at the position of the object's open file. The values are joined only for an open +/// file, and only while the text stays within twice the host's `maxWrite` UTF-16 code units: each +/// character takes at least one byte and at most two code units, so a longer text cannot fit in a +/// file, and the write sets `error` to the host's `tooLarge` and returns `false`. +fn write_values(i: &mut Interp, this: &Value, args: &[Value], what: &str, line: bool) -> JsResult { + let (o, _) = this_path(i, this, what)?; + let Some(h) = opened(i, o)? else { return Ok(Value::Bool(false)) }; + let c = classes(i)?; + let max = match i.get_value(&Value::Object(c.host), &key("maxWrite"))? { + Value::Number(n) if n.is_finite() && n >= 0.0 => (n as usize).saturating_mul(2), + _ => usize::MAX, + }; + let mut text = String::new(); + let mut units = 0usize; + for a in args { + i.use_fuel()?; + let s = i.to_str(a)?; + units = units.saturating_add(s.len()); + if units > max { + let m = message(i, "tooLarge")?; + set_slot(i, o, ERROR, m)?; + return Ok(Value::Bool(false)); + } + text.push_str(&s.to_rust_string()); + } + if line { + text.push_str(line_end(i, o)?); + } + i.reserve_heap(string_bytes(text.len()))?; + let text = Value::str(&text); + let r = i.rooted(&[h.clone(), text.clone()], |i| host(i, "write", &[h.clone(), text.clone()]))?; + Ok(Value::Bool(outcome(i, o, &r)?)) +} + +fn write(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + write_values(i, &this, args, "write", false) +} + +fn writeln(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { + write_values(i, &this, args, "writeln", true) +} + +// ---- file dialogs ---- + +/// The file dialogs, made from script code so the run can wait at the host's `pick` until the +/// person answers: `ask` gives `pick`'s arguments and `wrap` turns its answer into objects. A +/// `filter` that is a function is called with each file picked, and the files it gives a false +/// value for are left out; when none is left, the dialog gives `null`. +const DIALOGS: &str = "(function (ask, pick, wrap) { + var isArray = Array.isArray; + function kept(files, filter) { + if (files === null || typeof filter !== 'function') return files; + if (!isArray(files)) return filter(files) ? files : null; + var out = []; + for (var k = 0; k < files.length; k++) if (filter(files[k])) out[out.length] = files[k]; + return out.length ? out : null; + } + function dialog(kind, self, prompt, multi, filter) { var a = ask(kind, self, prompt, multi, filter); return kept(wrap(kind, self, pick(a[0], a[1], a[2], a[3], a[4])), filter); } + return [ + function openDialog(prompt, filter, multiSelect) { return dialog('open', null, prompt, multiSelect, filter); }, + function saveDialog(prompt, filter) { return dialog('save', null, prompt, false, filter); }, + function openDlg(prompt, filter, multiSelect) { return dialog('open', this, prompt, multiSelect, filter); }, + function saveDlg(prompt, filter) { return dialog('save', this, prompt, false, filter); }, + function selectDialog(prompt) { return dialog('folder', null, prompt, false, null); }, + function selectDlg(prompt) { return dialog('folder', this, prompt, false, null); } + ]; +})"; + +/// `ask(kind, self, prompt, multi, filter)`: `[kind, prompt, multi, start, filter]`, the arguments +/// of the host's `pick`, where `start` is the path of `self` (a `File` or `Folder`, or `null` for the +/// class's own dialog) and `filter` the file types, a string, or `""` for any other value. `self` +/// must be a `File` or `Folder` when it is not `null`. +fn ask(i: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + let kind = arg(args, 0); + let start = match arg(args, 1) { + Value::Null => Value::str(""), + s => this_path(i, &s, "dialog")?.1, + }; + let prompt = match arg(args, 2) { + Value::Undefined | Value::Null => Value::str(""), + p => Value::String(i.to_str(&p)?), + }; + let multi = Value::Bool(arg(args, 3).truthy()); + let filter = match arg(args, 4) { + f @ Value::String(_) => f, + _ => Value::str(""), + }; + i.rooted(&[kind.clone(), start.clone(), prompt.clone(), filter.clone()], |i| { + i.reserve_heap(OBJECT_BYTES + 5 * PROP_BYTES)?; + let proto = i.intrinsics.array_proto; + let out = i.heap.alloc_object(Object::new(Class::Array { length: 0, length_writable: true }, Some(proto))); + i.rooted(&[Value::Object(out)], |i| { + for (at, v) in [kind.clone(), prompt.clone(), multi.clone(), start.clone(), filter.clone()].into_iter().enumerate() { + put_at(i, out, at as f64, v)?; + } + Ok(Value::Object(out)) + }) + }) +} + +/// `wrap(kind, self, answer)`: the `File` (a `Folder` for a folder dialog) for each path `pick` +/// gave, an array of them for a list, `null` for `null`, and `null` after setting `self`'s `error` +/// for `{error}`. +fn wrap(i: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { + let c = classes(i)?; + let proto = if matches!(arg(args, 0), Value::String(s) if s.to_rust_string() == "folder") { c.folder_proto } else { c.file_proto }; + let answer = arg(args, 2); + match &answer { + Value::String(_) => return instance(i, proto, answer.clone()), + Value::Object(_) => {} + _ => return Ok(Value::Null), + } + let error = i.rooted(std::slice::from_ref(&answer), |i| field(i, &answer, "error"))?; + if matches!(error, Value::String(_)) { + if let Some(o) = arg(args, 1).as_object() + && matches!(slot(i, o, PATH)?, Value::String(_)) + { + set_slot(i, o, ERROR, error)?; + } + return Ok(Value::Null); + } + i.rooted(std::slice::from_ref(&answer), |i| { + let length = i.get_value(&answer, &key("length"))?; + let n = i.to_number(&length)?; + i.reserve_heap(OBJECT_BYTES)?; + let array_proto = i.intrinsics.array_proto; + let out = i.heap.alloc_object(Object::new(Class::Array { length: 0, length_writable: true }, Some(array_proto))); + i.rooted(&[Value::Object(out)], |i| { + let mut at = 0.0; + while at < n { + i.use_fuel()?; + let fs = i.get_value(&answer, &crate::value::number_to_str(at).flat())?; + let item = i.rooted(std::slice::from_ref(&fs), |i| instance(i, proto, fs.clone()))?; + put_at(i, out, at, item)?; + at += 1.0; + } + Ok(Value::Object(out)) + }) + }) +} + +/// Defines the file dialogs on `File`, `Folder` and their prototypes. +fn dialogs(i: &mut Interp, file: ObjId, file_proto: ObjId, folder: ObjId, folder_proto: ObjId) -> JsResult<()> { + let units = i.encode_source(DIALOGS).map_err(|e| i.compile_error_to_abrupt(e))?; + let code = i.compile_source(&units, false, CodeKind::Eval).map_err(|e| i.compile_error_to_abrupt(e))?; + let make = i.run_global(code, true)?; + let c = classes(i)?; + let pick = i.rooted(std::slice::from_ref(&make), |i| i.get_value(&Value::Object(c.host), &key("pick")))?; + let ask = native(i, "ask", ask, 5, NativeKind::Plain, false)?; + let made = i.rooted(&[make.clone(), pick.clone(), Value::Object(ask)], |i| { + let wrap = native(i, "wrap", wrap, 3, NativeKind::Plain, false)?; + i.call(&make, &Value::Undefined, &[Value::Object(ask), pick.clone(), Value::Object(wrap)]) + })?; + let on = [ + (file, "openDialog"), + (file, "saveDialog"), + (file_proto, "openDlg"), + (file_proto, "saveDlg"), + (folder, "selectDialog"), + (folder_proto, "selectDlg"), + ]; + i.rooted(std::slice::from_ref(&made), |i| { + for (at, (target, name)) in on.into_iter().enumerate() { + let f = i.get_value(&made, &crate::value::number_to_str(at as f64).flat())?; + data(i, target, name, f, HIDDEN)?; + } + Ok(()) + }) } fn text_static(i: &mut Interp, name: &str, args: &[Value]) -> JsResult { @@ -530,19 +795,18 @@ fn open(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult Value::Undefined => "r".to_string(), m => i.to_str(&m)?.to_rust_string().to_lowercase(), }; - let refusal = match mode.as_str() { - "r" => None, - "w" | "e" | "a" => Some("noWrites"), - _ => Some("badMode"), - }; - if let Some(name) = refusal { - let m = message(i, name)?; + if !matches!(mode.as_str(), "r" | "w" | "e" | "a") { + let m = message(i, "badMode")?; set_slot(i, o, ERROR, m)?; return Ok(Value::Bool(false)); } - close_open(i, o)?; + // The object's earlier changes are written first; when they cannot be, it does not open again. + if !close_open(i, o)? { + return Ok(Value::Bool(false)); + } let encoding = slot(i, o, ENCODING)?; - let r = host(i, "open", &[path, encoding])?; + let mode = Value::str(&mode); + let r = host(i, "open", &[path, encoding, mode])?; let (error, id) = i.rooted(std::slice::from_ref(&r), |i| Ok((field(i, &r, "error")?, field(i, &r, "id")?)))?; if matches!(error, Value::String(_)) { set_slot(i, o, ERROR, error)?; @@ -559,8 +823,7 @@ fn close(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { if opened(i, o)?.is_none() { return Ok(Value::Bool(false)); } - close_open(i, o)?; - Ok(Value::Bool(true)) + Ok(Value::Bool(close_open(i, o)?)) } fn read(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult { @@ -669,7 +932,7 @@ fn set_current(i: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult`: a new `Folder` for the host's location `place`, or `null`. fn place(i: &mut Interp, place: &str) -> JsResult { - let all = host(i, "locations", &[])?; + let all = host(i, "locations", &[Value::str(place)])?; let fs = i.rooted(std::slice::from_ref(&all), |i| field(i, &all, place))?; if !matches!(fs, Value::String(_)) { return Ok(Value::Null); @@ -735,8 +998,8 @@ fn common(i: &mut Interp, ctor: ObjId, proto: ObjId) -> JsResult<()> { method(i, proto, "changePath", change_path, 1)?; method(i, proto, "resolve", resolve, 0)?; method(i, proto, "execute", execute, 0)?; - method(i, proto, "remove", no_writes, 0)?; - method(i, proto, "rename", no_writes, 1)?; + method(i, proto, "remove", remove, 0)?; + method(i, proto, "rename", rename, 1)?; method(i, ctor, "encode", encode, 1)?; method(i, ctor, "decode", decode, 1)?; method(i, ctor, "isEncodingAvailable", encoding_available, 1)?; @@ -744,10 +1007,10 @@ fn common(i: &mut Interp, ctor: ObjId, proto: ObjId) -> JsResult<()> { data(i, ctor, "fs", system, HIDDEN) } -fn file_members(i: &mut Interp, ctor: ObjId, proto: ObjId) -> JsResult<()> { - accessor(i, proto, "length", length, Some(no_writes_setter))?; - accessor(i, proto, "hidden", hidden, Some(no_writes_setter))?; - accessor(i, proto, "readonly", readonly, Some(no_writes_setter))?; +fn file_members(i: &mut Interp, proto: ObjId) -> JsResult<()> { + accessor(i, proto, "length", length, Some(set_length))?; + accessor(i, proto, "hidden", hidden, Some(set_hidden))?; + accessor(i, proto, "readonly", readonly, Some(set_readonly))?; accessor(i, proto, "creator", four_question_marks, None)?; accessor(i, proto, "type", four_question_marks, None)?; accessor(i, proto, "eof", eof, None)?; @@ -760,21 +1023,15 @@ fn file_members(i: &mut Interp, ctor: ObjId, proto: ObjId) -> JsResult<()> { method(i, proto, "readch", read_char, 0)?; method(i, proto, "seek", seek, 2)?; method(i, proto, "tell", tell, 0)?; - method(i, proto, "write", no_writes, 1)?; - method(i, proto, "writeln", no_writes, 1)?; - method(i, proto, "copy", no_writes, 1)?; - method(i, proto, "createAlias", no_writes, 1)?; - method(i, proto, "openDlg", no_picker, 0)?; - method(i, proto, "saveDlg", no_picker, 0)?; - method(i, ctor, "openDialog", null_static, 0)?; - method(i, ctor, "saveDialog", null_static, 0) + method(i, proto, "write", write, 1)?; + method(i, proto, "writeln", writeln, 1)?; + method(i, proto, "copy", copy, 1)?; + method(i, proto, "createAlias", create_alias, 1) } fn folder_members(i: &mut Interp, ctor: ObjId, proto: ObjId) -> JsResult<()> { method(i, proto, "getFiles", get_files, 1)?; - method(i, proto, "create", no_writes, 0)?; - method(i, proto, "selectDlg", no_picker, 0)?; - method(i, ctor, "selectDialog", null_static, 0)?; + method(i, proto, "create", create, 0)?; accessor(i, ctor, "current", get_current, Some(set_current))?; for (place, get) in PLACES.into_iter().zip(PLACE_GETTERS) { accessor(i, ctor, place, get, None)?; @@ -814,8 +1071,9 @@ pub(crate) fn install(i: &mut Interp, items: Vec<(String, HostItem)>) -> JsResul constructor(i, "Folder", folder, folder_proto)?; common(i, file, file_proto)?; common(i, folder, folder_proto)?; - file_members(i, file, file_proto)?; - folder_members(i, folder, folder_proto) + file_members(i, file_proto)?; + folder_members(i, folder, folder_proto)?; + dialogs(i, file, file_proto, folder, folder_proto) }) } @@ -847,7 +1105,7 @@ mod tests { ("parent", Data::String("/".into())), ]) }; - let messages = ["notOpen", "noWrites", "noPicker", "badMode"].map(|k| (k.to_string(), HostItem::Value(Data::String(k.into())))); + let messages = ["notOpen", "badMode", "noAlias", "noHidden"].map(|k| (k.to_string(), HostItem::Value(Data::String(k.into())))); let stat = move |a: Vec| -> Result { let dir = text(&a, 0) == "/d"; Ok(obj(vec![("exists", Data::Bool(dir)), ("dir", Data::Bool(dir))])) diff --git a/crates/js/src/host.rs b/crates/js/src/host.rs index fbb5e4fc90..375312f497 100644 --- a/crates/js/src/host.rs +++ b/crates/js/src/host.rs @@ -412,7 +412,12 @@ impl Interp { Ok(units) => self.prepare_source(units.len().saturating_sub(floor)), Err(_) => Ok(()), }; - rest.map(|()| units.and_then(|units| self.compile_source_writes(&units, false, writes, crate::bytecode::CodeKind::Eval))) + rest.map(|()| { + units.and_then(|units| { + self.observe_code(&units); + self.compile_source_writes(&units, false, writes, crate::bytecode::CodeKind::Eval) + }) + }) }); let code = code.and_then(|c| c); self.source_tag = tag; diff --git a/crates/js/src/host_tests.rs b/crates/js/src/host_tests.rs index de252c6c64..afd300c807 100644 --- a/crates/js/src/host_tests.rs +++ b/crates/js/src/host_tests.rs @@ -638,6 +638,24 @@ fn error_sources_count_from_the_last_script_and_code_from_an_earlier_one_is_unkn assert_eq!(r.error_source(), 0, "a syntax error is in the script"); } +#[test] +fn the_code_observer_sees_every_source_evaluated_at_run_time() { + let mut r = realm(10_000_000); + let seen = Rc::new(RefCell::new(Vec::::new())); + let s = seen.clone(); + r.observe_code(move |units| s.borrow_mut().push(String::from_utf16_lossy(units))); + let source: HostFunction = Rc::new(|_| Ok(Data::String("40 + 2".into()))); + let load = HostItem::Evaluator { source, end: Rc::new(|| {}), strict_writes: Rc::new(|| None) }; + r.define_host_object("host", vec![("load".into(), load)]).unwrap(); + let out = r.run("function f() { return eval('1 + 1'); } f() + (0, eval)('2') + Function('a', 'return a')(3) + host.load()").unwrap(); + assert_eq!(out, JsValue::Number(49.0)); + let want = ["1 + 1", "2", "(function anonymous(a\n) {\nreturn a\n})", "40 + 2"]; + assert_eq!(*seen.borrow(), want, "the script's own text is not observed"); + seen.borrow_mut().clear(); + r.run("eval(7); Function.prototype.toString.call(f)").unwrap(); + assert!(seen.borrow().is_empty(), "eval of a value that is not a string compiles nothing"); +} + #[test] fn error_tags_stay_the_same_from_run_to_run_and_are_never_shared() { let mut r = realm(10_000_000); diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index 22a365b615..2cbc5ae9cf 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -162,6 +162,9 @@ pub(crate) struct Frame { /// Where the exception being thrown was raised: the code and the instruction. type ThrowSite = (Rc, usize); +/// What [`crate::Realm::observe_code`] calls with each source evaluated at run time. +pub(crate) type CodeObserver = Rc; + pub(crate) struct Interp { pub(crate) heap: Heap, pub(crate) stack: Vec, @@ -230,6 +233,9 @@ pub(crate) struct Interp { pub(crate) source_tag: u32, /// The sources [`crate::HostItem::Evaluator`] functions have given in this realm. pub(crate) evaluated: u32, + /// Called with the source text given to `eval`, `Function` and evaluator functions, before it + /// is compiled ([`crate::Realm::observe_code`]). + pub(crate) code_observer: Option, /// The tag of the source the last run's error was raised in. pub(crate) error_tag: u32, /// The mark of the host error ([`crate::HostError::Marked`]) whose exception or limit is @@ -468,6 +474,7 @@ impl Interp { data_limits: crate::DataLimits::default(), source_tag: crate::realm::UNKNOWN_SOURCE, evaluated: 0, + code_observer: None, error_tag: crate::realm::UNKNOWN_SOURCE, thrown_mark: None, finally_marks: Vec::new(), @@ -2422,6 +2429,13 @@ impl Interp { crate::to_utf16(text, &self.remaining_source_options()).map_err(CompileError::Syntax) } + /// Gives `units`, source a script evaluates at run time, to the realm's code observer. + pub(crate) fn observe_code(&self, units: &[u16]) { + if let Some(f) = &self.code_observer { + f(units); + } + } + /// Parses and compiles source for eval code or a script, counting it against the source /// limit. pub(crate) fn compile_source(&mut self, units: &[u16], strict: bool, kind: CodeKind) -> Result, CompileError> { @@ -2460,6 +2474,7 @@ impl Interp { self.check_source_units(s.len()).map_err(|e| self.compile_error_to_abrupt(e))?; self.prepare_source(s.len())?; let units = self.flat_reserved(s)?; + self.observe_code(&units); let code = self.compile_source(&units, strict, CodeKind::Eval).map_err(|e| self.compile_error_to_abrupt(e))?; self.charge_code(&code, declaration_bytes(&code).saturating_add(ENV_BYTES))?; let frame = self.frame()?; diff --git a/crates/js/src/realm.rs b/crates/js/src/realm.rs index 077f3b19b6..fbef8911c2 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -457,10 +457,12 @@ impl Realm { /// Adds the global constructors `File` and `Folder`, whose file system work the host functions /// in `items` do: `parse`, `relative`, `tempName`, `stat`, `open`, `close`, `read`, `readln`, /// `readch`, `seek`, `tell`, `eof`, `encoding`, `setEncoding`, `list`, `resolve`, `execute`, - /// `encode`, `decode`, `encodingAvailable`, `current` and `locations`, with the values `system` - /// and `lineFeed` and the messages `text.notOpen`, `text.noWrites`, `text.noPicker` and - /// `text.badMode`. Each object keeps its path, its `error` text, its open file's id, its - /// encoding and its line feed in properties that are not enumerable. + /// `write`, `copy`, `remove`, `rename`, `create`, `setLength`, `setReadonly`, `pick` (the file + /// dialogs, where a run may wait), `encode`, `decode`, `encodingAvailable`, `current` and + /// `locations`, with the values `system` and `lineFeed` and the messages `text.notOpen`, + /// `text.badMode`, `text.noAlias` and `text.noHidden`. Each object keeps its path, its `error` + /// text, its open file's id, its encoding and its line feed in properties that are not + /// enumerable. pub fn define_file_classes(&mut self, items: Vec<(String, crate::HostItem)>) -> Result<(), RunError> { match crate::file_classes::install(&mut self.interp, items) { Ok(()) => Ok(()), @@ -532,6 +534,14 @@ impl Realm { self.interp.date_host.offset = std::rc::Rc::new(offset); } + /// Calls `observe` with the text of each source the realm's scripts evaluate at run time, before + /// it is compiled: a string given to `eval` (direct or indirect), the parameters and body + /// `Function` joins, and a source an evaluator host function + /// ([`crate::HostItem::Evaluator`]) gives. Replaces an earlier observer. + pub fn observe_code(&mut self, observe: impl Fn(&[u16]) + 'static) { + self.interp.code_observer = Some(std::rc::Rc::new(observe)); + } + /// Collects garbage now and returns the heap's estimated size in bytes afterwards. pub fn collect_garbage(&mut self) -> usize { self.interp.collect_garbage(); diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 67e67ac444..193e35b8dd 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -177,6 +177,8 @@ impl VectorcraftApp { automation_roots: None, synthetic_frame: false, pending_plugin_install: None, + script_picked: Vec::new(), + script_picked_left_out: false, pen_end: Default::default(), host_iteration: 0, #[cfg(test)] diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 197f8faaaa..8140dca6d6 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -422,6 +422,7 @@ registry! { ScriptGrowth: [script_run::GROWTH_KIND] => script_run::GROWTH_SPEC, ScriptClose: [script_run::CLOSE_KIND] => script_run::CLOSE_SPEC, ScriptNotice: [script_run::NOTICE_KIND] => script_run::NOTICE_SPEC, + ScriptFiles: [script_run::PICKER_KIND] => script_run::PICKER_SPEC, VectorHalftone: [halftone::KIND] => halftone::SPEC, SimplifySlider: [simplify_slider::KIND] => simplify_slider::SPEC, SmoothSlider: [smooth_slider::KIND] => smooth_slider::SPEC, @@ -671,6 +672,9 @@ pub fn cancel(app: &mut VectorcraftApp) { if d.kind == script_run::NOTICE_KIND { script_run::notice_cancel(app, &d); } + if d.kind == script_run::PICKER_KIND { + script_run::picker_cancel(app, &d); + } // 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 index 8f5e3b1093..f8baa7b7de 100644 --- a/crates/ui-egui/src/dialogs/script_run.rs +++ b/crates/ui-egui/src/dialogs/script_run.rs @@ -13,10 +13,22 @@ //! `stop`. OK, Enter or `ui.dialog.confirm` without an `answer` gives the default button's answer. //! Escape or `ui.dialog.cancel` gives Cancel for a prompt, No for a confirm and Stop for an alert. //! Stop ends the run and puts back everything it did. +//! +//! A script's file dialog (kind `scriptFiles`: `File.openDialog`, `File.saveDialog`, +//! `Folder.selectDialog` and the objects' `openDlg`, `saveDlg` and `selectDlg`) has the fields +//! `kind` (open, save or folder), `prompt` and `canAlways`, and takes `answer`: `once`, `always` +//! (only with `canAlways`), `deny` or `stop`. Only the person at the keyboard answers `once` or +//! `always`: from `ui.dialog.set`, `ui.dialog.confirm` or synthetic input they are refused, and the +//! dialog stays open; `deny` and `stop` are taken from automation too. The paths it allows are the +//! ones Choose… picked in the host's file dialog, at most 2,048; `ui.dialog.set` cannot set them, +//! and the dialog's own fields change neither what it allows nor what it says it allows. Escape, +//! `ui.dialog.cancel`, Enter, and OK or `ui.dialog.confirm` without an `answer` give Deny. +//! `selectDlg` opens the host's folder picker in its own folder. use serde_json::{Value, json}; use vectorcraft_engine::cmd::scripts::{RUN_EXTS, TOO_LARGE, runs}; use vectorcraft_engine::script::dialogs::{MAX_PROMPT_BYTES, cut_to, shown_text}; +use vectorcraft_engine::script::files::{MAX_ENTRIES, PickAnswer, PickerKind, ScriptPicker}; use vectorcraft_engine::script::{DialogAnswer, ScriptDialog}; use super::{DialogAction, DialogSpec}; @@ -32,6 +44,19 @@ pub const GROWTH_KIND: &str = "scriptGrowth"; pub const CLOSE_KIND: &str = "scriptClose"; /// The dialog kind of a script's `alert`, `confirm` and `prompt`. pub const NOTICE_KIND: &str = "scriptDialog"; +/// The dialog kind of a script's file dialogs. +pub const PICKER_KIND: &str = "scriptFiles"; + +pub(super) const PICKER_SPEC: DialogSpec = DialogSpec { + heading: |_| tl!("Script File Access").into(), + body_with_actions: Some(picker_body), + confirm: picker_confirm, + ok: None, + inputs: |_| &["answer"], + min_width: 420.0, + max_width: Some(560.0), + ..DialogSpec::FORM +}; pub(super) const NOTICE_SPEC: DialogSpec = DialogSpec { heading: notice_heading, @@ -171,7 +196,7 @@ fn close_confirm(app: &mut VectorcraftApp, _: &Dialog) -> Result /// Quitting while a script runs asks whether to stop it, also over the script's own dialog, which /// Cancel shows again as it was. Any other open dialog stays, and quitting asks nothing yet. pub(crate) fn ask_to_close(app: &mut VectorcraftApp) { - let notice = app.ui.dialog.take_if(|d| d.kind == NOTICE_KIND); + let notice = app.ui.dialog.take_if(|d| d.kind == NOTICE_KIND || d.kind == PICKER_KIND); if app.ui.dialog.is_some() { return; } @@ -192,6 +217,7 @@ pub(crate) fn settle_close(app: &mut VectorcraftApp) { if !app.session.script_running() { app.ui.dialog = None; } else if app.session.script_dialog().is_none() + && app.session.script_picker().is_none() && let Some(d) = app.ui.dialog.as_mut() { d.fields.remove(super::PARENT); @@ -327,6 +353,192 @@ fn give(app: &mut VectorcraftApp, d: &Dialog, answer: &str) -> Result = match p.kind { + PickerKind::Open if several => crate::picks::open_files(app, &pick), + PickerKind::Open => crate::picks::open(app, &pick).into_iter().collect(), + PickerKind::Save => crate::picks::save(app, &pick).into_iter().collect(), + // `selectDlg` starts in its folder; `Folder.selectDialog` gives none. + PickerKind::Folder => match p.start.clone() { + Some(start) => crate::picks::folder_at(app, &start).into_iter().collect(), + None => crate::picks::folder(app).into_iter().collect(), + }, + }; + if !chosen.is_empty() { + let mut paths = if several { std::mem::take(&mut app.script_picked) } else { Vec::new() }; + let mut seen: std::collections::HashSet = paths.iter().cloned().collect(); + for path in chosen { + if seen.contains(&path) { + continue; + } + if paths.len() >= MAX_ENTRIES { + app.script_picked_left_out = true; + break; + } + seen.insert(path.clone()); + paths.push(path); + } + app.script_picked = paths; + } + Ok(()) + }); + // Picking a path doesn't fail. + let _ = r; +} + +/// The dialog's prompt and the access it describes come from the request the run waits at, not +/// from the dialog's fields, so `ui.dialog.set` cannot change what the person reads. +fn picker_body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> DialogAction { + let t = Tokens::get(ui.ctx()); + let Some((kind, prompt)) = app.session.script_picker().map(|p| (p.kind, shown_text(&p.prompt, true))) else { return DialogAction::None }; + if !prompt.is_empty() { + egui::ScrollArea::vertical().max_height(160.0).show(ui, |ui| ui.label(&prompt)); + ui.add_space(8.0); + } + ui.label(picker_request(kind)); + ui.add_space(8.0); + let paths = app.script_picked.clone(); + ui.horizontal(|ui| { + if widgets::secondary_button(ui, tl!("Choose…")).clicked() { + choose(app, d); + } + ui.add_space(8.0); + if let [path] = paths.as_slice() { + ui.label(egui::RichText::new(shown_text(path, false)).color(t.text_strong)); + } + }); + if paths.len() > 1 { + ui.add_space(4.0); + egui::ScrollArea::vertical().id_salt("script-picked").max_height(120.0).show(ui, |ui| { + for path in &paths { + ui.label(egui::RichText::new(shown_text(path, false)).color(t.text_strong)); + } + }); + } + if app.script_picked_left_out { + ui.add_space(4.0); + ui.colored_label(t.error, crate::i18n::msg(PICKED_LEFT_OUT)); + } + ui.add_space(16.0); + let chosen = !app.script_picked.is_empty(); + let can_always = app.session.script_picker().is_some_and(|p| p.can_always); + let mut answer = None; + let row = egui::vec2(ui.min_rect().width(), ui.spacing().interact_size.y); + ui.allocate_ui_with_layout(row, egui::Layout::right_to_left(egui::Align::Center), |ui| { + if widgets::primary_button_enabled(ui, tl!("Allow Once"), chosen).clicked() { + answer = Some("once"); + } + ui.add_space(8.0); + if can_always { + if ui.add_enabled_ui(chosen, |ui| widgets::secondary_button(ui, tl!("Always Allow This Script"))).inner.clicked() { + answer = Some("always"); + } + ui.add_space(8.0); + } + if widgets::secondary_button(ui, tl!("Deny")).clicked() { + answer = Some("deny"); + } + // The row runs right to left: Stop goes at its left end. + ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| { + if widgets::secondary_button(ui, tl!("Stop")).clicked() { + answer = Some("stop"); + } + }); + }); + // Enter gives the dialog's default answer, Deny, as `ui.dialog.confirm` without an answer does, + // unless it goes to the button that has the keyboard focus (Choose…). + let unfocused = ui.ctx().memory(|m| m.focused().is_none()); + if answer.is_none() && unfocused && crate::shortcuts::pressed_anew(ui.ctx(), egui::Key::Enter) { + answer = Some("deny"); + } + let Some(answer) = answer else { return DialogAction::None }; + d.fields.insert("answer".into(), json!(answer)); + DialogAction::Confirm +} + +/// What the file dialog of `kind` asks the person to allow. +fn picker_request(kind: PickerKind) -> &'static str { + match kind { + PickerKind::Open => tl!("The script asks to read a file you choose."), + PickerKind::Save => tl!("The script asks to read and write a file you choose."), + PickerKind::Folder => tl!("The script asks to read and write a folder you choose, with everything in it."), + } +} + +/// The note the file dialog shows when the person picked more files than a script is given. +const PICKED_LEFT_OUT: &str = "A script is given at most 2,048 files: the files picked after them were left out"; + +/// Gives the running script the file dialog's `answer`, or Deny. +fn picker_confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { + let answer = d.fields.get("answer").and_then(Value::as_str).unwrap_or("deny"); + give_pick(app, answer) +} + +/// Escape or Cancel: Deny. +pub(super) fn picker_cancel(app: &mut VectorcraftApp, _: &Dialog) { + let _ = give_pick(app, "deny"); +} + +/// Gives the running script `answer` with the paths Choose… picked. Only the person at the keyboard +/// allows access: Allow Once and Always Allow are refused, and the dialog stays open, while +/// automation sends the answer (a control or MCP request, or synthetic input) or opened the host's +/// file dialog; Deny and Stop are taken from anyone. +fn give_pick(app: &mut VectorcraftApp, answer: &str) -> Result { + let paths = app.script_picked.clone(); + let can_always = app.session.script_picker().is_some_and(|p| p.can_always); + let given = match answer { + "stop" => None, + "deny" => Some(PickAnswer::Deny), + "once" | "always" if app.automation_asked() => return Err("Only the person at the keyboard can allow a script's file access".into()), + "once" | "always" if paths.is_empty() => return Err("choose a file or folder first, or deny".into()), + "always" if !can_always => return Err("this script's file access can be allowed only once".into()), + "once" => Some(PickAnswer::Allow { paths, always: false }), + "always" => Some(PickAnswer::Allow { paths, always: true }), + _ => return Err("`answer` for a script's file dialog must be one of: once, always, deny, stop".into()), + }; + app.script_picked.clear(); + app.script_picked_left_out = false; + match given { + None => { + app.session.script_request_stop(); + } + Some(a) => { + app.session.script_pick(a); + } + } + if app.ui.dialog.as_ref().is_some_and(|open| open.kind == PICKER_KIND) { + app.ui.dialog = None; + } + Ok(Value::Null) +} + fn answers_for(kind: &str) -> &'static str { match kind { "confirm" => "yes, no, stop", diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 3828d9ba2d..f69fbaaf2d 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -4094,6 +4094,13 @@ axis Both И двете Show External Script Warning Показвай предупреждение за външни скриптове A Script Is Running Изпълнява се скрипт Script Alert Известие от скрипт + Script File Access Достъп на скрипт до файлове + The script asks to read a file you choose. Скриптът иска да прочете файл, който изберете. + The script asks to read and write a file you choose. Скриптът иска да чете и записва файл, който изберете. + The script asks to read and write a folder you choose, with everything in it. Скриптът иска да чете и записва папка, която изберете, с цялото ѝ съдържание. + Allow Once Разреши веднъж + Always Allow This Script Винаги разрешавай този скрипт + Deny Откажи A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Скриптът може да променя отворените документи и да записва файлове чрез командите, които изпълнява. Изпълнявайте само скриптове, на които имате доверие. Do not show this warning again Не показвай повече това предупреждение Stop the script and undo what it did? Then quit again. Да се спре ли скриптът и да се отменят ли промените му? След това излезте отново. diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 81fee3a079..7dae2382aa 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -4459,6 +4459,13 @@ imageTrace Outline Obris Show External Script Warning Prikaži upozorenje za vanjske skripte A Script Is Running Skripta se izvršava Script Alert Upozorenje skripte + Script File Access Pristup skripte datotekama + The script asks to read a file you choose. Skripta traži da pročita datoteku koju odaberete. + The script asks to read and write a file you choose. Skripta traži da čita i piše datoteku koju odaberete. + The script asks to read and write a folder you choose, with everything in it. Skripta traži da čita i piše folder koji odaberete, sa svim što je u njemu. + Allow Once Dozvoli jednom + Always Allow This Script Uvijek dozvoli ovu skriptu + Deny Odbij A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Skripta može mijenjati otvorene dokumente i pisati datoteke putem naredbi koje pokreće. Pokrećite samo skripte kojima vjerujete. Do not show this warning again Ne prikazuj više ovo upozorenje Stop the script and undo what it did? Then quit again. Zaustaviti skriptu i poništiti ono što je uradila? Zatim ponovo izađite. diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 02ae0f4a09..03f88d8386 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -5390,6 +5390,13 @@ digits Malayalam Malaiàlam Show External Script Warning Mostra l'avís dels scripts externs A Script Is Running S'està executant un script Script Alert Avís de l'script + Script File Access Accés de l’script als fitxers + The script asks to read a file you choose. L’script demana llegir un fitxer que trieu. + The script asks to read and write a file you choose. L’script demana llegir i escriure un fitxer que trieu. + The script asks to read and write a folder you choose, with everything in it. L’script demana llegir i escriure una carpeta que trieu, amb tot el que conté. + Allow Once Permet un cop + Always Allow This Script Permet sempre aquest script + Deny Denega A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Un script pot canviar els documents oberts i escriure fitxers mitjançant les ordres que executa. Executeu només scripts de confiança. Do not show this warning again No tornis a mostrar aquest avís 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. @@ -5418,8 +5425,6 @@ digits Malayalam Malaiàlam @msg Script file could not be read No s'ha pogut llegir el fitxer de l'script @msg Script folder has more than 2,048 entries La carpeta de l'script té més de 2.048 entrades @msg Script file open mode must be r, w, e or a El mode d'obertura del fitxer de l'script ha de ser r, w, e o a -@msg Script file writing is not available L'escriptura de fitxers de l'script no està disponible -@msg Script file dialogs are not available Els quadres de diàleg de fitxers de l'script no estan disponibles @msg Script files cannot be opened in another application Els fitxers de l'script no es poden obrir en una altra aplicació @msg Script file access is unavailable on the web L'accés als fitxers de l'script no està disponible al web @msg Script has 256 files open L'script té 256 fitxers oberts @@ -5490,6 +5495,27 @@ digits Malayalam Malaiàlam @msg there is no script engine named {name} no hi ha cap motor d'scripts anomenat {name} @msg Running a script S'està executant un script @msg Copied the script report S’ha copiat l’informe de l’script +@msg Script file access denied: {path} S’ha denegat l’accés de l’script als fitxers: {path} +@msg Script file access to the app's own folders is not allowed Els scripts no poden accedir a les carpetes pròpies de l’aplicació +@msg Script file cannot encode the text El fitxer de l’script no pot codificar el text +@msg Script file could not be written No s’ha pogut escriure el fitxer de l’script +@msg Script file dialogs need a person to answer them Els diàlegs de fitxers de l’script necessiten una persona que els respongui +@msg Script file is not open for writing El fitxer de l’script no està obert per escriure-hi +@msg Script file name is already in use El nom del fitxer de l’script ja està en ús +@msg Script file name must be a name without a folder El nom del fitxer de l’script ha de ser un nom sense carpeta +@msg Script file permission can be kept only for a script run from a file El permís de fitxers només es pot conservar per a un script executat des d’un fitxer +@msg Script file permission could not be saved No s’ha pogut desar el permís de fitxers de l’script +@msg Script folder is not empty La carpeta de l’script no és buida +@msg Script files cannot make aliases Els fitxers de l’script no poden crear àlies +@msg Script file hidden setting cannot be changed No es pot canviar l’opció d’ocult del fitxer de l’script +@msg {name}: a file dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: un diàleg de fitxers no es pot obrir dins d’una crida de retorn d’una funció integrada, d’un getter, d’una conversió o d’un fitxer que executa $.evalFile; crideu-lo des del codi propi de l’script +@msg the script wrote more file data than one run may write (32 MiB) l’script ha escrit més dades de fitxers de les que pot escriure una execució (32 MiB) +@msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` per al diàleg de fitxers d’un script ha de ser un d’aquests: once, always, deny, stop +@msg choose a file or folder first, or deny trieu primer un fitxer o una carpeta, o denegueu +@msg the script file permissions could not be saved: {e} no s’han pogut desar els permisos de fitxers dels scripts: {e} +@msg this script's file access can be allowed only once l’accés als fitxers d’aquest script només es pot permetre una vegada +@msg Only the person at the keyboard can allow a script's file access Només la persona al teclat pot permetre l’accés als fitxers d’un script +@msg A script is given at most 2,048 files: the files picked after them were left out Un script rep com a màxim 2.048 fitxers: els fitxers triats després d’aquests s’han deixat fora @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} @msg Couldn't copy to the system clipboard: {e} No s’ha pogut copiar al porta-retalls del sistema: {e} diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 7e3794e8a1..f57201ed46 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -4521,6 +4521,13 @@ imageTrace Outline Obrys Show External Script Warning Zobrazit upozornění u externích skriptů A Script Is Running Běží skript Script Alert Upozornění skriptu + Script File Access Přístup skriptu k souborům + The script asks to read a file you choose. Skript žádá o čtení souboru, který vyberete. + The script asks to read and write a file you choose. Skript žádá o čtení a zápis souboru, který vyberete. + The script asks to read and write a folder you choose, with everything in it. Skript žádá o čtení a zápis složky, kterou vyberete, se vším, co obsahuje. + Allow Once Povolit jednou + Always Allow This Script Vždy povolit tento skript + Deny Zamítnout A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Skript může měnit otevřené dokumenty a prostřednictvím příkazů, které spouští, zapisovat soubory. Spouštějte jen skripty, kterým důvěřujete. Do not show this warning again Toto upozornění již nezobrazovat Stop the script and undo what it did? Then quit again. Zastavit skript a vrátit jeho změny? Potom aplikaci ukončete znovu. @@ -4549,8 +4556,6 @@ imageTrace Outline Obrys @msg Script file could not be read Soubor skriptu se nepodařilo přečíst @msg Script folder has more than 2,048 entries Složka skriptu má více než 2 048 položek @msg Script file open mode must be r, w, e or a Režim otevření souboru skriptu musí být r, w, e nebo a -@msg Script file writing is not available Zápis souborů skriptu není k dispozici -@msg Script file dialogs are not available Dialogy souborů skriptu nejsou k dispozici @msg Script files cannot be opened in another application Soubory skriptu nelze otevřít v jiné aplikaci @msg Script file access is unavailable on the web Přístup k souborům skriptu není na webu k dispozici @msg Script has 256 files open Skript má otevřeno 256 souborů @@ -4621,6 +4626,27 @@ imageTrace Outline Obrys @msg there is no script engine named {name} skriptovací jádro s názvem {name} neexistuje @msg Running a script Běží skript @msg Copied the script report Zpráva o skriptu zkopírována +@msg Script file access denied: {path} Přístup skriptu k souborům byl odepřen: {path} +@msg Script file access to the app's own folders is not allowed Skript nemá povolen přístup k vlastním složkám aplikace +@msg Script file cannot encode the text Soubor skriptu nemůže zakódovat text +@msg Script file could not be written Soubor skriptu nelze zapsat +@msg Script file dialogs need a person to answer them Dialogy souborů skriptu potřebují osobu, která na ně odpoví +@msg Script file is not open for writing Soubor skriptu není otevřený pro zápis +@msg Script file name is already in use Název souboru skriptu se už používá +@msg Script file name must be a name without a folder Název souboru skriptu musí být název bez složky +@msg Script file permission can be kept only for a script run from a file Oprávnění k souborům lze zachovat jen pro skript spuštěný ze souboru +@msg Script file permission could not be saved Oprávnění skriptu k souborům nelze uložit +@msg Script folder is not empty Složka skriptu není prázdná +@msg Script files cannot make aliases Soubory skriptu nemohou vytvářet aliasy +@msg Script file hidden setting cannot be changed Nastavení skrytí souboru skriptu nelze změnit +@msg {name}: a file dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: dialog souboru nelze otevřít uvnitř zpětného volání vestavěné funkce, getteru, převodu ani souboru, který spouští $.evalFile; volejte jej z vlastního kódu skriptu +@msg the script wrote more file data than one run may write (32 MiB) skript zapsal více dat souborů, než smí zapsat jeden běh (32 MiB) +@msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` pro dialog souboru skriptu musí být jedna z hodnot: once, always, deny, stop +@msg choose a file or folder first, or deny nejprve vyberte soubor nebo složku, nebo odmítněte +@msg the script file permissions could not be saved: {e} oprávnění skriptů k souborům nelze uložit: {e} +@msg this script's file access can be allowed only once přístup tohoto skriptu k souborům lze povolit jen jednou +@msg Only the person at the keyboard can allow a script's file access Přístup skriptu k souborům může povolit jen člověk u klávesnice +@msg A script is given at most 2,048 files: the files picked after them were left out Skript dostane nejvýše 2 048 souborů: soubory vybrané po nich byly vynechány @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} @msg Couldn't open {name}: {e} {name} nelze otevřít: {e} diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index f7011e23bf..3fb08554b0 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -4213,6 +4213,13 @@ imageTrace Outline Kontur Show External Script Warning Vis advarsel om eksterne scripts A Script Is Running Et script kører Script Alert Scriptadvarsel + Script File Access Scriptadgang til filer + The script asks to read a file you choose. Scriptet beder om at læse en fil, du vælger. + The script asks to read and write a file you choose. Scriptet beder om at læse og skrive en fil, du vælger. + The script asks to read and write a folder you choose, with everything in it. Scriptet beder om at læse og skrive en mappe, du vælger, med alt indhold. + Allow Once Tillad én gang + Always Allow This Script Tillad altid dette script + Deny Afvis A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Et script kan ændre de åbne dokumenter og skrive filer gennem de kommandoer, det kører. Kør kun scripts, du stoler på. Do not show this warning again Vis ikke denne advarsel igen Stop the script and undo what it did? Then quit again. Stop scriptet og fortryd det, det har gjort? Afslut derefter igen. diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 4174537f87..de0e4eb16b 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -4135,6 +4135,13 @@ theme Appearance Erscheinungsbild Show External Script Warning Warnung bei externen Skripten anzeigen A Script Is Running Ein Skript wird ausgeführt Script Alert Skriptmeldung + Script File Access Dateizugriff des Skripts + The script asks to read a file you choose. Das Skript möchte eine Datei lesen, die Sie auswählen. + The script asks to read and write a file you choose. Das Skript möchte eine Datei lesen und schreiben, die Sie auswählen. + The script asks to read and write a folder you choose, with everything in it. Das Skript möchte einen Ordner, den Sie auswählen, mit seinem gesamten Inhalt lesen und schreiben. + Allow Once Einmal erlauben + Always Allow This Script Dieses Skript immer erlauben + Deny Ablehnen A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Ein Skript kann die geöffneten Dokumente ändern und über die ausgeführten Befehle Dateien schreiben. Führen Sie nur Skripte aus, denen Sie vertrauen. Do not show this warning again Diese Warnung nicht mehr anzeigen Stop the script and undo what it did? Then quit again. Skript stoppen und seine Änderungen rückgängig machen? Beenden Sie danach erneut. @@ -4163,8 +4170,6 @@ theme Appearance Erscheinungsbild @msg Script file could not be read Die Skriptdatei konnte nicht gelesen werden @msg Script folder has more than 2,048 entries Der Skriptordner hat mehr als 2.048 Einträge @msg Script file open mode must be r, w, e or a Der Öffnungsmodus der Skriptdatei muss r, w, e oder a sein -@msg Script file writing is not available Das Schreiben von Skriptdateien ist nicht verfügbar -@msg Script file dialogs are not available Dateidialoge für Skripte sind nicht verfügbar @msg Script files cannot be opened in another application Skriptdateien können nicht in einer anderen Anwendung geöffnet werden @msg Script file access is unavailable on the web Der Zugriff auf Skriptdateien ist im Web nicht verfügbar @msg Script has 256 files open Das Skript hat 256 Dateien geöffnet @@ -4235,6 +4240,27 @@ theme Appearance Erscheinungsbild @msg there is no script engine named {name} es gibt keine Skript-Engine namens {name} @msg Running a script Skript wird ausgeführt @msg Copied the script report Skriptbericht kopiert +@msg Script file access denied: {path} Dateizugriff des Skripts verweigert: {path} +@msg Script file access to the app's own folders is not allowed Skripte dürfen nicht auf die eigenen Ordner der App zugreifen +@msg Script file cannot encode the text Skriptdatei kann den Text nicht kodieren +@msg Script file could not be written Skriptdatei konnte nicht geschrieben werden +@msg Script file dialogs need a person to answer them Dateidialoge von Skripten brauchen eine Person, die sie beantwortet +@msg Script file is not open for writing Skriptdatei ist nicht zum Schreiben geöffnet +@msg Script file name is already in use Name der Skriptdatei wird bereits verwendet +@msg Script file name must be a name without a folder Name der Skriptdatei muss ein Name ohne Ordner sein +@msg Script file permission can be kept only for a script run from a file Dateiberechtigung kann nur für ein Skript behalten werden, das aus einer Datei ausgeführt wird +@msg Script file permission could not be saved Dateiberechtigung des Skripts konnte nicht gespeichert werden +@msg Script folder is not empty Skriptordner ist nicht leer +@msg Script files cannot make aliases Skriptdateien können keine Aliasse erstellen +@msg Script file hidden setting cannot be changed Ausgeblendet-Einstellung der Skriptdatei kann nicht geändert werden +@msg {name}: a file dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: ein Dateidialog kann nicht in einem Callback einer eingebauten Funktion, eines Getters, einer Umwandlung oder einer Datei geöffnet werden, die $.evalFile ausführt; rufen Sie ihn aus dem eigenen Code des Skripts auf +@msg the script wrote more file data than one run may write (32 MiB) das Skript hat mehr Dateidaten geschrieben, als ein Lauf schreiben darf (32 MiB) +@msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` für den Dateidialog eines Skripts muss einer der folgenden Werte sein: once, always, deny, stop +@msg choose a file or folder first, or deny wählen Sie zuerst eine Datei oder einen Ordner aus oder lehnen Sie ab +@msg the script file permissions could not be saved: {e} die Dateiberechtigungen der Skripte konnten nicht gespeichert werden: {e} +@msg this script's file access can be allowed only once der Dateizugriff dieses Skripts kann nur einmal erlaubt werden +@msg Only the person at the keyboard can allow a script's file access Nur die Person an der Tastatur kann den Dateizugriff eines Skripts erlauben +@msg A script is given at most 2,048 files: the files picked after them were left out Ein Skript erhält höchstens 2.048 Dateien: Die danach ausgewählten Dateien wurden weggelassen @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} @msg Couldn't open {name}: {e} {name} konnte nicht geöffnet werden: {e} diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index bde2fbee78..b4229beada 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -2309,6 +2309,13 @@ axis Both Και τα δύο Show External Script Warning Εμφάνιση προειδοποίησης για εξωτερικά σενάρια A Script Is Running Εκτελείται ένα σενάριο Script Alert Ειδοποίηση σεναρίου + Script File Access Πρόσβαση σεναρίου σε αρχεία + The script asks to read a file you choose. Το σενάριο ζητά να διαβάσει ένα αρχείο που θα επιλέξετε. + The script asks to read and write a file you choose. Το σενάριο ζητά να διαβάσει και να γράψει ένα αρχείο που θα επιλέξετε. + The script asks to read and write a folder you choose, with everything in it. Το σενάριο ζητά να διαβάσει και να γράψει έναν φάκελο που θα επιλέξετε, με όλο το περιεχόμενό του. + Allow Once Να επιτραπεί μία φορά + Always Allow This Script Να επιτρέπεται πάντα αυτό το σενάριο + Deny Άρνηση A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Ένα σενάριο μπορεί να αλλάξει τα ανοιχτά έγγραφα και να γράψει αρχεία μέσω των εντολών που εκτελεί. Εκτελείτε μόνο σενάρια που εμπιστεύεστε. Do not show this warning again Να μην εμφανιστεί ξανά αυτή η προειδοποίηση Stop the script and undo what it did? Then quit again. Διακοπή του σεναρίου και αναίρεση όσων έκανε; Έπειτα κάντε ξανά έξοδο. @@ -2337,8 +2344,6 @@ axis Both Και τα δύο @msg Script file could not be read Δεν ήταν δυνατή η ανάγνωση του αρχείου σεναρίου @msg Script folder has more than 2,048 entries Ο φάκελος σεναρίου έχει περισσότερες από 2.048 καταχωρίσεις @msg Script file open mode must be r, w, e or a Ο τρόπος ανοίγματος του αρχείου σεναρίου πρέπει να είναι r, w, e ή a -@msg Script file writing is not available Η εγγραφή αρχείων σεναρίου δεν είναι διαθέσιμη -@msg Script file dialogs are not available Τα παράθυρα διαλόγου αρχείων σεναρίου δεν είναι διαθέσιμα @msg Script files cannot be opened in another application Τα αρχεία σεναρίου δεν μπορούν να ανοίξουν σε άλλη εφαρμογή @msg Script file access is unavailable on the web Η πρόσβαση σε αρχεία σεναρίου δεν είναι διαθέσιμη στο web @msg Script has 256 files open Το σενάριο έχει 256 ανοιχτά αρχεία @@ -2409,6 +2414,27 @@ axis Both Και τα δύο @msg there is no script engine named {name} δεν υπάρχει μηχανή σεναρίων με όνομα {name} @msg Running a script Εκτελείται σενάριο @msg Copied the script report Η αναφορά του σεναρίου αντιγράφηκε +@msg Script file access denied: {path} Η πρόσβαση του σεναρίου σε αρχεία απορρίφθηκε: {path} +@msg Script file access to the app's own folders is not allowed Δεν επιτρέπεται η πρόσβαση σεναρίων στους φακέλους της ίδιας της εφαρμογής +@msg Script file cannot encode the text Το αρχείο του σεναρίου δεν μπορεί να κωδικοποιήσει το κείμενο +@msg Script file could not be written Δεν ήταν δυνατή η εγγραφή του αρχείου του σεναρίου +@msg Script file dialogs need a person to answer them Τα παράθυρα διαλόγου αρχείων του σεναρίου χρειάζονται ένα άτομο για να απαντήσει +@msg Script file is not open for writing Το αρχείο του σεναρίου δεν είναι ανοιχτό για εγγραφή +@msg Script file name is already in use Το όνομα του αρχείου του σεναρίου χρησιμοποιείται ήδη +@msg Script file name must be a name without a folder Το όνομα του αρχείου του σεναρίου πρέπει να είναι όνομα χωρίς φάκελο +@msg Script file permission can be kept only for a script run from a file Η άδεια αρχείων μπορεί να διατηρηθεί μόνο για σενάριο που εκτελείται από αρχείο +@msg Script file permission could not be saved Δεν ήταν δυνατή η αποθήκευση της άδειας αρχείων του σεναρίου +@msg Script folder is not empty Ο φάκελος του σεναρίου δεν είναι κενός +@msg Script files cannot make aliases Τα αρχεία του σεναρίου δεν μπορούν να δημιουργήσουν ψευδώνυμα +@msg Script file hidden setting cannot be changed Η ρύθμιση απόκρυψης του αρχείου του σεναρίου δεν μπορεί να αλλάξει +@msg {name}: a file dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: ένα παράθυρο διαλόγου αρχείων δεν μπορεί να ανοίξει μέσα σε callback ενσωματωμένης συνάρτησης, getter, μετατροπής ή αρχείου που εκτελεί το $.evalFile· καλέστε το από τον κώδικα του ίδιου του σεναρίου +@msg the script wrote more file data than one run may write (32 MiB) το σενάριο έγραψε περισσότερα δεδομένα αρχείων από όσα επιτρέπεται να γράψει μία εκτέλεση (32 MiB) +@msg `answer` for a script's file dialog must be one of: once, always, deny, stop το `answer` για το παράθυρο διαλόγου αρχείων ενός σεναρίου πρέπει να είναι ένα από: once, always, deny, stop +@msg choose a file or folder first, or deny επιλέξτε πρώτα ένα αρχείο ή έναν φάκελο, ή απορρίψτε +@msg the script file permissions could not be saved: {e} δεν ήταν δυνατή η αποθήκευση των αδειών αρχείων των σεναρίων: {e} +@msg this script's file access can be allowed only once η πρόσβαση αυτού του σεναρίου σε αρχεία μπορεί να επιτραπεί μόνο μία φορά +@msg Only the person at the keyboard can allow a script's file access Μόνο το άτομο στο πληκτρολόγιο μπορεί να επιτρέψει την πρόσβαση ενός σεναρίου σε αρχεία +@msg A script is given at most 2,048 files: the files picked after them were left out Ένα σενάριο λαμβάνει το πολύ 2.048 αρχεία: τα αρχεία που επιλέχθηκαν μετά από αυτά παραλείφθηκαν @msg Corners edits the corners of a path Η εντολή Γωνίες επεξεργάζεται τις γωνίες μιας διαδρομής @msg Couldn't copy to the system clipboard: {e} Δεν ήταν δυνατή η αντιγραφή στο πρόχειρο συστήματος: {e} @msg Couldn't open {name}: {e} Δεν ήταν δυνατό το άνοιγμα του {name}: {e} diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index ff28d9dfc5..37af97bec8 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -4211,6 +4211,13 @@ axis Both Ambos Show External Script Warning Mostrar advertencia de scripts externos A Script Is Running Se está ejecutando un script Script Alert Aviso del script + Script File Access Acceso del script a archivos + The script asks to read a file you choose. El script pide leer un archivo que usted elija. + The script asks to read and write a file you choose. El script pide leer y escribir un archivo que usted elija. + The script asks to read and write a folder you choose, with everything in it. El script pide leer y escribir una carpeta que usted elija, con todo su contenido. + Allow Once Permitir una vez + Always Allow This Script Permitir siempre este script + Deny Denegar A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Un script puede cambiar los documentos abiertos y escribir archivos mediante los comandos que ejecuta. Ejecute solo scripts de confianza. Do not show this warning again No volver a mostrar esta advertencia Stop the script and undo what it did? Then quit again. ¿Detener el script y deshacer lo que hizo? Después, vuelva a salir. @@ -4239,8 +4246,6 @@ axis Both Ambos @msg Script file could not be read No se pudo leer el archivo de script @msg Script folder has more than 2,048 entries La carpeta de script tiene más de 2048 entradas @msg Script file open mode must be r, w, e or a El modo de apertura del archivo de script debe ser r, w, e o a -@msg Script file writing is not available La escritura de archivos de script no está disponible -@msg Script file dialogs are not available Los cuadros de diálogo de archivos de script no están disponibles @msg Script files cannot be opened in another application Los archivos de script no se pueden abrir en otra aplicación @msg Script file access is unavailable on the web El acceso a archivos de script no está disponible en la web @msg Script has 256 files open El script tiene 256 archivos abiertos @@ -4311,6 +4316,27 @@ axis Both Ambos @msg there is no script engine named {name} no hay ningún motor de scripts llamado {name} @msg Running a script Ejecutando un script @msg Copied the script report Se copió el informe del script +@msg Script file access denied: {path} Acceso del script a archivos denegado: {path} +@msg Script file access to the app's own folders is not allowed El script no puede acceder a las carpetas propias de la aplicación +@msg Script file cannot encode the text El archivo del script no puede codificar el texto +@msg Script file could not be written No se pudo escribir el archivo del script +@msg Script file dialogs need a person to answer them Los cuadros de diálogo de archivo del script necesitan que una persona los responda +@msg Script file is not open for writing El archivo del script no está abierto para escritura +@msg Script file name is already in use El nombre del archivo del script ya está en uso +@msg Script file name must be a name without a folder El nombre del archivo del script debe ser un nombre sin carpeta +@msg Script file permission can be kept only for a script run from a file El permiso de archivos solo se puede conservar para un script ejecutado desde un archivo +@msg Script file permission could not be saved No se pudo guardar el permiso de archivos del script +@msg Script folder is not empty La carpeta del script no está vacía +@msg Script files cannot make aliases Los archivos del script no pueden crear alias +@msg Script file hidden setting cannot be changed No se puede cambiar el ajuste de oculto del archivo del script +@msg {name}: a file dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: un cuadro de diálogo de archivo no se puede abrir dentro de una devolución de llamada de una función integrada, un getter, una conversión o un archivo que ejecuta $.evalFile; llámelo desde el propio código del script +@msg the script wrote more file data than one run may write (32 MiB) el script escribió más datos de archivo de los que puede escribir una ejecución (32 MiB) +@msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` para el cuadro de diálogo de archivo de un script debe ser uno de: once, always, deny, stop +@msg choose a file or folder first, or deny elija primero un archivo o una carpeta, o deniegue +@msg the script file permissions could not be saved: {e} no se pudieron guardar los permisos de archivos de los scripts: {e} +@msg this script's file access can be allowed only once el acceso a archivos de este script solo se puede permitir una vez +@msg Only the person at the keyboard can allow a script's file access Solo la persona que está en el teclado puede permitir el acceso a archivos de un script +@msg A script is given at most 2,048 files: the files picked after them were left out Un script recibe como máximo 2.048 archivos: los archivos elegidos después de ellos se omitieron @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} @msg Couldn't open {name}: {e} No se pudo abrir {name}: {e} diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index bb74188ed8..029229411c 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -4435,6 +4435,13 @@ imageTrace Outline Ääriviiva Show External Script Warning Näytä ulkoisten komentosarjojen varoitus A Script Is Running Komentosarja on käynnissä Script Alert Komentosarjan ilmoitus + Script File Access Komentosarjan tiedostojen käyttö + The script asks to read a file you choose. Komentosarja pyytää lupaa lukea valitsemasi tiedoston. + The script asks to read and write a file you choose. Komentosarja pyytää lupaa lukea ja kirjoittaa valitsemasi tiedoston. + The script asks to read and write a folder you choose, with everything in it. Komentosarja pyytää lupaa lukea ja kirjoittaa valitsemasi kansion ja kaiken sen sisällön. + Allow Once Salli kerran + Always Allow This Script Salli tämä komentosarja aina + Deny Estä A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Komentosarja voi muuttaa avoimia asiakirjoja ja kirjoittaa tiedostoja suorittamillaan komennoilla. Suorita vain komentosarjoja, joihin luotat. Do not show this warning again Älä näytä tätä varoitusta uudelleen Stop the script and undo what it did? Then quit again. Pysäytetäänkö komentosarja ja kumotaan sen muutokset? Lopeta sitten uudelleen. @@ -4463,8 +4470,6 @@ imageTrace Outline Ääriviiva @msg Script file could not be read Komentosarjatiedostoa ei voitu lukea @msg Script folder has more than 2,048 entries Komentosarjakansiossa on yli 2 048 kohdetta @msg Script file open mode must be r, w, e or a Komentosarjatiedoston avaustilan on oltava r, w, e tai a -@msg Script file writing is not available Komentosarjatiedostojen kirjoittaminen ei ole käytettävissä -@msg Script file dialogs are not available Komentosarjojen tiedostovalintaikkunat eivät ole käytettävissä @msg Script files cannot be opened in another application Komentosarjatiedostoja ei voi avata toisessa sovelluksessa @msg Script file access is unavailable on the web Komentosarjatiedostojen käyttö ei ole mahdollista verkossa @msg Script has 256 files open Komentosarjalla on 256 tiedostoa auki @@ -4535,6 +4540,27 @@ imageTrace Outline Ääriviiva @msg there is no script engine named {name} skriptimoottoria nimeltä {name} ei ole @msg Running a script Suoritetaan komentosarjaa @msg Copied the script report Komentosarjan raportti kopioitiin +@msg Script file access denied: {path} Komentosarjan tiedostojen käyttö estettiin: {path} +@msg Script file access to the app's own folders is not allowed Komentosarjat eivät saa käyttää sovelluksen omia kansioita +@msg Script file cannot encode the text Komentosarjan tiedosto ei voi koodata tekstiä +@msg Script file could not be written Komentosarjan tiedostoa ei voitu kirjoittaa +@msg Script file dialogs need a person to answer them Komentosarjan tiedostovalintaikkunoihin tarvitaan vastaava henkilö +@msg Script file is not open for writing Komentosarjan tiedosto ei ole auki kirjoittamista varten +@msg Script file name is already in use Komentosarjan tiedoston nimi on jo käytössä +@msg Script file name must be a name without a folder Komentosarjan tiedoston nimen on oltava nimi ilman kansiota +@msg Script file permission can be kept only for a script run from a file Tiedostolupa voidaan säilyttää vain tiedostosta suoritetulle komentosarjalle +@msg Script file permission could not be saved Komentosarjan tiedostolupaa ei voitu tallentaa +@msg Script folder is not empty Komentosarjan kansio ei ole tyhjä +@msg Script files cannot make aliases Komentosarjan tiedostot eivät voi luoda aliaksia +@msg Script file hidden setting cannot be changed Komentosarjan tiedoston piilotusasetusta ei voi muuttaa +@msg {name}: a file dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: tiedostovalintaikkunaa ei voi avata sisäänrakennetun funktion, getterin, muunnoksen tai $.evalFile-funktion suorittaman tiedoston takaisinkutsussa; kutsu sitä komentosarjan omasta koodista +@msg the script wrote more file data than one run may write (32 MiB) komentosarja kirjoitti enemmän tiedostodataa kuin yksi suoritus saa kirjoittaa (32 MiB) +@msg `answer` for a script's file dialog must be one of: once, always, deny, stop komentosarjan tiedostovalintaikkunan `answer`-arvon on oltava jokin seuraavista: once, always, deny, stop +@msg choose a file or folder first, or deny valitse ensin tiedosto tai kansio tai estä +@msg the script file permissions could not be saved: {e} komentosarjojen tiedostolupia ei voitu tallentaa: {e} +@msg this script's file access can be allowed only once tämän komentosarjan tiedostojen käytön voi sallia vain kerran +@msg Only the person at the keyboard can allow a script's file access Vain näppäimistön ääressä oleva ihminen voi sallia komentosarjan tiedostojen käytön +@msg A script is given at most 2,048 files: the files picked after them were left out Komentosarja saa enintään 2 048 tiedostoa: niiden jälkeen valitut tiedostot jätettiin pois @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} @msg Couldn't open {name}: {e} Tiedostoa {name} ei voitu avata: {e} diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 09c9c35b0d..d942ad6638 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -4200,6 +4200,13 @@ axis Both Les deux Show External Script Warning Afficher l’avertissement des scripts externes A Script Is Running Un script est en cours d’exécution Script Alert Alerte de script + Script File Access Accès du script aux fichiers + The script asks to read a file you choose. Le script demande à lire un fichier que vous choisissez. + The script asks to read and write a file you choose. Le script demande à lire et écrire un fichier que vous choisissez. + The script asks to read and write a folder you choose, with everything in it. Le script demande à lire et écrire un dossier que vous choisissez, avec tout son contenu. + Allow Once Autoriser une fois + Always Allow This Script Toujours autoriser ce script + Deny Refuser A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Un script peut modifier les documents ouverts et écrire des fichiers au moyen des commandes qu’il exécute. N’exécutez que des scripts de confiance. Do not show this warning again Ne plus afficher cet avertissement 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. @@ -4228,8 +4235,6 @@ axis Both Les deux @msg Script file could not be read Le fichier de script n’a pas pu être lu @msg Script folder has more than 2,048 entries Le dossier de script contient plus de 2 048 entrées @msg Script file open mode must be r, w, e or a Le mode d’ouverture du fichier de script doit être r, w, e ou a -@msg Script file writing is not available L’écriture de fichiers de script n’est pas disponible -@msg Script file dialogs are not available Les boîtes de dialogue de fichiers de script ne sont pas disponibles @msg Script files cannot be opened in another application Les fichiers de script ne peuvent pas être ouverts dans une autre application @msg Script file access is unavailable on the web L’accès aux fichiers de script n’est pas disponible sur le web @msg Script has 256 files open Le script a 256 fichiers ouverts @@ -4300,6 +4305,27 @@ axis Both Les deux @msg there is no script engine named {name} il n'y a aucun moteur de script nommé {name} @msg Running a script Exécution d’un script @msg Copied the script report Rapport du script copié +@msg Script file access denied: {path} Accès du script aux fichiers refusé : {path} +@msg Script file access to the app's own folders is not allowed L’accès du script aux dossiers propres à l’application n’est pas autorisé +@msg Script file cannot encode the text Le fichier du script ne peut pas encoder le texte +@msg Script file could not be written Le fichier du script n’a pas pu être écrit +@msg Script file dialogs need a person to answer them Les boîtes de dialogue de fichiers du script ont besoin d’une personne pour y répondre +@msg Script file is not open for writing Le fichier du script n’est pas ouvert en écriture +@msg Script file name is already in use Le nom du fichier du script est déjà utilisé +@msg Script file name must be a name without a folder Le nom du fichier du script doit être un nom sans dossier +@msg Script file permission can be kept only for a script run from a file L’autorisation d’accès aux fichiers ne peut être conservée que pour un script exécuté depuis un fichier +@msg Script file permission could not be saved L’autorisation d’accès aux fichiers du script n’a pas pu être enregistrée +@msg Script folder is not empty Le dossier du script n’est pas vide +@msg Script files cannot make aliases Les fichiers du script ne peuvent pas créer d’alias +@msg Script file hidden setting cannot be changed Le réglage masqué du fichier du script ne peut pas être modifié +@msg {name}: a file dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name} : une boîte de dialogue de fichiers ne peut pas s’ouvrir dans un rappel d’une fonction intégrée, d’un accesseur, d’une conversion ou d’un fichier exécuté par $.evalFile ; appelez-la depuis le propre code du script +@msg the script wrote more file data than one run may write (32 MiB) le script a écrit plus de données de fichiers qu’une exécution ne peut en écrire (32 Mio) +@msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` pour la boîte de dialogue de fichiers d’un script doit être l’une des valeurs : once, always, deny, stop +@msg choose a file or folder first, or deny choisissez d’abord un fichier ou un dossier, ou refusez +@msg the script file permissions could not be saved: {e} les autorisations d’accès aux fichiers des scripts n’ont pas pu être enregistrées : {e} +@msg this script's file access can be allowed only once l’accès aux fichiers de ce script ne peut être autorisé qu’une fois +@msg Only the person at the keyboard can allow a script's file access Seule la personne au clavier peut autoriser l’accès aux fichiers d’un script +@msg A script is given at most 2,048 files: the files picked after them were left out Un script reçoit au plus 2 048 fichiers : les fichiers choisis après eux ont été laissés de côté @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} @msg Couldn't open {name}: {e} Impossible d’ouvrir {name} : {e} diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 9aa4bd7b99..43be9c9051 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -6494,6 +6494,13 @@ antiAlias Sharp शार्प Show External Script Warning बाहरी स्क्रिप्ट की चेतावनी दिखाएँ A Script Is Running एक स्क्रिप्ट चल रही है Script Alert स्क्रिप्ट सूचना + Script File Access स्क्रिप्ट की फ़ाइल पहुँच + The script asks to read a file you choose. स्क्रिप्ट आपकी चुनी हुई फ़ाइल पढ़ने की अनुमति माँगती है। + The script asks to read and write a file you choose. स्क्रिप्ट आपकी चुनी हुई फ़ाइल पढ़ने और लिखने की अनुमति माँगती है। + The script asks to read and write a folder you choose, with everything in it. स्क्रिप्ट आपका चुना हुआ फ़ोल्डर और उसकी सारी सामग्री पढ़ने और लिखने की अनुमति माँगती है। + Allow Once एक बार अनुमति दें + Always Allow This Script इस स्क्रिप्ट को हमेशा अनुमति दें + Deny अस्वीकार करें A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. स्क्रिप्ट खुले दस्तावेज़ बदल सकती है और अपने चलाए कमांड से फ़ाइलें लिख सकती है। केवल भरोसेमंद स्क्रिप्ट चलाएँ। Do not show this warning again यह चेतावनी फिर न दिखाएँ Stop the script and undo what it did? Then quit again. स्क्रिप्ट रोककर उसके बदलाव पूर्ववत करें? फिर दोबारा बाहर निकलें। @@ -6522,8 +6529,6 @@ antiAlias Sharp शार्प @msg Script file could not be read स्क्रिप्ट फ़ाइल पढ़ी नहीं जा सकी @msg Script folder has more than 2,048 entries स्क्रिप्ट फ़ोल्डर में 2,048 से अधिक प्रविष्टियाँ हैं @msg Script file open mode must be r, w, e or a स्क्रिप्ट फ़ाइल खोलने का मोड r, w, e या a होना चाहिए -@msg Script file writing is not available स्क्रिप्ट फ़ाइल लिखना उपलब्ध नहीं है -@msg Script file dialogs are not available स्क्रिप्ट फ़ाइल संवाद उपलब्ध नहीं हैं @msg Script files cannot be opened in another application स्क्रिप्ट फ़ाइलें किसी अन्य ऐप्लिकेशन में नहीं खोली जा सकतीं @msg Script file access is unavailable on the web वेब पर स्क्रिप्ट फ़ाइल पहुँच उपलब्ध नहीं है @msg Script has 256 files open स्क्रिप्ट ने 256 फ़ाइलें खोल रखी हैं @@ -6594,6 +6599,27 @@ antiAlias Sharp शार्प @msg there is no script engine named {name} {name} नाम का कोई स्क्रिप्ट इंजन नहीं है @msg Running a script स्क्रिप्ट चल रही है @msg Copied the script report Copied स्क्रिप्ट रिपोर्ट +@msg Script file access denied: {path} स्क्रिप्ट की फ़ाइल पहुँच अस्वीकार की गई: {path} +@msg Script file access to the app's own folders is not allowed स्क्रिप्ट को ऐप के अपने फ़ोल्डरों तक पहुँचने की अनुमति नहीं है +@msg Script file cannot encode the text स्क्रिप्ट फ़ाइल टेक्स्ट को एन्कोड नहीं कर सकती +@msg Script file could not be written स्क्रिप्ट फ़ाइल लिखी नहीं जा सकी +@msg Script file dialogs need a person to answer them स्क्रिप्ट के फ़ाइल डायलॉग को उत्तर देने के लिए किसी व्यक्ति की ज़रूरत है +@msg Script file is not open for writing स्क्रिप्ट फ़ाइल लिखने के लिए खुली नहीं है +@msg Script file name is already in use स्क्रिप्ट फ़ाइल का नाम पहले से उपयोग में है +@msg Script file name must be a name without a folder स्क्रिप्ट फ़ाइल का नाम बिना फ़ोल्डर वाला नाम होना चाहिए +@msg Script file permission can be kept only for a script run from a file फ़ाइल अनुमति केवल फ़ाइल से चलाई गई स्क्रिप्ट के लिए रखी जा सकती है +@msg Script file permission could not be saved स्क्रिप्ट की फ़ाइल अनुमति सहेजी नहीं जा सकी +@msg Script folder is not empty स्क्रिप्ट फ़ोल्डर खाली नहीं है +@msg Script files cannot make aliases स्क्रिप्ट फ़ाइलें उपनाम नहीं बना सकतीं +@msg Script file hidden setting cannot be changed स्क्रिप्ट फ़ाइल की छिपी सेटिंग बदली नहीं जा सकती +@msg {name}: a file dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: फ़ाइल डायलॉग किसी बिल्ट-इन फ़ंक्शन, getter, रूपांतरण या $.evalFile द्वारा चलाई गई फ़ाइल के callback के भीतर नहीं खुल सकता; इसे स्क्रिप्ट के अपने कोड से कॉल करें +@msg the script wrote more file data than one run may write (32 MiB) स्क्रिप्ट ने एक रन में लिखे जा सकने वाले फ़ाइल डेटा से अधिक लिखा (32 MiB) +@msg `answer` for a script's file dialog must be one of: once, always, deny, stop स्क्रिप्ट के फ़ाइल डायलॉग के लिए `answer` इनमें से एक होना चाहिए: once, always, deny, stop +@msg choose a file or folder first, or deny पहले कोई फ़ाइल या फ़ोल्डर चुनें, या अस्वीकार करें +@msg the script file permissions could not be saved: {e} स्क्रिप्ट की फ़ाइल अनुमतियाँ सहेजी नहीं जा सकीं: {e} +@msg this script's file access can be allowed only once इस स्क्रिप्ट की फ़ाइल पहुँच केवल एक बार दी जा सकती है +@msg Only the person at the keyboard can allow a script's file access किसी स्क्रिप्ट को फ़ाइल पहुँच केवल कीबोर्ड पर मौजूद व्यक्ति दे सकता है +@msg A script is given at most 2,048 files: the files picked after them were left out किसी स्क्रिप्ट को अधिकतम 2,048 फ़ाइलें दी जाती हैं: उनके बाद चुनी गई फ़ाइलें छोड़ दी गईं @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: प्रतिलिपि केवल इमेज को लेती है: डॉक्यूमेंट्स को फिर से लिंक करें जहां उनकी फ़ाइलें हैं @msg copying a file isn't available on the web एक फ़ाइल की प्रतिलिपि वेब पर उपलब्ध नहीं है diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index af6f586880..b3c0827878 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -5015,6 +5015,13 @@ imageTrace Outline Körvonal Show External Script Warning Figyelmeztetés külső parancsfájlok előtt A Script Is Running Egy parancsfájl fut Script Alert Parancsfájl-értesítés + Script File Access Parancsfájl fájlhozzáférése + The script asks to read a file you choose. A parancsfájl egy Ön által választott fájl olvasását kéri. + The script asks to read and write a file you choose. A parancsfájl egy Ön által választott fájl olvasását és írását kéri. + The script asks to read and write a folder you choose, with everything in it. A parancsfájl egy Ön által választott mappa és teljes tartalma olvasását és írását kéri. + Allow Once Engedélyezés egyszer + Always Allow This Script A parancsfájl engedélyezése mindig + Deny Elutasítás A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. A parancsfájl módosíthatja a megnyitott dokumentumokat, és a futtatott parancsokkal fájlokat írhat. Csak megbízható parancsfájlokat futtasson. Do not show this warning again Ne jelenjen meg többé ez a figyelmeztetés 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. @@ -5043,8 +5050,6 @@ imageTrace Outline Körvonal @msg Script file could not be read A parancsfájlt nem sikerült beolvasni @msg Script folder has more than 2,048 entries A parancsfájlmappában 2048-nál több bejegyzés van @msg Script file open mode must be r, w, e or a A parancsfájl megnyitási módja r, w, e vagy a lehet -@msg Script file writing is not available A parancsfájlok írása nem érhető el -@msg Script file dialogs are not available A parancsfájlok fájlpárbeszédpanelei nem érhetők el @msg Script files cannot be opened in another application A parancsfájlok nem nyithatók meg másik alkalmazásban @msg Script file access is unavailable on the web A parancsfájlok elérése a weben nem érhető el @msg Script has 256 files open A parancsfájlnak 256 megnyitott fájlja van @@ -5115,6 +5120,27 @@ imageTrace Outline Körvonal @msg there is no script engine named {name} nincs {name} nevű parancsfájlmotor @msg Running a script Parancsfájl futtatása @msg Copied the script report Szkriptjelentés másolva +@msg Script file access denied: {path} A parancsfájl fájlhozzáférése megtagadva: {path} +@msg Script file access to the app's own folders is not allowed A parancsfájlok nem férhetnek hozzá az alkalmazás saját mappáihoz +@msg Script file cannot encode the text A parancsfájl fájlja nem tudja kódolni a szöveget +@msg Script file could not be written A parancsfájl fájlját nem sikerült írni +@msg Script file dialogs need a person to answer them A parancsfájl fájlpárbeszédpaneleire egy személynek kell válaszolnia +@msg Script file is not open for writing A parancsfájl fájlja nincs írásra megnyitva +@msg Script file name is already in use A parancsfájl fájljának neve már használatban van +@msg Script file name must be a name without a folder A parancsfájl fájljának neve mappa nélküli név kell legyen +@msg Script file permission can be kept only for a script run from a file A fájlengedély csak fájlból futtatott parancsfájlnál tartható meg +@msg Script file permission could not be saved A parancsfájl fájlengedélyét nem sikerült menteni +@msg Script folder is not empty A parancsfájl mappája nem üres +@msg Script files cannot make aliases A parancsfájl fájljai nem hozhatnak létre álneveket +@msg Script file hidden setting cannot be changed A parancsfájl fájljának rejtett beállítása nem módosítható +@msg {name}: a file dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: fájlpárbeszédpanel nem nyílhat meg beépített függvény, getter, átalakítás vagy a $.evalFile által futtatott fájl visszahívásán belül; hívja meg a parancsfájl saját kódjából +@msg the script wrote more file data than one run may write (32 MiB) a parancsfájl több fájladatot írt, mint amennyit egy futás írhat (32 MiB) +@msg `answer` for a script's file dialog must be one of: once, always, deny, stop a parancsfájl fájlpárbeszédpaneléhez tartozó `answer` értéke a következők egyike kell legyen: once, always, deny, stop +@msg choose a file or folder first, or deny először válasszon fájlt vagy mappát, vagy utasítsa el +@msg the script file permissions could not be saved: {e} a parancsfájlok fájlengedélyeit nem sikerült menteni: {e} +@msg this script's file access can be allowed only once ennek a parancsfájlnak a fájlhozzáférése csak egyszer engedélyezhető +@msg Only the person at the keyboard can allow a script's file access Parancsfájl fájlhozzáférését csak a billentyűzetnél ülő személy engedélyezheti +@msg A script is given at most 2,048 files: the files picked after them were left out Egy parancsfájl legfeljebb 2 048 fájlt kap: az ezek után kiválasztott fájlok kimaradtak @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} @msg Couldn't copy to the system clipboard: {e} Nem sikerült a rendszer vágólapjára másolni: {e} diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index e0ba31ecd5..b9b0d3e474 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -4213,6 +4213,13 @@ imageTrace Outline Kontur Show External Script Warning Tampilkan Peringatan Skrip Eksternal A Script Is Running Skrip Sedang Berjalan Script Alert Peringatan Skrip + Script File Access Akses Berkas Skrip + The script asks to read a file you choose. Skrip meminta izin untuk membaca berkas yang Anda pilih. + The script asks to read and write a file you choose. Skrip meminta izin untuk membaca dan menulis berkas yang Anda pilih. + The script asks to read and write a folder you choose, with everything in it. Skrip meminta izin untuk membaca dan menulis folder yang Anda pilih, beserta seluruh isinya. + Allow Once Izinkan Sekali + Always Allow This Script Selalu Izinkan Skrip Ini + Deny Tolak A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Skrip dapat mengubah dokumen yang terbuka dan menulis file melalui perintah yang dijalankannya. Jalankan hanya skrip yang Anda percayai. Do not show this warning again Jangan tampilkan peringatan ini lagi Stop the script and undo what it did? Then quit again. Hentikan skrip dan batalkan yang telah dilakukannya? Lalu keluar lagi. diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index ce0bc58ce5..0958a77ece 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -4262,6 +4262,13 @@ axis Both Entrambi Show External Script Warning Mostra avviso per gli script esterni A Script Is Running È in esecuzione uno script Script Alert Avviso dello script + Script File Access Accesso dello script ai file + The script asks to read a file you choose. Lo script chiede di leggere un file che scegli. + The script asks to read and write a file you choose. Lo script chiede di leggere e scrivere un file che scegli. + The script asks to read and write a folder you choose, with everything in it. Lo script chiede di leggere e scrivere una cartella che scegli, con tutto il suo contenuto. + Allow Once Consenti una volta + Always Allow This Script Consenti sempre questo script + Deny Nega A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Uno script può modificare i documenti aperti e scrivere file tramite i comandi che esegue. Esegui solo script di cui ti fidi. Do not show this warning again Non mostrare più questo avviso Stop the script and undo what it did? Then quit again. Interrompere lo script e annullare ciò che ha fatto? Poi esci di nuovo. @@ -4290,8 +4297,6 @@ axis Both Entrambi @msg Script file could not be read Impossibile leggere il file di script @msg Script folder has more than 2,048 entries La cartella di script contiene più di 2.048 voci @msg Script file open mode must be r, w, e or a La modalità di apertura del file di script deve essere r, w, e oppure a -@msg Script file writing is not available La scrittura dei file di script non è disponibile -@msg Script file dialogs are not available Le finestre di dialogo dei file di script non sono disponibili @msg Script files cannot be opened in another application I file di script non possono essere aperti in un'altra applicazione @msg Script file access is unavailable on the web L'accesso ai file di script non è disponibile sul web @msg Script has 256 files open Lo script ha 256 file aperti @@ -4362,6 +4367,27 @@ axis Both Entrambi @msg there is no script engine named {name} non esiste un motore di script chiamato {name} @msg Running a script Esecuzione di uno script @msg Copied the script report Rapporto dello script copiato +@msg Script file access denied: {path} Accesso dello script ai file negato: {path} +@msg Script file access to the app's own folders is not allowed L'accesso dello script alle cartelle dell'app non è consentito +@msg Script file cannot encode the text Il file dello script non può codificare il testo +@msg Script file could not be written Impossibile scrivere il file dello script +@msg Script file dialogs need a person to answer them Le finestre di dialogo dei file dello script richiedono una persona che risponda +@msg Script file is not open for writing Il file dello script non è aperto in scrittura +@msg Script file name is already in use Il nome del file dello script è già in uso +@msg Script file name must be a name without a folder Il nome del file dello script deve essere un nome senza cartella +@msg Script file permission can be kept only for a script run from a file Il permesso sui file può essere mantenuto solo per uno script eseguito da un file +@msg Script file permission could not be saved Impossibile salvare il permesso sui file dello script +@msg Script folder is not empty La cartella dello script non è vuota +@msg Script files cannot make aliases I file dello script non possono creare alias +@msg Script file hidden setting cannot be changed L'impostazione nascosto del file dello script non può essere modificata +@msg {name}: a file dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: una finestra di dialogo dei file non può aprirsi in un callback di una funzione integrata, di un getter, di una conversione o di un file eseguito da $.evalFile; chiamala dal codice dello script stesso +@msg the script wrote more file data than one run may write (32 MiB) lo script ha scritto più dati di file di quanti ne possa scrivere un'esecuzione (32 MiB) +@msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` per la finestra di dialogo dei file di uno script deve essere uno tra: once, always, deny, stop +@msg choose a file or folder first, or deny scegli prima un file o una cartella, oppure nega +@msg the script file permissions could not be saved: {e} impossibile salvare i permessi sui file degli script: {e} +@msg this script's file access can be allowed only once l'accesso ai file di questo script può essere consentito solo una volta +@msg Only the person at the keyboard can allow a script's file access Solo la persona alla tastiera può consentire l’accesso ai file di uno script +@msg A script is given at most 2,048 files: the files picked after them were left out Uno script riceve al massimo 2.048 file: i file scelti dopo questi sono stati esclusi @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} @msg Couldn't open {name}: {e} Impossibile aprire {name}: {e} diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 1ecce4618a..c42b5453fb 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -5016,6 +5016,13 @@ swatch Bright Violet ビビッドバイオレット Show External Script Warning 外部スクリプトの警告を表示 A Script Is Running スクリプトの実行中 Script Alert スクリプトの通知 + Script File Access スクリプトのファイルアクセス + The script asks to read a file you choose. スクリプトが、選択したファイルの読み取りを求めています。 + The script asks to read and write a file you choose. スクリプトが、選択したファイルの読み書きを求めています。 + The script asks to read and write a folder you choose, with everything in it. スクリプトが、選択したフォルダーとその中身すべての読み書きを求めています。 + Allow Once 今回のみ許可 + Always Allow This Script このスクリプトを常に許可 + Deny 拒否 A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. スクリプトは開いているドキュメントを変更でき、実行するコマンドを通じてファイルを書き込むこともできます。信頼できるスクリプトだけを実行してください。 Do not show this warning again 今後この警告を表示しない Stop the script and undo what it did? Then quit again. スクリプトを停止して変更を取り消しますか?その後、もう一度終了してください。 @@ -5044,8 +5051,6 @@ swatch Bright Violet ビビッドバイオレット @msg Script file could not be read スクリプトファイルを読み込めませんでした @msg Script folder has more than 2,048 entries スクリプトフォルダーの項目が 2,048 を超えています @msg Script file open mode must be r, w, e or a スクリプトファイルを開くモードは r、w、e、a のいずれかにしてください -@msg Script file writing is not available スクリプトファイルの書き込みは利用できません -@msg Script file dialogs are not available スクリプトファイルのダイアログは利用できません @msg Script files cannot be opened in another application スクリプトファイルを別のアプリケーションで開くことはできません @msg Script file access is unavailable on the web Web ではスクリプトファイルにアクセスできません @msg Script has 256 files open スクリプトが 256 個のファイルを開いています @@ -5116,6 +5121,27 @@ swatch Bright Violet ビビッドバイオレット @msg there is no script engine named {name} {name} という名前のスクリプトエンジンはありません @msg Running a script スクリプトを実行中 @msg Copied the script report スクリプトのレポートをコピーしました +@msg Script file access denied: {path} スクリプトのファイルアクセスが拒否されました: {path} +@msg Script file access to the app's own folders is not allowed スクリプトからアプリ自身のフォルダーへのアクセスは許可されていません +@msg Script file cannot encode the text スクリプトのファイルでテキストをエンコードできません +@msg Script file could not be written スクリプトのファイルを書き込めませんでした +@msg Script file dialogs need a person to answer them スクリプトのファイルダイアログには応答する人が必要です +@msg Script file is not open for writing スクリプトのファイルが書き込み用に開かれていません +@msg Script file name is already in use スクリプトのファイル名はすでに使用されています +@msg Script file name must be a name without a folder スクリプトのファイル名はフォルダーを含まない名前にしてください +@msg Script file permission can be kept only for a script run from a file ファイルの許可を保持できるのは、ファイルから実行したスクリプトだけです +@msg Script file permission could not be saved スクリプトのファイルの許可を保存できませんでした +@msg Script folder is not empty スクリプトのフォルダーが空ではありません +@msg Script files cannot make aliases スクリプトのファイルではエイリアスを作成できません +@msg Script file hidden setting cannot be changed スクリプトのファイルの非表示設定は変更できません +@msg {name}: a file dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: 組み込み関数、ゲッター、変換、または $.evalFile が実行するファイルのコールバック内ではファイルダイアログを開けません。スクリプト自身のコードから呼び出してください +@msg the script wrote more file data than one run may write (32 MiB) スクリプトが 1 回の実行で書き込める量を超えるファイルデータを書き込みました (32 MiB) +@msg `answer` for a script's file dialog must be one of: once, always, deny, stop スクリプトのファイルダイアログの `answer` は once、always、deny、stop のいずれかにしてください +@msg choose a file or folder first, or deny 先にファイルまたはフォルダーを選択するか、拒否してください +@msg the script file permissions could not be saved: {e} スクリプトのファイル許可を保存できませんでした: {e} +@msg this script's file access can be allowed only once このスクリプトのファイルアクセスは 1 回だけ許可できます +@msg Only the person at the keyboard can allow a script's file access スクリプトのファイルアクセスを許可できるのはキーボードの前にいる人だけです +@msg A script is given at most 2,048 files: the files picked after them were left out スクリプトに渡せるファイルは 2,048 個までのため、それ以降に選んだファイルは除外されました @msg Exported {path} {path} を書き出しました @msg no CSS to copy: select objects with CSS of their own コピーする CSS がありません: 独自の CSS を持つオブジェクトを選択してください @msg unknown highlight `{h}` `{h}` は不明なハイライトの指定です diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 3d6425c373..f9a20f812c 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -5415,6 +5415,13 @@ imageTrace Outline კონტური Show External Script Warning გარე სკრიპტის გაფრთხილების ჩვენება A Script Is Running სკრიპტი მუშაობს Script Alert სკრიპტის შეტყობინება + Script File Access სკრიპტის წვდომა ფაილებზე + The script asks to read a file you choose. სკრიპტი ითხოვს თქვენ მიერ არჩეული ფაილის წაკითხვას. + The script asks to read and write a file you choose. სკრიპტი ითხოვს თქვენ მიერ არჩეული ფაილის წაკითხვასა და ჩაწერას. + The script asks to read and write a folder you choose, with everything in it. სკრიპტი ითხოვს თქვენ მიერ არჩეული საქაღალდისა და მთელი მისი შიგთავსის წაკითხვასა და ჩაწერას. + Allow Once ერთხელ დაშვება + Always Allow This Script ამ სკრიპტის ყოველთვის დაშვება + Deny უარყოფა A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. სკრიპტს შეუძლია ღია დოკუმენტების შეცვლა და მის მიერ გაშვებული ბრძანებებით ფაილების ჩაწერა. გაუშვით მხოლოდ სანდო სკრიპტები. Do not show this warning again აღარ აჩვენო ეს გაფრთხილება Stop the script and undo what it did? Then quit again. შეჩერდეს სკრიპტი და გაუქმდეს მისი ცვლილებები? შემდეგ ხელახლა გამოდით. @@ -5443,8 +5450,6 @@ imageTrace Outline კონტური @msg Script file could not be read სკრიპტის ფაილის წაკითხვა ვერ მოხერხდა @msg Script folder has more than 2,048 entries სკრიპტის საქაღალდეში 2048-ზე მეტი ჩანაწერია @msg Script file open mode must be r, w, e or a სკრიპტის ფაილის გახსნის რეჟიმი უნდა იყოს r, w, e ან a -@msg Script file writing is not available სკრიპტის ფაილების ჩაწერა მიუწვდომელია -@msg Script file dialogs are not available სკრიპტის ფაილის დიალოგები მიუწვდომელია @msg Script files cannot be opened in another application სკრიპტის ფაილების სხვა აპლიკაციაში გახსნა შეუძლებელია @msg Script file access is unavailable on the web ვებში სკრიპტის ფაილებზე წვდომა მიუწვდომელია @msg Script has 256 files open სკრიპტს 256 ფაილი აქვს გახსნილი @@ -5515,6 +5520,27 @@ imageTrace Outline კონტური @msg there is no script engine named {name} სკრიპტის ძრავა სახელით {name} არ არსებობს @msg Running a script სკრიპტი მუშაობს @msg Copied the script report კოპირებულია სკრიპტის ანგარიში +@msg Script file access denied: {path} სკრიპტის წვდომა ფაილებზე უარყოფილია: {path} +@msg Script file access to the app's own folders is not allowed სკრიპტს არ აქვს აპის საკუთარ საქაღალდეებზე წვდომის უფლება +@msg Script file cannot encode the text სკრიპტის ფაილი ვერ აკოდირებს ტექსტს +@msg Script file could not be written სკრიპტის ფაილის ჩაწერა ვერ მოხერხდა +@msg Script file dialogs need a person to answer them სკრიპტის ფაილის დიალოგებს სჭირდება ადამიანი, რომელიც უპასუხებს +@msg Script file is not open for writing სკრიპტის ფაილი ჩასაწერად გახსნილი არ არის +@msg Script file name is already in use სკრიპტის ფაილის სახელი უკვე გამოიყენება +@msg Script file name must be a name without a folder სკრიპტის ფაილის სახელი უნდა იყოს სახელი საქაღალდის გარეშე +@msg Script file permission can be kept only for a script run from a file ფაილების ნებართვის შენახვა შესაძლებელია მხოლოდ ფაილიდან გაშვებული სკრიპტისთვის +@msg Script file permission could not be saved სკრიპტის ფაილების ნებართვის შენახვა ვერ მოხერხდა +@msg Script folder is not empty სკრიპტის საქაღალდე ცარიელი არ არის +@msg Script files cannot make aliases სკრიპტის ფაილებს არ შეუძლიათ ფსევდონიმების შექმნა +@msg Script file hidden setting cannot be changed სკრიპტის ფაილის დამალვის პარამეტრის შეცვლა შეუძლებელია +@msg {name}: a file dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: ფაილის დიალოგი ვერ გაიხსნება ჩაშენებული ფუნქციის, getter-ის, გარდაქმნის ან $.evalFile-ის მიერ გაშვებული ფაილის callback-ში; გამოიძახეთ ის სკრიპტის საკუთარი კოდიდან +@msg the script wrote more file data than one run may write (32 MiB) სკრიპტმა ჩაწერა იმაზე მეტი ფაილის მონაცემი, ვიდრე ერთ გაშვებას შეუძლია ჩაწეროს (32 MiB) +@msg `answer` for a script's file dialog must be one of: once, always, deny, stop სკრიპტის ფაილის დიალოგისთვის `answer` უნდა იყოს ერთ-ერთი: once, always, deny, stop +@msg choose a file or folder first, or deny ჯერ აირჩიეთ ფაილი ან საქაღალდე, ან უარყავით +@msg the script file permissions could not be saved: {e} სკრიპტების ფაილების ნებართვების შენახვა ვერ მოხერხდა: {e} +@msg this script's file access can be allowed only once ამ სკრიპტის წვდომა ფაილებზე მხოლოდ ერთხელ შეიძლება დაიშვას +@msg Only the person at the keyboard can allow a script's file access სკრიპტის წვდომას ფაილებზე მხოლოდ კლავიატურასთან მყოფი ადამიანი უშვებს +@msg A script is given at most 2,048 files: the files picked after them were left out სკრიპტი იღებს მაქსიმუმ 2 048 ფაილს: მათ შემდეგ არჩეული ფაილები გამოტოვებულია @msg Offset Path: the offset leaves nothing of the selected paths (an inset larger than the shapes) ტრაექტორიის წანაცვლება: წანაცვლების შემდეგ მონიშნული ტრაექტორიებიდან არაფერი რჩება (შიგნით წანაცვლება ფიგურებზე დიდია) @msg {path}: not a file {path}: ფაილი არ არის Load EPS into Clipboard EPS-ის ბუფერში ჩატვირთვა diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index fb87488d64..3d6d38ff44 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -4943,6 +4943,13 @@ theme Appearance 외관 Show External Script Warning 외부 스크립트 경고 표시 A Script Is Running 스크립트 실행 중 Script Alert 스크립트 알림 + Script File Access 스크립트 파일 접근 + The script asks to read a file you choose. 스크립트가 선택한 파일을 읽도록 요청합니다. + The script asks to read and write a file you choose. 스크립트가 선택한 파일을 읽고 쓰도록 요청합니다. + The script asks to read and write a folder you choose, with everything in it. 스크립트가 선택한 폴더와 그 안의 모든 항목을 읽고 쓰도록 요청합니다. + Allow Once 한 번 허용 + Always Allow This Script 이 스크립트 항상 허용 + Deny 거부 A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. 스크립트는 열려 있는 문서를 변경하고 실행하는 명령을 통해 파일을 쓸 수 있습니다. 신뢰할 수 있는 스크립트만 실행하세요. Do not show this warning again 이 경고를 다시 표시하지 않음 Stop the script and undo what it did? Then quit again. 스크립트를 중지하고 변경 내용을 취소할까요? 그런 다음 다시 종료하세요. @@ -4971,8 +4978,6 @@ theme Appearance 외관 @msg Script file could not be read 스크립트 파일을 읽을 수 없습니다 @msg Script folder has more than 2,048 entries 스크립트 폴더의 항목이 2,048개를 초과합니다 @msg Script file open mode must be r, w, e or a 스크립트 파일 열기 모드는 r, w, e 또는 a여야 합니다 -@msg Script file writing is not available 스크립트 파일 쓰기를 사용할 수 없습니다 -@msg Script file dialogs are not available 스크립트 파일 대화 상자를 사용할 수 없습니다 @msg Script files cannot be opened in another application 스크립트 파일을 다른 응용 프로그램에서 열 수 없습니다 @msg Script file access is unavailable on the web 웹에서는 스크립트 파일에 접근할 수 없습니다 @msg Script has 256 files open 스크립트가 파일 256개를 열고 있습니다 @@ -5043,6 +5048,27 @@ theme Appearance 외관 @msg there is no script engine named {name} 이름이 {name}인 스크립트 엔진이 없습니다 @msg Running a script 스크립트 실행 중 @msg Copied the script report 스크립트 보고서를 복사했습니다 +@msg Script file access denied: {path} 스크립트 파일 접근이 거부되었습니다: {path} +@msg Script file access to the app's own folders is not allowed 스크립트는 앱 자체 폴더에 접근할 수 없습니다 +@msg Script file cannot encode the text 스크립트 파일이 텍스트를 인코딩할 수 없습니다 +@msg Script file could not be written 스크립트 파일을 쓸 수 없습니다 +@msg Script file dialogs need a person to answer them 스크립트 파일 대화 상자에는 응답할 사람이 필요합니다 +@msg Script file is not open for writing 스크립트 파일이 쓰기용으로 열려 있지 않습니다 +@msg Script file name is already in use 스크립트 파일 이름이 이미 사용 중입니다 +@msg Script file name must be a name without a folder 스크립트 파일 이름은 폴더 없는 이름이어야 합니다 +@msg Script file permission can be kept only for a script run from a file 파일 권한은 파일에서 실행한 스크립트에만 유지할 수 있습니다 +@msg Script file permission could not be saved 스크립트 파일 권한을 저장할 수 없습니다 +@msg Script folder is not empty 스크립트 폴더가 비어 있지 않습니다 +@msg Script files cannot make aliases 스크립트 파일은 별칭을 만들 수 없습니다 +@msg Script file hidden setting cannot be changed 스크립트 파일의 숨김 설정을 변경할 수 없습니다 +@msg {name}: a file dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: 기본 제공 함수, getter, 변환 또는 $.evalFile이 실행하는 파일의 콜백 안에서는 파일 대화 상자를 열 수 없습니다. 스크립트 자체 코드에서 호출하세요 +@msg the script wrote more file data than one run may write (32 MiB) 스크립트가 한 번의 실행에서 쓸 수 있는 것보다 많은 파일 데이터를 썼습니다(32 MiB) +@msg `answer` for a script's file dialog must be one of: once, always, deny, stop 스크립트 파일 대화 상자의 `answer`는 once, always, deny, stop 중 하나여야 합니다 +@msg choose a file or folder first, or deny 먼저 파일이나 폴더를 선택하거나 거부하세요 +@msg the script file permissions could not be saved: {e} 스크립트 파일 권한을 저장할 수 없습니다: {e} +@msg this script's file access can be allowed only once 이 스크립트의 파일 접근은 한 번만 허용할 수 있습니다 +@msg Only the person at the keyboard can allow a script's file access 스크립트의 파일 접근은 키보드 앞에 있는 사람만 허용할 수 있습니다 +@msg A script is given at most 2,048 files: the files picked after them were left out 스크립트에는 파일이 최대 2,048개까지 전달됩니다: 그 뒤에 고른 파일은 제외되었습니다 @msg Exported {path} {path}을(를) 내보냈습니다 @msg no CSS to copy: select objects with CSS of their own 복사할 CSS가 없습니다: 자체 CSS가 있는 개체를 선택하세요 @msg unknown highlight `{h}` 알 수 없는 강조 `{h}` diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index b3388fa82a..6dea6dca40 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -4227,6 +4227,13 @@ imageTrace Outline Contour Show External Script Warning Waarschuwing voor externe scripts tonen A Script Is Running Er wordt een script uitgevoerd Script Alert Scriptmelding + Script File Access Bestandstoegang van script + The script asks to read a file you choose. Het script vraagt een bestand te lezen dat u kiest. + The script asks to read and write a file you choose. Het script vraagt een bestand te lezen en te schrijven dat u kiest. + The script asks to read and write a folder you choose, with everything in it. Het script vraagt een map die u kiest te lezen en te schrijven, met alles wat erin staat. + Allow Once Eenmaal toestaan + Always Allow This Script Dit script altijd toestaan + Deny Weigeren A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Een script kan de geopende documenten wijzigen en via de uitgevoerde opdrachten bestanden schrijven. Voer alleen scripts uit die u vertrouwt. Do not show this warning again Deze waarschuwing niet meer tonen Stop the script and undo what it did? Then quit again. Het script stoppen en de wijzigingen ervan ongedaan maken? Sluit daarna opnieuw af. diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 0729e35c79..d9fca7852c 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -4344,6 +4344,13 @@ imageTrace Outline Kontur Show External Script Warning Pokazuj ostrzeżenie o skryptach zewnętrznych A Script Is Running Skrypt jest uruchomiony Script Alert Komunikat skryptu + Script File Access Dostęp skryptu do plików + The script asks to read a file you choose. Skrypt prosi o odczyt wybranego przez Ciebie pliku. + The script asks to read and write a file you choose. Skrypt prosi o odczyt i zapis wybranego przez Ciebie pliku. + The script asks to read and write a folder you choose, with everything in it. Skrypt prosi o odczyt i zapis wybranego przez Ciebie folderu wraz z całą jego zawartością. + Allow Once Zezwól raz + Always Allow This Script Zawsze zezwalaj temu skryptowi + Deny Odmów A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Skrypt może zmieniać otwarte dokumenty i zapisywać pliki za pomocą wykonywanych poleceń. Uruchamiaj tylko skrypty, którym ufasz. Do not show this warning again Nie pokazuj więcej tego ostrzeżenia Stop the script and undo what it did? Then quit again. Zatrzymać skrypt i cofnąć jego zmiany? Następnie zakończ program ponownie. @@ -4372,8 +4379,6 @@ imageTrace Outline Kontur @msg Script file could not be read Nie udało się odczytać pliku skryptu @msg Script folder has more than 2,048 entries Folder skryptu ma więcej niż 2048 pozycji @msg Script file open mode must be r, w, e or a Tryb otwarcia pliku skryptu musi być r, w, e lub a -@msg Script file writing is not available Zapisywanie plików skryptu jest niedostępne -@msg Script file dialogs are not available Okna dialogowe plików skryptu są niedostępne @msg Script files cannot be opened in another application Plików skryptu nie można otworzyć w innej aplikacji @msg Script file access is unavailable on the web Dostęp do plików skryptu jest niedostępny w przeglądarce @msg Script has 256 files open Skrypt ma otwartych 256 plików @@ -4444,6 +4449,27 @@ imageTrace Outline Kontur @msg there is no script engine named {name} nie ma silnika skryptów o nazwie {name} @msg Running a script Uruchamianie skryptu @msg Copied the script report Skopiowano raport skryptu +@msg Script file access denied: {path} Odmówiono skryptowi dostępu do plików: {path} +@msg Script file access to the app's own folders is not allowed Skrypt nie ma dostępu do własnych folderów aplikacji +@msg Script file cannot encode the text Plik skryptu nie może zakodować tekstu +@msg Script file could not be written Nie można zapisać pliku skryptu +@msg Script file dialogs need a person to answer them Okna dialogowe plików skryptu wymagają osoby, która na nie odpowie +@msg Script file is not open for writing Plik skryptu nie jest otwarty do zapisu +@msg Script file name is already in use Nazwa pliku skryptu jest już używana +@msg Script file name must be a name without a folder Nazwa pliku skryptu musi być nazwą bez folderu +@msg Script file permission can be kept only for a script run from a file Uprawnienie do plików można zachować tylko dla skryptu uruchomionego z pliku +@msg Script file permission could not be saved Nie można zapisać uprawnienia skryptu do plików +@msg Script folder is not empty Folder skryptu nie jest pusty +@msg Script files cannot make aliases Pliki skryptu nie mogą tworzyć aliasów +@msg Script file hidden setting cannot be changed Nie można zmienić ustawienia ukrycia pliku skryptu +@msg {name}: a file dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: okna dialogowego plików nie można otworzyć w wywołaniu zwrotnym funkcji wbudowanej, gettera, konwersji ani pliku uruchamianego przez $.evalFile; wywołaj je z własnego kodu skryptu +@msg the script wrote more file data than one run may write (32 MiB) skrypt zapisał więcej danych plików, niż może zapisać jedno uruchomienie (32 MiB) +@msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` dla okna dialogowego plików skryptu musi być jedną z wartości: once, always, deny, stop +@msg choose a file or folder first, or deny najpierw wybierz plik lub folder albo odmów +@msg the script file permissions could not be saved: {e} nie można zapisać uprawnień skryptów do plików: {e} +@msg this script's file access can be allowed only once na dostęp tego skryptu do plików można zezwolić tylko raz +@msg Only the person at the keyboard can allow a script's file access Na dostęp skryptu do plików może zezwolić tylko osoba przy klawiaturze +@msg A script is given at most 2,048 files: the files picked after them were left out Skrypt otrzymuje najwyżej 2 048 plików: pliki wybrane po nich zostały pominięte @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} @msg Couldn't open {name}: {e} Nie udało się otworzyć {name}: {e} diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 36f778dbd5..030c073639 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -5225,6 +5225,13 @@ axis Both Ambos Show External Script Warning Mostrar aviso de scripts externos A Script Is Running Um script está em execução Script Alert Alerta do script + Script File Access Acesso do script a arquivos + The script asks to read a file you choose. O script pede para ler um arquivo que você escolher. + The script asks to read and write a file you choose. O script pede para ler e gravar um arquivo que você escolher. + The script asks to read and write a folder you choose, with everything in it. O script pede para ler e gravar uma pasta que você escolher, com todo o seu conteúdo. + Allow Once Permitir uma vez + Always Allow This Script Sempre permitir este script + Deny Negar A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Um script pode alterar os documentos abertos e gravar arquivos pelos comandos que executa. Execute apenas scripts em que você confia. Do not show this warning again Não mostrar este aviso novamente Stop the script and undo what it did? Then quit again. Parar o script e desfazer o que ele fez? Depois, saia novamente. @@ -5253,8 +5260,6 @@ axis Both Ambos @msg Script file could not be read Não foi possível ler o arquivo de script @msg Script folder has more than 2,048 entries A pasta de script tem mais de 2.048 entradas @msg Script file open mode must be r, w, e or a O modo de abertura do arquivo de script deve ser r, w, e ou a -@msg Script file writing is not available A gravação de arquivos de script não está disponível -@msg Script file dialogs are not available As caixas de diálogo de arquivos de script não estão disponíveis @msg Script files cannot be opened in another application Arquivos de script não podem ser abertos em outro aplicativo @msg Script file access is unavailable on the web O acesso a arquivos de script não está disponível na web @msg Script has 256 files open O script tem 256 arquivos abertos @@ -5325,6 +5330,27 @@ axis Both Ambos @msg there is no script engine named {name} não há nenhum mecanismo de script chamado {name} @msg Running a script Executando um script @msg Copied the script report Relatório do script copiado +@msg Script file access denied: {path} Acesso do script a arquivos negado: {path} +@msg Script file access to the app's own folders is not allowed O script não pode acessar as pastas do próprio aplicativo +@msg Script file cannot encode the text O arquivo do script não consegue codificar o texto +@msg Script file could not be written Não foi possível gravar o arquivo do script +@msg Script file dialogs need a person to answer them As caixas de diálogo de arquivo do script precisam de uma pessoa para respondê-las +@msg Script file is not open for writing O arquivo do script não está aberto para gravação +@msg Script file name is already in use O nome do arquivo do script já está em uso +@msg Script file name must be a name without a folder O nome do arquivo do script deve ser um nome sem pasta +@msg Script file permission can be kept only for a script run from a file A permissão de arquivos só pode ser mantida para um script executado a partir de um arquivo +@msg Script file permission could not be saved Não foi possível salvar a permissão de arquivos do script +@msg Script folder is not empty A pasta do script não está vazia +@msg Script files cannot make aliases Os arquivos do script não podem criar aliases +@msg Script file hidden setting cannot be changed A configuração de oculto do arquivo do script não pode ser alterada +@msg {name}: a file dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: uma caixa de diálogo de arquivo não pode abrir dentro de um callback de uma função integrada, de um getter, de uma conversão ou de um arquivo que $.evalFile executa; chame-a a partir do próprio código do script +@msg the script wrote more file data than one run may write (32 MiB) o script gravou mais dados de arquivo do que uma execução pode gravar (32 MiB) +@msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` para a caixa de diálogo de arquivo de um script deve ser um destes: once, always, deny, stop +@msg choose a file or folder first, or deny escolha primeiro um arquivo ou uma pasta, ou negue +@msg the script file permissions could not be saved: {e} não foi possível salvar as permissões de arquivos dos scripts: {e} +@msg this script's file access can be allowed only once o acesso a arquivos deste script só pode ser permitido uma vez +@msg Only the person at the keyboard can allow a script's file access Somente a pessoa ao teclado pode permitir o acesso a arquivos de um script +@msg A script is given at most 2,048 files: the files picked after them were left out Um script recebe no máximo 2.048 arquivos: os arquivos escolhidos depois deles foram deixados de fora @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}` @msg give corners of the path: anchors where its sides meet at an angle informe os cantos do caminho: pontos de ancoragem onde os lados se encontram em ângulo diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 442a9612d4..c18c366da1 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -4248,6 +4248,13 @@ axis Both Оба Show External Script Warning Показывать предупреждение о внешних скриптах A Script Is Running Выполняется скрипт Script Alert Сообщение скрипта + Script File Access Доступ скрипта к файлам + The script asks to read a file you choose. Скрипт запрашивает чтение выбранного вами файла. + The script asks to read and write a file you choose. Скрипт запрашивает чтение и запись выбранного вами файла. + The script asks to read and write a folder you choose, with everything in it. Скрипт запрашивает чтение и запись выбранной вами папки со всем её содержимым. + Allow Once Разрешить один раз + Always Allow This Script Всегда разрешать этот скрипт + Deny Запретить A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Скрипт может изменять открытые документы и записывать файлы с помощью выполняемых команд. Запускайте только те скрипты, которым доверяете. Do not show this warning again Больше не показывать это предупреждение Stop the script and undo what it did? Then quit again. Остановить скрипт и отменить его изменения? Затем выйдите ещё раз. @@ -4276,8 +4283,6 @@ axis Both Оба @msg Script file could not be read Не удалось прочитать файл скрипта @msg Script folder has more than 2,048 entries В папке скрипта больше 2048 элементов @msg Script file open mode must be r, w, e or a Режим открытия файла скрипта должен быть r, w, e или a -@msg Script file writing is not available Запись файлов скрипта недоступна -@msg Script file dialogs are not available Диалоговые окна файлов скрипта недоступны @msg Script files cannot be opened in another application Файлы скрипта нельзя открыть в другом приложении @msg Script file access is unavailable on the web Доступ к файлам скрипта в веб-версии недоступен @msg Script has 256 files open У скрипта открыто 256 файлов @@ -4348,6 +4353,27 @@ axis Both Оба @msg there is no script engine named {name} движка скриптов с именем {name} нет @msg Running a script Выполняется скрипт @msg Copied the script report Отчёт о сценарии скопирован +@msg Script file access denied: {path} Доступ скрипта к файлам запрещён: {path} +@msg Script file access to the app's own folders is not allowed Скрипту не разрешён доступ к собственным папкам приложения +@msg Script file cannot encode the text Файл скрипта не может закодировать текст +@msg Script file could not be written Не удалось записать файл скрипта +@msg Script file dialogs need a person to answer them Для ответа на файловые диалоги скрипта нужен человек +@msg Script file is not open for writing Файл скрипта не открыт для записи +@msg Script file name is already in use Имя файла скрипта уже используется +@msg Script file name must be a name without a folder Имя файла скрипта должно быть именем без папки +@msg Script file permission can be kept only for a script run from a file Разрешение на файлы можно сохранить только для скрипта, запущенного из файла +@msg Script file permission could not be saved Не удалось сохранить разрешение скрипта на файлы +@msg Script folder is not empty Папка скрипта не пуста +@msg Script files cannot make aliases Файлы скрипта не могут создавать псевдонимы +@msg Script file hidden setting cannot be changed Нельзя изменить параметр скрытости файла скрипта +@msg {name}: a file dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: файловый диалог нельзя открыть внутри обратного вызова встроенной функции, геттера, преобразования или файла, который выполняет $.evalFile; вызовите его из собственного кода скрипта +@msg the script wrote more file data than one run may write (32 MiB) скрипт записал больше данных файлов, чем может записать один запуск (32 MiB) +@msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` для файлового диалога скрипта должен быть одним из: once, always, deny, stop +@msg choose a file or folder first, or deny сначала выберите файл или папку либо откажите +@msg the script file permissions could not be saved: {e} не удалось сохранить разрешения скриптов на файлы: {e} +@msg this script's file access can be allowed only once доступ этого скрипта к файлам можно разрешить только один раз +@msg Only the person at the keyboard can allow a script's file access Разрешить скрипту доступ к файлам может только человек за клавиатурой +@msg A script is given at most 2,048 files: the files picked after them were left out Скрипт получает не больше 2 048 файлов: файлы, выбранные после них, пропущены @msg Corners edits the corners of a path «Углы» редактирует углы контура @msg Couldn't copy to the system clipboard: {e} Не удалось скопировать в системный буфер обмена: {e} @msg Couldn't open {name}: {e} Не удалось открыть {name}: {e} diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 8a8f8453b6..0331bdbd36 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -4121,6 +4121,13 @@ axis Both Båda Show External Script Warning Visa varning för externa skript A Script Is Running Ett skript körs Script Alert Skriptmeddelande + Script File Access Skriptets filåtkomst + The script asks to read a file you choose. Skriptet ber om att läsa en fil som du väljer. + The script asks to read and write a file you choose. Skriptet ber om att läsa och skriva en fil som du väljer. + The script asks to read and write a folder you choose, with everything in it. Skriptet ber om att läsa och skriva en mapp som du väljer, med allt innehåll. + Allow Once Tillåt en gång + Always Allow This Script Tillåt alltid det här skriptet + Deny Neka A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Ett skript kan ändra de öppna dokumenten och skriva filer genom de kommandon det kör. Kör bara skript du litar på. Do not show this warning again Visa inte den här varningen igen Stop the script and undo what it did? Then quit again. Stoppa skriptet och ångra det det gjort? Avsluta sedan igen. @@ -4149,8 +4156,6 @@ axis Both Båda @msg Script file could not be read Skriptfilen kunde inte läsas @msg Script folder has more than 2,048 entries Skriptmappen har fler än 2 048 poster @msg Script file open mode must be r, w, e or a Skriptfilens öppningsläge måste vara r, w, e eller a -@msg Script file writing is not available Skrivning av skriptfiler är inte tillgänglig -@msg Script file dialogs are not available Fildialogrutor för skript är inte tillgängliga @msg Script files cannot be opened in another application Skriptfiler kan inte öppnas i ett annat program @msg Script file access is unavailable on the web Åtkomst till skriptfiler är inte tillgänglig på webben @msg Script has 256 files open Skriptet har 256 filer öppna @@ -4221,6 +4226,27 @@ axis Both Båda @msg there is no script engine named {name} det finns ingen skriptmotor med namnet {name} @msg Running a script Kör ett skript @msg Copied the script report Kopierade skriptrapporten +@msg Script file access denied: {path} Skriptets filåtkomst nekades: {path} +@msg Script file access to the app's own folders is not allowed Skript får inte komma åt appens egna mappar +@msg Script file cannot encode the text Skriptets fil kan inte koda texten +@msg Script file could not be written Skriptets fil kunde inte skrivas +@msg Script file dialogs need a person to answer them Skriptets fildialoger behöver en person som svarar på dem +@msg Script file is not open for writing Skriptets fil är inte öppen för skrivning +@msg Script file name is already in use Namnet på skriptets fil används redan +@msg Script file name must be a name without a folder Namnet på skriptets fil måste vara ett namn utan mapp +@msg Script file permission can be kept only for a script run from a file Filbehörighet kan bara behållas för ett skript som körs från en fil +@msg Script file permission could not be saved Skriptets filbehörighet kunde inte sparas +@msg Script folder is not empty Skriptets mapp är inte tom +@msg Script files cannot make aliases Skriptets filer kan inte skapa alias +@msg Script file hidden setting cannot be changed Inställningen för dold för skriptets fil kan inte ändras +@msg {name}: a file dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: en fildialog kan inte öppnas i ett återanrop från en inbyggd funktion, en getter, en konvertering eller en fil som $.evalFile kör; anropa den från skriptets egen kod +@msg the script wrote more file data than one run may write (32 MiB) skriptet skrev mer fildata än en körning får skriva (32 MiB) +@msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` för ett skripts fildialog måste vara ett av: once, always, deny, stop +@msg choose a file or folder first, or deny välj först en fil eller mapp, eller neka +@msg the script file permissions could not be saved: {e} skriptens filbehörigheter kunde inte sparas: {e} +@msg this script's file access can be allowed only once det här skriptets filåtkomst kan bara tillåtas en gång +@msg Only the person at the keyboard can allow a script's file access Bara personen vid tangentbordet kan tillåta ett skripts filåtkomst +@msg A script is given at most 2,048 files: the files picked after them were left out Ett skript får högst 2 048 filer: filerna som valdes efter dem utelämnades @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} @msg Couldn't open {name}: {e} Kunde inte öppna {name}: {e} diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 66caa1c3a4..b1e61e080e 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -1739,6 +1739,68 @@ fn recolor_notes_on_objects_left_unchanged_translate_with_their_counts() { } } +/// The errors a script's `File` and `Folder` objects and file dialogs give, and those of the +/// commands that answer the dialogs and keep their permissions, have a translated row in every +/// complete-message language. Each one in the first list is still a message the source gives; the +/// second list holds the note the file dialog shows when it left out picked files, and texts a +/// script reads only from a File or Folder object's `error`. +#[test] +fn script_file_messages_translate_in_every_complete_message_language() { + const SCANNED: &[&str] = &[ + "Script file access denied", + "Script file access denied: {path}", + "Script file access is unavailable on the web", + "Script file access to the app's own folders is not allowed", + "Script file cannot be decoded", + "Script file cannot encode the text", + "Script file could not be read", + "Script file could not be written", + "Script file dialogs need a person to answer them", + "Script file does not exist", + "Script file exceeds 8 MiB", + "Script file is not a regular file", + "Script file is not open", + "Script file is not open for writing", + "Script file name is already in use", + "Script file name must be a name without a folder", + "Script file path exceeds 32,767 characters", + "Script file permission can be kept only for a script run from a file", + "Script file permission could not be saved", + "Script files cannot be opened in another application", + "Script folder has more than 2,048 entries", + "Script folder mask takes too many steps to match", + "{name}: a file dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code", + "the script opened more file data than one run may open (32 MiB)", + "the script wrote more file data than one run may write (32 MiB)", + "`answer` for a script's file dialog must be one of: once, always, deny, stop", + "choose a file or folder first, or deny", + "the script file permissions could not be saved: {e}", + "this script's file access can be allowed only once", + "Only the person at the keyboard can allow a script's file access", + ]; + const ERROR_ONLY: &[&str] = &[ + "A script is given at most 2,048 files: the files picked after them were left out", + "Script file open mode must be r, w, e or a", + "Script has 256 files open", + "Script folder is not empty", + "Script files cannot make aliases", + "Script file hidden setting cannot be changed", + ]; + let messages = message_literals(); + let gone: Vec<&&str> = SCANNED.iter().filter(|m| !messages.contains(**m)).collect(); + assert!(gone.is_empty(), "no longer messages in the source: {gone:?}"); + for code in COMPLETE_MESSAGES { + let lang = Lang::from_code(code).expect("registered"); + let (entries, _) = parse_entries(lang.0.source); + for m in SCANNED.iter().chain(ERROR_ONLY) { + let row = entries.iter().find(|(ctx, src, _)| ctx == "@msg" && src == m); + assert!(row.is_some_and(|(_, src, tr)| tr != src), "{code}: no translated row for {m:?}"); + } + } + let de = Lang::from_code("de").expect("de registered"); + assert_eq!(message(de, "Script file access denied: C:/x/a.txt"), "Dateizugriff des Skripts verweigert: C:/x/a.txt"); +} + #[test] fn package_status_message_templates_parse() { let c = Catalog::parse(concat!( @@ -2532,8 +2594,8 @@ fn script_errors_are_translated() { "Script file could not be read", "Script folder has more than 2,048 entries", "Script file open mode must be r, w, e or a", - "Script file writing is not available", - "Script file dialogs are not available", + "Script file is not open for writing", + "Script file dialogs need a person to answer them", "Script files cannot be opened in another application", "Script file access is unavailable on the web", "Script has 256 files open", diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index ef8773c31b..f4df32faee 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -4001,6 +4001,13 @@ axis Both Her İkisi Show External Script Warning Harici Betik Uyarısını Göster A Script Is Running Bir Betik Çalışıyor Script Alert Betik Uyarısı + Script File Access Betik Dosya Erişimi + The script asks to read a file you choose. Betik, seçtiğiniz bir dosyayı okumak için izin istiyor. + The script asks to read and write a file you choose. Betik, seçtiğiniz bir dosyayı okumak ve yazmak için izin istiyor. + The script asks to read and write a folder you choose, with everything in it. Betik, seçtiğiniz bir klasörü içindeki her şeyle birlikte okumak ve yazmak için izin istiyor. + Allow Once Bir Kez İzin Ver + Always Allow This Script Bu Betiğe Her Zaman İzin Ver + Deny Reddet A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Bir betik açık belgeleri değiştirebilir ve çalıştırdığı komutlarla dosya yazabilir. Yalnızca güvendiğiniz betikleri çalıştırın. Do not show this warning again Bu uyarıyı bir daha gösterme 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. @@ -4029,8 +4036,6 @@ axis Both Her İkisi @msg Script file could not be read Betik dosyası okunamadı @msg Script folder has more than 2,048 entries Betik klasöründe 2.048'den fazla öğe var @msg Script file open mode must be r, w, e or a Betik dosyası açma modu r, w, e veya a olmalıdır -@msg Script file writing is not available Betik dosyası yazma kullanılamıyor -@msg Script file dialogs are not available Betik dosyası iletişim kutuları kullanılamıyor @msg Script files cannot be opened in another application Betik dosyaları başka bir uygulamada açılamaz @msg Script file access is unavailable on the web Betik dosyası erişimi web'de kullanılamıyor @msg Script has 256 files open Betiğin 256 açık dosyası var @@ -4101,6 +4106,27 @@ axis Both Her İkisi @msg there is no script engine named {name} {name} adlı bir betik motoru yok @msg Running a script Betik çalıştırılıyor @msg Copied the script report Komut dosyası raporu kopyalandı +@msg Script file access denied: {path} Betiğin dosya erişimi reddedildi: {path} +@msg Script file access to the app's own folders is not allowed Betiklerin uygulamanın kendi klasörlerine erişmesine izin verilmez +@msg Script file cannot encode the text Betiğin dosyası metni kodlayamıyor +@msg Script file could not be written Betiğin dosyası yazılamadı +@msg Script file dialogs need a person to answer them Betiğin dosya iletişim kutularının yanıtlanması için bir kişi gerekir +@msg Script file is not open for writing Betiğin dosyası yazmak için açık değil +@msg Script file name is already in use Betiğin dosya adı zaten kullanılıyor +@msg Script file name must be a name without a folder Betiğin dosya adı klasör içermeyen bir ad olmalıdır +@msg Script file permission can be kept only for a script run from a file Dosya izni yalnızca bir dosyadan çalıştırılan betik için saklanabilir +@msg Script file permission could not be saved Betiğin dosya izni kaydedilemedi +@msg Script folder is not empty Betiğin klasörü boş değil +@msg Script files cannot make aliases Betiğin dosyaları takma ad oluşturamaz +@msg Script file hidden setting cannot be changed Betiğin dosyasının gizli ayarı değiştirilemez +@msg {name}: a file dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: dosya iletişim kutusu yerleşik bir işlevin, bir getter'ın, bir dönüştürmenin veya $.evalFile'ın çalıştırdığı bir dosyanın geri çağrısı içinde açılamaz; onu betiğin kendi kodundan çağırın +@msg the script wrote more file data than one run may write (32 MiB) betik, bir çalıştırmanın yazabileceğinden fazla dosya verisi yazdı (32 MiB) +@msg `answer` for a script's file dialog must be one of: once, always, deny, stop bir betiğin dosya iletişim kutusu için `answer` şunlardan biri olmalıdır: once, always, deny, stop +@msg choose a file or folder first, or deny önce bir dosya veya klasör seçin ya da reddedin +@msg the script file permissions could not be saved: {e} betiklerin dosya izinleri kaydedilemedi: {e} +@msg this script's file access can be allowed only once bu betiğin dosya erişimine yalnızca bir kez izin verilebilir +@msg Only the person at the keyboard can allow a script's file access Bir betiğin dosya erişimine yalnızca klavye başındaki kişi izin verebilir +@msg A script is given at most 2,048 files: the files picked after them were left out Bir betiğe en fazla 2.048 dosya verilir: bunlardan sonra seçilen dosyalar dışarıda bırakıldı @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} @msg Couldn't open {name}: {e} {name} açılamadı: {e} diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 0bccbd8cb6..219a79d05e 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -4246,6 +4246,13 @@ axis Both Обидві Show External Script Warning Показувати попередження про зовнішні скрипти A Script Is Running Виконується скрипт Script Alert Повідомлення скрипту + Script File Access Доступ скрипту до файлів + The script asks to read a file you choose. Скрипт просить дозволу прочитати вибраний вами файл. + The script asks to read and write a file you choose. Скрипт просить дозволу читати й записувати вибраний вами файл. + The script asks to read and write a folder you choose, with everything in it. Скрипт просить дозволу читати й записувати вибрану вами папку з усім її вмістом. + Allow Once Дозволити один раз + Always Allow This Script Завжди дозволяти цей скрипт + Deny Заборонити A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Скрипт може змінювати відкриті документи й записувати файли за допомогою команд, які виконує. Запускайте лише ті скрипти, яким довіряєте. Do not show this warning again Більше не показувати це попередження Stop the script and undo what it did? Then quit again. Зупинити скрипт і скасувати його зміни? Потім вийдіть ще раз. @@ -4274,8 +4281,6 @@ axis Both Обидві @msg Script file could not be read Не вдалося прочитати файл скрипта @msg Script folder has more than 2,048 entries Тека скрипта має понад 2048 елементів @msg Script file open mode must be r, w, e or a Режим відкриття файлу скрипта має бути r, w, e або a -@msg Script file writing is not available Запис файлів скрипта недоступний -@msg Script file dialogs are not available Діалогові вікна файлів скрипта недоступні @msg Script files cannot be opened in another application Файли скрипта не можна відкрити в іншому застосунку @msg Script file access is unavailable on the web Доступ до файлів скрипта у вебверсії недоступний @msg Script has 256 files open Скрипт має 256 відкритих файлів @@ -4346,6 +4351,27 @@ axis Both Обидві @msg there is no script engine named {name} рушія скриптів з назвою {name} немає @msg Running a script Виконується скрипт @msg Copied the script report Звіт про сценарій скопійовано +@msg Script file access denied: {path} Доступ скрипту до файлів заборонено: {path} +@msg Script file access to the app's own folders is not allowed Скрипту не дозволено доступ до власних папок застосунку +@msg Script file cannot encode the text Файл скрипту не може закодувати текст +@msg Script file could not be written Не вдалося записати файл скрипту +@msg Script file dialogs need a person to answer them Для відповіді на файлові діалоги скрипту потрібна людина +@msg Script file is not open for writing Файл скрипту не відкрито для запису +@msg Script file name is already in use Ім’я файлу скрипту вже використовується +@msg Script file name must be a name without a folder Ім’я файлу скрипту має бути іменем без папки +@msg Script file permission can be kept only for a script run from a file Дозвіл на файли можна зберегти лише для скрипту, запущеного з файлу +@msg Script file permission could not be saved Не вдалося зберегти дозвіл скрипту на файли +@msg Script folder is not empty Папка скрипту не порожня +@msg Script files cannot make aliases Файли скрипту не можуть створювати псевдоніми +@msg Script file hidden setting cannot be changed Не можна змінити параметр прихованості файлу скрипту +@msg {name}: a file dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: файловий діалог не можна відкрити всередині зворотного виклику вбудованої функції, гетера, перетворення або файлу, який виконує $.evalFile; викличте його з власного коду скрипту +@msg the script wrote more file data than one run may write (32 MiB) скрипт записав більше даних файлів, ніж може записати один запуск (32 MiB) +@msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` для файлового діалогу скрипту має бути одним із: once, always, deny, stop +@msg choose a file or folder first, or deny спершу виберіть файл або папку чи відмовте +@msg the script file permissions could not be saved: {e} не вдалося зберегти дозволи скриптів на файли: {e} +@msg this script's file access can be allowed only once доступ цього скрипту до файлів можна дозволити лише один раз +@msg Only the person at the keyboard can allow a script's file access Дозволити скрипту доступ до файлів може лише людина за клавіатурою +@msg A script is given at most 2,048 files: the files picked after them were left out Скрипт отримує щонайбільше 2 048 файлів: файли, вибрані після них, пропущено @msg Corners edits the corners of a path «Кути» редагує кути контуру @msg Couldn't copy to the system clipboard: {e} Не вдалося скопіювати до системного буфера обміну: {e} @msg Couldn't open {name}: {e} Не вдалося відкрити {name}: {e} diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 4f084029db..d9e307c7f4 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -4672,6 +4672,13 @@ theme Appearance Giao diện 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 Script Alert Thông báo của tập lệnh + Script File Access Quyền truy cập tệp của tập lệnh + The script asks to read a file you choose. Tập lệnh yêu cầu đọc một tệp bạn chọn. + The script asks to read and write a file you choose. Tập lệnh yêu cầu đọc và ghi một tệp bạn chọn. + The script asks to read and write a folder you choose, with everything in it. Tập lệnh yêu cầu đọc và ghi một thư mục bạn chọn, cùng mọi thứ bên trong. + Allow Once Cho phép một lần + Always Allow This Script Luôn cho phép tập lệnh này + Deny Từ chối A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. Tập lệnh có thể thay đổi các tài liệu đang mở và ghi tệp thông qua các lệnh mà nó chạy. Chỉ chạy những tập lệnh bạn tin cậy. Do not show this warning again Không hiện lại cảnh báo này 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. @@ -4700,8 +4707,6 @@ theme Appearance Giao diện @msg Script file could not be read Không thể đọc tệp tập lệnh @msg Script folder has more than 2,048 entries Thư mục tập lệnh có hơn 2.048 mục @msg Script file open mode must be r, w, e or a Chế độ mở tệp tập lệnh phải là r, w, e hoặc a -@msg Script file writing is not available Không thể ghi tệp tập lệnh -@msg Script file dialogs are not available Không có hộp thoại tệp cho tập lệnh @msg Script files cannot be opened in another application Không thể mở tệp tập lệnh trong ứng dụng khác @msg Script file access is unavailable on the web Không thể truy cập tệp tập lệnh trên web @msg Script has 256 files open Tập lệnh đang mở 256 tệp @@ -4772,6 +4777,27 @@ theme Appearance Giao diện @msg there is no script engine named {name} không có bộ máy tập lệnh nào tên {name} @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 Script file access denied: {path} Quyền truy cập tệp của tập lệnh bị từ chối: {path} +@msg Script file access to the app's own folders is not allowed Tập lệnh không được phép truy cập các thư mục riêng của ứng dụng +@msg Script file cannot encode the text Tệp của tập lệnh không thể mã hóa văn bản +@msg Script file could not be written Không thể ghi tệp của tập lệnh +@msg Script file dialogs need a person to answer them Hộp thoại tệp của tập lệnh cần một người trả lời +@msg Script file is not open for writing Tệp của tập lệnh chưa được mở để ghi +@msg Script file name is already in use Tên tệp của tập lệnh đã được sử dụng +@msg Script file name must be a name without a folder Tên tệp của tập lệnh phải là một tên không có thư mục +@msg Script file permission can be kept only for a script run from a file Chỉ có thể giữ quyền truy cập tệp cho tập lệnh chạy từ một tệp +@msg Script file permission could not be saved Không thể lưu quyền truy cập tệp của tập lệnh +@msg Script folder is not empty Thư mục của tập lệnh không trống +@msg Script files cannot make aliases Tệp của tập lệnh không thể tạo bí danh +@msg Script file hidden setting cannot be changed Không thể thay đổi cài đặt ẩn của tệp tập lệnh +@msg {name}: a file dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: không thể mở hộp thoại tệp bên trong callback của hàm dựng sẵn, getter, phép chuyển đổi hoặc tệp mà $.evalFile chạy; hãy gọi nó từ mã riêng của tập lệnh +@msg the script wrote more file data than one run may write (32 MiB) tập lệnh đã ghi nhiều dữ liệu tệp hơn mức một lần chạy được phép ghi (32 MiB) +@msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` cho hộp thoại tệp của tập lệnh phải là một trong: once, always, deny, stop +@msg choose a file or folder first, or deny hãy chọn một tệp hoặc thư mục trước, hoặc từ chối +@msg the script file permissions could not be saved: {e} không thể lưu quyền truy cập tệp của các tập lệnh: {e} +@msg this script's file access can be allowed only once quyền truy cập tệp của tập lệnh này chỉ có thể được cho phép một lần +@msg Only the person at the keyboard can allow a script's file access Chỉ người ngồi tại bàn phím mới có thể cho phép tập lệnh truy cập tệp +@msg A script is given at most 2,048 files: the files picked after them were left out Một tập lệnh nhận tối đa 2.048 tệp: các tệp được chọn sau đó đã bị bỏ qua @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} @msg Couldn't copy to the system clipboard: {e} Không thể sao chép vào khay nhớ tạm hệ thống: {e} diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index b04e65a65b..4f7d745e25 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -4704,6 +4704,13 @@ imageTrace Outline 轮廓 Show External Script Warning 显示外部脚本警告 A Script Is Running 脚本正在运行 Script Alert 脚本提示 + Script File Access 脚本文件访问 + The script asks to read a file you choose. 脚本请求读取您选择的文件。 + The script asks to read and write a file you choose. 脚本请求读写您选择的文件。 + The script asks to read and write a folder you choose, with everything in it. 脚本请求读写您选择的文件夹及其中的所有内容。 + Allow Once 允许一次 + Always Allow This Script 始终允许此脚本 + Deny 拒绝 A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. 脚本可以更改打开的文档,并可通过其运行的命令写入文件。请只运行您信任的脚本。 Do not show this warning again 不再显示此警告 Stop the script and undo what it did? Then quit again. 要停止脚本并撤销其更改吗?然后请再次退出。 @@ -4732,8 +4739,6 @@ imageTrace Outline 轮廓 @msg Script file could not be read 无法读取脚本文件 @msg Script folder has more than 2,048 entries 脚本文件夹的条目超过 2,048 个 @msg Script file open mode must be r, w, e or a 脚本文件的打开模式必须是 r、w、e 或 a -@msg Script file writing is not available 脚本文件写入不可用 -@msg Script file dialogs are not available 脚本文件对话框不可用 @msg Script files cannot be opened in another application 脚本文件无法在其他应用程序中打开 @msg Script file access is unavailable on the web 网页版无法访问脚本文件 @msg Script has 256 files open 脚本已打开 256 个文件 @@ -4804,6 +4809,27 @@ imageTrace Outline 轮廓 @msg there is no script engine named {name} 没有名为 {name} 的脚本引擎 @msg Running a script 正在运行脚本 @msg Copied the script report 已复制脚本报告 +@msg Script file access denied: {path} 脚本的文件访问被拒绝:{path} +@msg Script file access to the app's own folders is not allowed 不允许脚本访问应用自身的文件夹 +@msg Script file cannot encode the text 脚本的文件无法编码该文本 +@msg Script file could not be written 无法写入脚本的文件 +@msg Script file dialogs need a person to answer them 脚本的文件对话框需要有人回答 +@msg Script file is not open for writing 脚本的文件未以写入方式打开 +@msg Script file name is already in use 脚本的文件名已被使用 +@msg Script file name must be a name without a folder 脚本的文件名必须是不含文件夹的名称 +@msg Script file permission can be kept only for a script run from a file 只有从文件运行的脚本才能保留文件权限 +@msg Script file permission could not be saved 无法保存脚本的文件权限 +@msg Script folder is not empty 脚本的文件夹不为空 +@msg Script files cannot make aliases 脚本的文件无法创建别名 +@msg Script file hidden setting cannot be changed 无法更改脚本文件的隐藏设置 +@msg {name}: a file dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}:文件对话框不能在内置函数、getter、转换或 $.evalFile 运行的文件的回调中打开;请从脚本自身的代码中调用 +@msg the script wrote more file data than one run may write (32 MiB) 脚本写入的文件数据超过了一次运行可写入的上限 (32 MiB) +@msg `answer` for a script's file dialog must be one of: once, always, deny, stop 脚本文件对话框的 `answer` 必须是以下之一:once、always、deny、stop +@msg choose a file or folder first, or deny 请先选择文件或文件夹,或拒绝 +@msg the script file permissions could not be saved: {e} 无法保存脚本的文件权限:{e} +@msg this script's file access can be allowed only once 此脚本的文件访问只能允许一次 +@msg Only the person at the keyboard can allow a script's file access 只有键盘前的人才能允许脚本访问文件 +@msg A script is given at most 2,048 files: the files picked after them were left out 脚本最多获得 2,048 个文件:之后选择的文件已被略去 @msg Exported {path} 已导出 {path} @msg no CSS to copy: select objects with CSS of their own 没有可复制的 CSS:请选择带有自身 CSS 的对象 @msg unknown highlight `{h}` 未知的高亮显示 `{h}` diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index be62fde8a7..a1d90936f3 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -2471,6 +2471,13 @@ file-filter Templates 範本 Show External Script Warning 顯示外部指令碼警告 A Script Is Running 指令碼正在執行 Script Alert 指令碼提示 + Script File Access 指令碼檔案存取 + The script asks to read a file you choose. 指令碼要求讀取您選擇的檔案。 + The script asks to read and write a file you choose. 指令碼要求讀寫您選擇的檔案。 + The script asks to read and write a folder you choose, with everything in it. 指令碼要求讀寫您選擇的資料夾及其中的所有內容。 + Allow Once 允許一次 + Always Allow This Script 一律允許此指令碼 + Deny 拒絕 A script can change the open documents and can write files through the commands it runs. Run only scripts you trust. 指令碼可以變更開啟的文件,並可透過其執行的命令寫入檔案。請只執行您信任的指令碼。 Do not show this warning again 不再顯示此警告 Stop the script and undo what it did? Then quit again. 要停止指令碼並還原其變更嗎?然後請再次結束。 @@ -2499,8 +2506,6 @@ file-filter Templates 範本 @msg Script file could not be read 無法讀取指令碼檔案 @msg Script folder has more than 2,048 entries 指令碼資料夾的項目超過 2,048 個 @msg Script file open mode must be r, w, e or a 指令碼檔案的開啟模式必須是 r、w、e 或 a -@msg Script file writing is not available 無法使用指令碼檔案寫入 -@msg Script file dialogs are not available 無法使用指令碼檔案對話方塊 @msg Script files cannot be opened in another application 指令碼檔案無法在其他應用程式中開啟 @msg Script file access is unavailable on the web 網頁版無法存取指令碼檔案 @msg Script has 256 files open 指令碼已開啟 256 個檔案 @@ -2571,6 +2576,27 @@ file-filter Templates 範本 @msg there is no script engine named {name} 沒有名為 {name} 的指令碼引擎 @msg Running a script 正在執行指令碼 @msg Copied the script report 已複製指令碼報告 +@msg Script file access denied: {path} 指令碼的檔案存取遭拒:{path} +@msg Script file access to the app's own folders is not allowed 不允許指令碼存取應用程式本身的資料夾 +@msg Script file cannot encode the text 指令碼的檔案無法編碼該文字 +@msg Script file could not be written 無法寫入指令碼的檔案 +@msg Script file dialogs need a person to answer them 指令碼的檔案對話框需要有人回應 +@msg Script file is not open for writing 指令碼的檔案未以寫入方式開啟 +@msg Script file name is already in use 指令碼的檔案名稱已在使用中 +@msg Script file name must be a name without a folder 指令碼的檔案名稱必須是不含資料夾的名稱 +@msg Script file permission can be kept only for a script run from a file 只有從檔案執行的指令碼才能保留檔案權限 +@msg Script file permission could not be saved 無法儲存指令碼的檔案權限 +@msg Script folder is not empty 指令碼的資料夾不是空的 +@msg Script files cannot make aliases 指令碼的檔案無法建立別名 +@msg Script file hidden setting cannot be changed 無法變更指令碼檔案的隱藏設定 +@msg {name}: a file dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}:檔案對話框無法在內建函式、getter、轉換或 $.evalFile 執行的檔案的回呼中開啟;請從指令碼本身的程式碼中呼叫 +@msg the script wrote more file data than one run may write (32 MiB) 指令碼寫入的檔案資料超過一次執行可寫入的上限 (32 MiB) +@msg `answer` for a script's file dialog must be one of: once, always, deny, stop 指令碼檔案對話框的 `answer` 必須是下列之一:once、always、deny、stop +@msg choose a file or folder first, or deny 請先選擇檔案或資料夾,或拒絕 +@msg the script file permissions could not be saved: {e} 無法儲存指令碼的檔案權限:{e} +@msg this script's file access can be allowed only once 此指令碼的檔案存取只能允許一次 +@msg Only the person at the keyboard can allow a script's file access 只有鍵盤前的人才能允許指令碼存取檔案 +@msg A script is given at most 2,048 files: the files picked after them were left out 指令碼最多取得 2,048 個檔案:之後選擇的檔案已略去 @msg Exported {path} 已匯出 {path} @msg no CSS to copy: select objects with CSS of their own 沒有可複製的 CSS:請選取有自己 CSS 的物件 @msg unknown highlight `{h}` 未知的反白顯示 `{h}` diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index c4c6ded189..17fcb312ca 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -329,6 +329,11 @@ pub struct VectorcraftApp { /// The plug-in install the approval dialog asks about, kept out of the dialog's fields, which /// `ui.dialog.set` writes. pub(crate) pending_plugin_install: Option, + /// The paths Choose… picked in a script's file dialog, kept out of the dialog's fields, which + /// `ui.dialog.set` writes. + pub(crate) script_picked: Vec, + /// Choose… left out files past the most a script is given. + pub(crate) script_picked_left_out: bool, /// The pen end the canvas saw last and the tool its eraser end stands in for /// ([`stylus::sync_eraser_tool`]). pub(crate) pen_end: stylus::PenEnd, diff --git a/crates/ui-egui/src/picks.rs b/crates/ui-egui/src/picks.rs index ea1b51e049..694fc0e6d7 100644 --- a/crates/ui-egui/src/picks.rs +++ b/crates/ui-egui/src/picks.rs @@ -32,10 +32,14 @@ pub enum PickRequest { Open(FilePick), /// An open dialog for files to place. OpenMany, + /// An open dialog for several files of the pick's types. + OpenFiles(FilePick), /// A save dialog. Save(FilePick), /// A folder picker. Folder, + /// A folder picker that starts in the folder given. + FolderAt(String), } /// The paths a dialog shown off the UI thread picked (none: cancelled). A save dialog that reports @@ -192,10 +196,10 @@ impl Picks { /// The kind of dialog open off the UI thread (`ui.inspect`'s `fileDialog`). pub(crate) fn waiting_kind(&self) -> Option<&'static str> { self.waiting.as_ref().map(|w| match w.request { - PickRequest::Open(_) => "open", + PickRequest::Open(_) | PickRequest::OpenFiles(_) => "open", PickRequest::OpenMany => "place", PickRequest::Save(_) => "save", - PickRequest::Folder => "folder", + PickRequest::Folder | PickRequest::FolderAt(_) => "folder", }) } } @@ -350,19 +354,32 @@ pub(crate) fn folder(app: &mut VectorcraftApp) -> Option { ask(app, PickRequest::Folder)?.into_iter().next() } +/// A folder from the folder picker, which starts in `start` when the host can start it there. +pub(crate) fn folder_at(app: &mut VectorcraftApp, start: &str) -> Option { + ask(app, PickRequest::FolderAt(start.to_string()))?.into_iter().next() +} + /// Paths from the open dialog for files to place (none: cancelled). pub(crate) fn open_many(app: &mut VectorcraftApp) -> Vec { ask(app, PickRequest::OpenMany).unwrap_or_default() } +/// Paths from an open dialog for several files of `pick`'s types (none: cancelled, or shown off the +/// UI thread for now). +pub(crate) fn open_files(app: &mut VectorcraftApp, pick: &FilePick) -> Vec { + ask(app, PickRequest::OpenFiles(pick.clone())).unwrap_or_default() +} + /// Whether the host shows `request`'s kind of dialog at all. pub(crate) fn can(app: &VectorcraftApp, request: &PickRequest) -> bool { let s = &app.services; match request { PickRequest::Open(_) => s.pick_open.is_some(), PickRequest::OpenMany => s.pick_open_multi.is_some() || s.pick_open.is_some(), + PickRequest::OpenFiles(_) => s.pick_open_files.is_some() || s.pick_open.is_some(), PickRequest::Save(_) => s.pick_save.is_some(), PickRequest::Folder => s.pick_folder.is_some(), + PickRequest::FolderAt(_) => s.pick_folder_at.is_some() || s.pick_folder.is_some(), } } @@ -402,11 +419,21 @@ fn ask(app: &mut VectorcraftApp, request: PickRequest) -> Option { PickRequest::Open(pick) => one(s.pick_open.as_mut().and_then(|f| f(pick))), PickRequest::Save(pick) => one(s.pick_save.as_mut().and_then(|f| f(pick))), PickRequest::Folder => one(s.pick_folder.as_mut().and_then(|f| f())), + PickRequest::FolderAt(start) => match (s.pick_folder_at.as_mut(), s.pick_folder.as_mut()) { + (Some(at), _) => one(at(start)), + (None, Some(f)) => one(f()), + (None, None) => None, + }, PickRequest::OpenMany => match (s.pick_open_multi.as_mut(), s.pick_open.as_mut()) { (Some(many), _) => Some(many()), (None, Some(f)) => one(f(&FilePick::default())), (None, None) => None, }, + PickRequest::OpenFiles(pick) => match (s.pick_open_files.as_mut(), s.pick_open.as_mut()) { + (Some(many), _) => Some(many(pick)), + (None, Some(f)) => one(f(pick)), + (None, None) => None, + }, } } diff --git a/crates/ui-egui/src/script_runs.rs b/crates/ui-egui/src/script_runs.rs index 02c2229741..799e73b2cc 100644 --- a/crates/ui-egui/src/script_runs.rs +++ b/crates/ui-egui/src/script_runs.rs @@ -1,7 +1,7 @@ //! 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, or that opened a dialog with -//! `alert`, `confirm` or `prompt`, waits for the person's answer. +//! `alert`, `confirm`, `prompt` or a `File` or `Folder` file dialog, waits for the person's answer. use serde_json::json; @@ -44,6 +44,15 @@ pub fn poll(app: &mut VectorcraftApp) { /// question about its growth. Closes the script's dialog when the run no longer waits at it. /// → true while the run waits. fn ask(app: &mut VectorcraftApp) -> bool { + if let Some(picker) = app.session.script_picker() { + if app.ui.dialog.is_none() { + script_run::open_picker(app, &picker); + } + return true; + } + if app.ui.dialog.as_ref().is_some_and(|d| d.kind == script_run::PICKER_KIND) { + app.ui.dialog = None; + } if let Some(dialog) = app.session.script_dialog() { if app.ui.dialog.is_none() { script_run::open_notice(app, &dialog); diff --git a/crates/ui-egui/src/services.rs b/crates/ui-egui/src/services.rs index 676a9a48c8..ce48ef17c1 100644 --- a/crates/ui-egui/src/services.rs +++ b/crates/ui-egui/src/services.rs @@ -35,6 +35,11 @@ pub type PickOpen = Box Option>; pub type PickSave = Box Option>; +pub type PickOpenFiles = Box Vec>; + +/// Shows a folder picker that starts in the given folder; returns the folder picked. +pub type PickFolderAt = Box Option>; + pub type ReadFn = Box Result, String>>; /// The first `max` bytes of the file at a path (all of it when it is shorter); the rest of the file @@ -120,6 +125,9 @@ pub struct Services { pub open_url: Option, /// Show an open dialog for several files (File → Place…); returns their paths (none: cancelled). pub pick_open_multi: Option Vec>>, + /// Show an open dialog for several files of the pick's types (a script's `File.openDialog` with + /// `multiSelect`); returns their paths (none: cancelled). Without it, an open dialog for one. + pub pick_open_files: Option, /// Web: start an async pick of files to place (they arrive via `place_inbox`). pub place_async: Option>, /// Files that arrived asynchronously to be placed (web: picked for Place, or dropped on the @@ -160,6 +168,9 @@ pub struct Services { pub open_in_photocraft: Option, /// Show a folder picker; returns its path (desktop: Relink to Folder, Package). pub pick_folder: Option Option>>, + /// Show a folder picker that starts in a folder (a script's `selectDlg`); returns its path. + /// Without it, `pick_folder`, which starts where the host starts it. + pub pick_folder_at: Option, /// Show the system's color sampler, which picks a color anywhere on the screen (macOS, Linux /// through the desktop portal, and browsers with an EyeDropper): Sample Color from Screen /// ([`screen_color`]). Without it that command answers with an error and the Color Picker's diff --git a/crates/ui-egui/src/tests/picks.rs b/crates/ui-egui/src/tests/picks.rs index e808cf2463..f0926e1979 100644 --- a/crates/ui-egui/src/tests/picks.rs +++ b/crates/ui-egui/src/tests/picks.rs @@ -53,6 +53,7 @@ pub(crate) fn off_the_ui_thread(services: &mut Services) -> (Shown, Written) { services.pick_open = Some(Box::new(in_line)); services.pick_save = Some(Box::new(in_line)); services.pick_open_multi = Some(Box::new(|| panic!("no dialog on the UI thread"))); + services.pick_open_files = Some(Box::new(|_: &FilePick| panic!("no dialog on the UI thread"))); services.pick_folder = Some(Box::new(|| panic!("no dialog on the UI thread"))); services.read = Some(Box::new(|_: &str| Ok(SVG.to_vec()))); services.write = Some(Box::new(move |path: &str, _: &[u8]| { @@ -1074,11 +1075,11 @@ fn without_tests(code: &str) -> String { } /// The calls in `code` (from [`code_only`]) of the host's in-line dialogs: [`Services`]' -/// `pick_open`, `pick_save`, `pick_folder` and `pick_open_multi` used other than to ask whether -/// the host has them (`.is_some()`, `.is_none()`). +/// `pick_open`, `pick_save`, `pick_folder`, `pick_folder_at`, `pick_open_multi` and +/// `pick_open_files` used other than to ask whether the host has them (`.is_some()`, `.is_none()`). fn in_line_dialogs(code: &str) -> Vec { let mut found = vec![]; - for name in ["pick_open", "pick_save", "pick_folder", "pick_open_multi"] { + for name in ["pick_open", "pick_save", "pick_folder", "pick_folder_at", "pick_open_multi", "pick_open_files"] { let field = format!(".{name}"); let mut rest = code; while let Some(at) = rest.find(&field) { diff --git a/crates/ui-egui/src/tests/script_run.rs b/crates/ui-egui/src/tests/script_run.rs index 08ac8e1917..ba6553e068 100644 --- a/crates/ui-egui/src/tests/script_run.rs +++ b/crates/ui-egui/src/tests/script_run.rs @@ -267,9 +267,13 @@ fn a_stop_names_the_files_the_run_left_written() { 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) {{}}"); + let source = format!("Folder.selectDialog('Folder'); 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!(app.session.script_picker().is_some(), "the run waits at its folder dialog"); + let paths = vec![dir.to_string_lossy().into_owned()]; + assert!(app.session.script_pick(vectorcraft_engine::script::files::PickAnswer::Allow { paths, always: false })); + 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(); @@ -277,6 +281,327 @@ fn a_stop_names_the_files_the_run_left_written() { let _ = std::fs::remove_dir_all(&dir); } +/// A script's open dialog with `multiSelect` shows the host's dialog for several files, with the +/// file types of the script's filter, and the script gets every file picked. +#[test] +fn a_scripts_open_dialog_picks_several_files_of_its_types() { + let asked = std::rc::Rc::new(std::cell::RefCell::new(Vec::new())); + let dir = folder("several"); + let paths: Vec = ["a.txt", "b.txt"].iter().map(|n| dir.join(n).to_string_lossy().into_owned()).collect(); + for p in &paths { + std::fs::write(p, "x").unwrap(); + } + let (seen, given) = (asked.clone(), paths.clone()); + let services = crate::Services { + pick_open: Some(Box::new(|_: &crate::FilePick| panic!("the dialog for one file"))), + pick_open_files: Some(Box::new(move |pick: &crate::FilePick| { + seen.borrow_mut().push(pick.filters.clone()); + given.clone() + })), + ..Default::default() + }; + let mut app = VectorcraftApp::new(Session::new(), services); + app.run("file.new", json!({})).unwrap(); + app.session.prefs.show_external_script_warning = false; + let source = "var f = File.openDialog('Pick', 'Text:*.txt;All files:*.*', true); vc.log([f.length, f[0].name, f[1].name]);"; + menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": source })).unwrap().unwrap(); + script_runs::poll(&mut app); + let mut d = app.ui.dialog.take().expect("the script's file dialog"); + assert_eq!(d.kind, dialogs::script_run::PICKER_KIND); + dialogs::script_run::choose(&mut app, &mut d); + assert_eq!(*asked.borrow(), vec![vec![("Text".to_string(), vec!["txt".to_string()]), ("All files".to_string(), vec!["*".to_string()])]]); + assert_eq!(app.script_picked, paths); + d.fields.insert("answer".into(), json!("once")); + app.ui.dialog = Some(d); + confirm(&mut app).unwrap(); + finish(&mut app); + assert_eq!(app.session.script_report().unwrap()["log"], json!([[2, "a.txt", "b.txt"]])); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A folder's `selectDlg` asks the host for a folder picker that starts in that folder, and +/// `Folder.selectDialog` for one that starts where the host starts it. +#[test] +fn a_scripts_folder_dialog_starts_in_the_folder_it_was_asked_from() { + let dir = folder("selectstart"); + let requests = std::rc::Rc::new(std::cell::RefCell::new(Vec::new())); + let seen = requests.clone(); + let picked = dir.to_string_lossy().into_owned(); + let services = crate::Services { + start_pick: Some(Box::new(move |request: crate::picks::PickRequest| { + seen.borrow_mut().push(request); + None + })), + pick_folder: Some(Box::new(move || Some(picked.clone()))), + ..Default::default() + }; + let mut app = VectorcraftApp::new(Session::new(), services); + app.run("file.new", json!({})).unwrap(); + app.session.prefs.show_external_script_warning = false; + let source = format!( + "var a = new Folder({:?}).selectDlg('Pick'); var b = Folder.selectDialog('Pick'); vc.log([a !== null, b !== null]);", + dir.to_string_lossy() + ); + menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": source })).unwrap().unwrap(); + for _ in 0..2 { + script_runs::poll(&mut app); + let mut d = app.ui.dialog.take().expect("the script's file dialog"); + assert_eq!(d.kind, dialogs::script_run::PICKER_KIND); + dialogs::script_run::choose(&mut app, &mut d); + d.fields.insert("answer".into(), json!("once")); + app.ui.dialog = Some(d); + confirm(&mut app).unwrap(); + } + finish(&mut app); + let start = app.session.script_report().map(|r| r["log"].clone()); + assert_eq!(start, Some(json!([[true, true]]))); + let r = requests.borrow(); + let starts_in_dir = |s: &str| std::fs::canonicalize(s).ok() == std::fs::canonicalize(&dir).ok(); + assert!(matches!(&r[..], [crate::picks::PickRequest::FolderAt(s), crate::picks::PickRequest::Folder] if starts_in_dir(s)), "{r:?}"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// Where the host shows file dialogs in line (Windows), a folder's `selectDlg` also opens the +/// folder picker in that folder, and `Folder.selectDialog` the one that starts where the host +/// starts it. +#[test] +fn a_scripts_folder_dialog_shown_in_line_starts_in_the_folder_it_was_asked_from() { + let dir = folder("selectstartinline"); + let shown = std::rc::Rc::new(std::cell::RefCell::new(Vec::new())); + let (at, plain) = (shown.clone(), shown.clone()); + let (picked_at, picked) = (dir.to_string_lossy().into_owned(), dir.to_string_lossy().into_owned()); + let services = crate::Services { + pick_folder_at: Some(Box::new(move |start: &str| { + at.borrow_mut().push(Some(start.to_string())); + Some(picked_at.clone()) + })), + pick_folder: Some(Box::new(move || { + plain.borrow_mut().push(None); + Some(picked.clone()) + })), + ..Default::default() + }; + let mut app = VectorcraftApp::new(Session::new(), services); + app.run("file.new", json!({})).unwrap(); + app.session.prefs.show_external_script_warning = false; + let source = format!( + "var a = new Folder({:?}).selectDlg('Pick'); var b = Folder.selectDialog('Pick'); vc.log([a !== null, b !== null]);", + dir.to_string_lossy() + ); + menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": source })).unwrap().unwrap(); + for _ in 0..2 { + script_runs::poll(&mut app); + let mut d = app.ui.dialog.take().expect("the script's file dialog"); + assert_eq!(d.kind, dialogs::script_run::PICKER_KIND); + dialogs::script_run::choose(&mut app, &mut d); + d.fields.insert("answer".into(), json!("once")); + app.ui.dialog = Some(d); + confirm(&mut app).unwrap(); + } + finish(&mut app); + assert_eq!(app.session.script_report().map(|r| r["log"].clone()), Some(json!([[true, true]]))); + let r = shown.borrow(); + let starts_in_dir = |s: &str| std::fs::canonicalize(s).ok() == std::fs::canonicalize(&dir).ok(); + assert!(matches!(&r[..], [Some(s), None] if starts_in_dir(s)), "{r:?}"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A control request, handled as the app handles one: while `answering_control` is set. +fn control(app: &mut VectorcraftApp, method: &str, params: Value) -> Value { + let (req, _) = crate::control::ControlRequest::new(method, params); + app.ui.answering_control = true; + let outcome = crate::control::handle(app, &egui::Context::default(), &req); + app.ui.answering_control = false; + let crate::control::Outcome::Done(r) = outcome else { panic!("expected an immediate reply") }; + r +} + +const BY_PERSON: &str = "Only the person at the keyboard can allow a script's file access"; + +/// The paths a script's file dialog allows come from Choose… alone: `ui.dialog.set` cannot set +/// them, and fields set on the dialog do not let Always Allow keep a grant the run cannot keep. +#[test] +fn a_scripts_file_dialog_takes_no_paths_from_automation() { + let dir = folder("automated"); + let secret = dir.join("secret.txt"); + std::fs::write(&secret, "secret").unwrap(); + let mut app = app(); + app.session.prefs.show_external_script_warning = false; + let source = "var f = File.openDialog('Pick'); vc.log(f === null ? null : f.fsName);"; + menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": source })).unwrap().unwrap(); + script_runs::poll(&mut app); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(dialogs::script_run::PICKER_KIND)); + let p = secret.to_string_lossy().into_owned(); + let r = control(&mut app, "ui.dialog.set", json!({"field": "paths", "value": [p]})); + assert!(r["error"].as_str().is_some_and(|e| e.contains("no field `paths`")), "{r}"); + let always = json!({"fields": [{"field": "canAlways", "value": true}, {"field": "answer", "value": "always"}], "action": "confirm"}); + let r = control(&mut app, "ui.dialog.set", always.clone()); + assert_eq!(r["error"], BY_PERSON, "{r}"); + let d = app.ui.dialog.as_mut().expect("the dialog stays open"); + d.fields.insert("answer".into(), json!("once")); + assert_eq!(confirm(&mut app).unwrap_err(), "choose a file or folder first, or deny"); + app.script_picked = vec![p]; + let r = control(&mut app, "ui.dialog.set", always); + assert_eq!(r["error"], BY_PERSON, "{r}"); + let d = app.ui.dialog.as_mut().expect("the dialog stays open"); + d.fields.insert("canAlways".into(), json!(true)); + d.fields.insert("answer".into(), json!("always")); + assert_eq!(confirm(&mut app).unwrap_err(), "this script's file access can be allowed only once"); + let r = control(&mut app, "ui.dialog.set", json!({"fields": [{"field": "answer", "value": "deny"}], "action": "confirm"})); + assert!(r.get("error").is_none_or(Value::is_null), "{r}"); + finish(&mut app); + assert_eq!(app.session.script_report().unwrap()["log"], json!([null])); + let _ = std::fs::remove_dir_all(&dir); +} + +/// Allow Once and Always Allow This Script are taken only from the person at the keyboard: a control +/// request and synthetic input are refused and the dialog stays open, after a person picked a file +/// with Choose… too, while Deny from automation is taken. +#[test] +fn a_scripts_file_access_is_allowed_only_by_the_person() { + let dir = folder("byperson"); + let picked = dir.join("picked.txt"); + std::fs::write(&picked, "picked").unwrap(); + let mut app = app(); + app.session.prefs.show_external_script_warning = false; + let source = "var f = File.openDialog('Pick'); vc.log(f === null ? null : f.name);"; + menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": source })).unwrap().unwrap(); + script_runs::poll(&mut app); + app.script_picked = vec![picked.to_string_lossy().into_owned()]; + let r = control(&mut app, "ui.dialog.set", json!({"fields": [{"field": "answer", "value": "once"}], "action": "confirm"})); + assert_eq!(r["error"], BY_PERSON, "{r}"); + assert!(app.session.script_picker().is_some(), "the run still waits"); + let r = control(&mut app, "ui.dialog.set", json!({"fields": [{"field": "answer", "value": "deny"}], "action": "confirm"})); + assert!(r.get("error").is_none_or(Value::is_null), "Deny is taken from automation: {r}"); + finish(&mut app); + assert_eq!(app.session.script_report().unwrap()["log"], json!([null])); + + menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": source })).unwrap().unwrap(); + script_runs::poll(&mut app); + app.script_picked = vec![picked.to_string_lossy().into_owned()]; + app.ui.dialog.as_mut().expect("the file dialog").fields.insert("answer".into(), json!("once")); + app.synthetic_frame = true; + assert_eq!(confirm(&mut app).unwrap_err(), BY_PERSON); + app.synthetic_frame = false; + assert!(app.session.script_picker().is_some(), "the run still waits"); + confirm(&mut app).unwrap(); + finish(&mut app); + assert_eq!(app.session.script_report().unwrap()["log"], json!(["picked.txt"])); + let _ = std::fs::remove_dir_all(&dir); +} + +/// The texts the dialog layer draws, once a few frames have let it settle. +fn dialog_texts(app: &mut VectorcraftApp) -> Vec { + fn texts(s: &egui::Shape, out: &mut Vec) { + match s { + egui::Shape::Text(t) => out.push(t.galley.text().to_string()), + egui::Shape::Vec(v) => v.iter().for_each(|s| texts(s, out)), + _ => {} + } + } + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut v = vec![]; + for _ in 0..3 { + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| dialogs::show(app, ui.ctx())); + out.textures_delta.clear(); + v.clear(); + out.shapes.iter().for_each(|c| texts(&c.shape, &mut v)); + } + v +} + +/// The dialog says what the run asks for and shows the script's prompt, also after `ui.dialog.set` +/// changed the dialog's `kind` and `prompt` fields. +#[test] +fn a_scripts_file_dialog_says_what_the_run_asks_for() { + let mut app = app(); + app.session.prefs.show_external_script_warning = false; + let source = "vc.log(Folder.selectDialog('Pick the export folder'));"; + menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": source })).unwrap().unwrap(); + script_runs::poll(&mut app); + let r = + control(&mut app, "ui.dialog.set", json!({"fields": [{"field": "kind", "value": "open"}, {"field": "prompt", "value": "Nothing to see"}]})); + assert!(r.get("error").is_none_or(Value::is_null), "{r}"); + let texts = dialog_texts(&mut app); + let folder = "The script asks to read and write a folder you choose, with everything in it."; + assert!(texts.iter().any(|t| t == folder), "{texts:?}"); + assert!(texts.iter().any(|t| t == "Pick the export folder"), "{texts:?}"); + assert!(!texts.iter().any(|t| t == "Nothing to see" || t == "The script asks to read a file you choose."), "{texts:?}"); + dialogs::cancel(&mut app); + finish(&mut app); +} + +/// Enter in the file dialog gives Deny, its default answer, also after the person picked a folder. +#[test] +fn enter_in_a_scripts_file_dialog_denies() { + let mut app = app(); + app.session.prefs.show_external_script_warning = false; + let source = "vc.log(Folder.selectDialog('Pick'));"; + menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": source })).unwrap().unwrap(); + script_runs::poll(&mut app); + app.script_picked = vec![folder("enterdeny").to_string_lossy().into_owned()]; + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let enter = egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }; + for events in [vec![], vec![], vec![enter]] { + let mut out = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| dialogs::show(&mut app, ui.ctx())); + out.textures_delta.clear(); + } + assert!(app.ui.dialog.as_ref().is_none_or(|d| d.kind != dialogs::script_run::PICKER_KIND), "the dialog closes"); + finish(&mut app); + assert_eq!(app.session.script_report().unwrap()["log"], json!([null])); +} + +/// Enter on the file dialog's focused Choose… button goes to that button and does not deny. +#[test] +fn enter_on_a_focused_choose_button_does_not_deny() { + let mut app = app(); + app.session.prefs.show_external_script_warning = false; + menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": "vc.log(Folder.selectDialog('Pick'));" })).unwrap().unwrap(); + script_runs::poll(&mut app); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let key = |key| egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }; + let frame = |app: &mut VectorcraftApp, events| { + let mut out = ctx.run_ui(egui::RawInput { events, ..Default::default() }, |ui| dialogs::show(app, ui.ctx())); + out.textures_delta.clear(); + }; + for events in [vec![], vec![], vec![key(egui::Key::Tab)], vec![]] { + frame(&mut app, events); + } + assert!(ctx.memory(|m| m.focused().is_some()), "Tab gives a button the keyboard focus"); + frame(&mut app, vec![key(egui::Key::Enter)]); + frame(&mut app, vec![]); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(dialogs::script_run::PICKER_KIND), "the dialog stays open"); + assert!(app.session.script_picker().is_some(), "the run still waits"); + dialogs::cancel(&mut app); + finish(&mut app); +} + +/// Choose… keeps at most the 2,048 files a script is given, and the dialog says the files picked +/// after them were left out. +#[test] +fn a_scripts_file_dialog_keeps_at_most_2048_picked_files() { + let given: Vec = (0..2050).map(|n| format!("/picked/{n}.txt")).collect(); + let all = given.clone(); + let services = crate::Services { pick_open_files: Some(Box::new(move |_: &crate::FilePick| all.clone())), ..Default::default() }; + let mut app = VectorcraftApp::new(Session::new(), services); + app.run("file.new", json!({})).unwrap(); + app.session.prefs.show_external_script_warning = false; + menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": "File.openDialog('Pick', '', true);" })).unwrap().unwrap(); + script_runs::poll(&mut app); + let mut d = app.ui.dialog.take().expect("the script's file dialog"); + dialogs::script_run::choose(&mut app, &mut d); + app.ui.dialog = Some(d); + assert_eq!(app.script_picked, given[..2048]); + let texts = dialog_texts(&mut app); + let note = "A script is given at most 2,048 files: the files picked after them were left out"; + assert!(texts.iter().any(|t| t == note), "{texts:?}"); + dialogs::cancel(&mut app); + finish(&mut app); +} + #[test] fn a_new_app_shows_the_warning_by_default() { assert!(Session::new().prefs.show_external_script_warning); diff --git a/docs/mcp.md b/docs/mcp.md index 274db05a34..dd5de656cd 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2218,8 +2218,8 @@ script reads files with them: - `open('r')` opens a file to read, and `read([chars])`, `readln()`, `readch()`, `seek(pos[, mode])`, `tell()`, `eof` and `close()` read it. `read`, `readln` and `readch` count characters, and `seek` and `tell` count bytes. `readln` and `readch` take CR, LF, CRLF and LF CR as one line end. `folder.getFiles([mask])` lists a folder, sorted by name; - the mask matches `*` and `?` without regard to case, and a function as the mask keeps the entries it returns true - for. + the mask matches `*` and `?`, without regard to case on Windows and macOS and with case elsewhere, and a function + as the mask keeps the entries it returns true for. - A method that fails returns `false`, `null` or an empty string and sets `error`, such as `Script file access denied`, `Script file does not exist` or `Script file is not open`. A count or a position that is not a finite number, or a negative count, throws a `RangeError`. @@ -2234,7 +2234,9 @@ VectorCraft reads files by these rules of its own: `getFiles` leaves such an entry out. A missing file is refused the same way unless the nearest folder above it that exists is inside the script's folder. It is also refused when a link above it leads to a folder that does not exist. - `open` reads the whole file. A file larger than 8 MiB is refused from its size before any of it is read, with - `Script file exceeds 8 MiB`, and a run that opens more than 32 MiB in all ends with an error. A run has at most 256 + `Script file exceeds 8 MiB`, and a run that opens more than 32 MiB in all ends with an error. A file opened again + after its objects closed counts only the bytes it grew by, and a file that another object has open counts again. A + run has at most 256 files open at once; another `open` returns `false` with `Script has 256 files open` until one is closed. - The encoding is the one the file's byte order mark gives (UTF-8, UTF-16LE or UTF-16BE), otherwise the `encoding` the script set before `open`, otherwise UTF-8 when the bytes are valid UTF-8, otherwise CP1252. `BINARY` reads each @@ -2245,11 +2247,111 @@ VectorCraft reads files by these rules of its own: folder gives `null` with `Script folder mask takes too many steps to match`. - A path longer than 32,767 characters throws a `RangeError` (`Script file path exceeds 32,767 characters`) when a `File` or `Folder` is made from it. -- Writing is not available yet: `open('w')`, `open('e')`, `open('a')`, `write`, `writeln`, `copy`, `remove`, - `rename`, `create` and `createAlias` return `false` with `Script file writing is not available`, and setting - `length`, `hidden` or `readonly` sets `error` to that message and changes nothing. The file - and folder dialogs return `null`, and `execute` opens nothing and returns `false`. In the web build every lookup - fails with `Script file access is unavailable on the web`. +- `createAlias` returns `false` with `Script files cannot make aliases`, setting `hidden` sets `error` to `Script + file hidden setting cannot be changed` and changes nothing, and `execute` opens nothing and returns `false`. In the + web build every lookup fails with `Script file access is unavailable on the web`. + +The help page's writing members work as it describes +(, +): + +- `open('w')` empties the file, or makes it, `open('e')` opens a file that is there, and `open('a')` opens it at its + end. `write(...values)` writes the values as `String(value)` gives them, and `writeln(...values)` adds the line end + `lineFeed` names: CR LF for `Windows`, CR for `Macintosh` and LF for `Unix`. A byte order mark is written only + when the script writes ``. +- `copy(target)` copies the file to a path or a `File` and replaces a file that is there. `remove()` deletes a file, + or a folder only when it is empty (`Script folder is not empty`), at once and without the trash. `rename(name)` + takes a name without a folder; a name that is in use gives `Script file name is already in use`, and the object + takes the new path; another object that has the file open writes to the new path. An object whose changes + `close` could not write does not remove or rename its file, and another object that has a removed file open + drops its changes and takes no more writes. `copy` of a file over 8 MiB gives `Script file exceeds 8 MiB`, and `copy` of a file that + is open copies what the open file holds; an object that has the target open then holds the copy. `folder.create()` makes the folder and the folders above it, and gives `Script file access denied` without making any when one of them is outside the places the script may write. Setting `length` cuts the file or + pads it with zero bytes, also in an object that has the file open, and setting `readonly` changes the file (on + Unix, setting it clears every write bit, and clearing it gives back the bits the run cleared, or else the owner's + write bit). `changePath` of an object whose changes cannot be written gives `false` with `error` set and keeps its path. `copy` onto the file itself leaves it as it is, and `open('w')` with an + encoding that is not one gives `false` and leaves the file as it is. +- `File.openDialog(prompt, filter, multiSelect)`, `File.saveDialog(prompt, filter)` and `Folder.selectDialog(prompt)`, + and the objects' `openDlg`, `saveDlg` and `selectDlg`, give a `File` or a `Folder`, or `null` when the person + cancels; `multiSelect` gives an array of the files picked. A string `filter` such as `"JavaScript:*.jsx;All + files:*.*"` gives the file types the dialog shows: each `name:pattern` starts a type, a pattern without a name adds + to the type before it, and patterns are separated by `,` or `;`. `*.ext` patterns name extensions and `*` or `*.*` + every file; other patterns are left out. A `filter` that is a function is called with a `File` for each file + picked, and the files it gives a false value for are left out of the result; when none is left, the dialog + gives `null`. The dialog itself then shows every file. + +VectorCraft writes files by these rules of its own: + +- A script writes only in `Folder.temp`, `Folder.userData` and what a person allowed it in a file dialog. Its own + folder is only read. `Folder.temp` is a folder for the run, made when the script first names it and deleted when + the run ends; `new File()` names a new file there. `Folder.userData` is the script's own folder in the Script Data + folder next to the settings, kept between runs; a script given as `source`, or a session without a settings + folder, gets one inside `Folder.temp`. When that folder is a link, `Folder.userData` is `null` and the place the + link leads to is not granted. When automation write roots are set and do not take the folder, `Folder.temp` or + `Folder.userData` is `null` and the folder is not made; the same holds when they do not take a missing folder above it. When automation write roots are set, the place written must also be inside + them. Opening a file with `e` or `a` reads it, so the automation read roots apply to it as well. The folder that + holds the settings (the Scripts and Plug-ins folders among them) is kept out of every grant, also before it has + been made, apart from the script's own `Folder.userData`, and a folder that holds it cannot be renamed. Anything + else gives `false` with + `Script file access denied`. +- What a script writes is written when it closes the file or when the run ends, also when the run fails. At the + run's end the files left open are written in the order they were opened. A file + that `close` could not write is written again when the run ends, and a `write` that would pass the run's limit + is not written. A run that + would otherwise succeed fails when a changed file it left open cannot be written, with + `Error: the script left open files that could not be written` and the files' paths. One file + holds at most 8 MiB, and a run that writes more than 32 MiB in all ends with an error. `write` encodes in the + file's encoding: `ASCII` and `ISO-8859-1` give `false` with `Script file cannot encode the text` for a character + they cannot hold, and `BINARY` writes each character's low byte. `write` and `writeln` turn their values into text + only for an open file, and stop once the text is longer than 16,777,216 UTF-16 code units, giving `false` with + `Script file exceeds 8 MiB`. Each object that has a file open holds its own bytes, so the 32 MiB counts what + setting `length` adds to the file and to each such object, and what `copy` writes to its target and to each such + object of the target. The report's `written` names each file written, at most 4,096 of them; a run that wrote more + also has `writtenMore: true`. +- In the app a file dialog shows the script's prompt and what the script asks for: a file to read (open), a file to + read and write (save), or a folder to read and write with everything in it. The person chooses with Choose…, whose + dialog picks several files at once, and adds them to those chosen before, when the script asked for several with + `multiSelect` (Choose… keeps at most 2,048, and the dialog says when it left out the files picked after them), and + then picks Allow Once, Always Allow This Script or Deny; Deny, Enter, Escape and Cancel give `null`, and Stop ends + the run. Choose… for a folder's `selectDlg` opens the host's folder dialog in that folder. + The prompt and what the dialog says the script asks for come from the script's request, so `ui.dialog.set` on the + dialog's `kind` or `prompt` does not change them. Only the person at the keyboard allows access: an `answer` of + `once` or `always` from `ui.dialog.set`, `ui.dialog.confirm` or synthetic input gives `Only the person at the + keyboard can allow a script's file access`, and the dialog stays open; `deny` and `stop` are taken from automation. + Always Allow This Script keeps the grant in `Script Grants.json` next to the settings for that script file with + that text with the files it includes, by its SHA-256, so a changed or moved script, or a changed included file, + asks again. It is offered only for a script run from a file. The grant also keeps the SHA-256 of each source the + run evaluated up to its end (a file `$.evalFile` ran, a string given to `eval` or `Function`, at most 256). A later + run loses the grant before it evaluates a source the grant does not list, and from the start when its + `#targetengine` engine holds code the grant does not list, such as another script's. A kept grant stays on the + real path that was allowed: when that path now leads elsewhere, through a link put in its place or in a folder + above it, the grant is not used. +- A command a script runs with `vc.run` reads and writes files only where the script's `File` and `Folder` objects + may, and in the files the open documents were opened from or saved to. Anything else fails with + `Script file access denied` and the path, saving into a user library (swatches, brushes, symbols or graphic + styles) included; reading the app's own libraries is allowed. A script given as `source` that a person allowed nothing writes only in + its `Folder.temp` and `Folder.userData` and to the open documents' own files. + A pick inside the folder that holds the settings gives `null` and sets `error` to `Script file access to the app's + own folders is not allowed`. +- A run with nobody to ask, as over MCP or the command line, gives `null` from every file dialog and sets `error` to + `Script file dialogs need a person to answer them`, and takes no kept grant. In the app, a file dialog inside a + built-in's callback, a getter, a conversion or a file `$.evalFile` runs throws an error. + +`script.grants {}` lists the kept grants: `{grants: [{script, sha256, code, path, write, folder}], file}`, with `code` +the SHA-256 of each evaluated source (of its UTF-16 code units in little-endian order), `folder` true for a folder's +grant, which covers everything in the folder (a file's grant covers its own path only, also when a folder later +takes its place), and `file` the grants +file's path, or `null` without a settings folder. `script.grants.revoke {script?, path?, all?}` removes the grants of +a script file, of a path, of both together, or with `all: true` every grant, and returns `{removed}`. While a script +runs it is refused with the busy error, as the run keeps the grants it started with. A script cannot run either +command. + +```json +{"name":"run_command","arguments":{"command":"script.grants.revoke","params":{"all":true}}} +``` + +```sh +vectorcraft-cli run --cmd script.grants --params '{}' +``` Window › Script Console shows the session's script lines, oldest first: each run's start, its `$.write` and `$.writeln` output, its `vc.log` entries, its uncaught error as `name:line:column: message` (or `name: file:line:column: message` when the error is in another diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f04ee3c910..ba3af3858f 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -783,7 +783,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scripts: a run reads its preprocessor lines before any of it runs: `#include` and `//@include` put another file in place of the line, looked for beside the including file, in the `#includepath` folders and in `JSINCLUDE`; `#script` names the run; `#target` and `#strict off` are taken, `#strict on` turns on strict write checks (below), `#targetengine` names the engine (below), and `#engine` is refused. `$.evalFile` runs a file with the same globals and returns its last value, and `$.fileName` and `$.includePath` give the file being run and the include folders. A script run from a file reads these files only in its folder and below, without `..` names or links that lead out, and an error in one is reported at its own file, line and column ([preprocessor directives](https://extendscript.docsforadobe.dev/extendscript-tools-features/preprocessor-directives/), [the `$` object](https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/); `crates/engine/src/tests/script_include.rs`). - Scripts: `#targetengine name` (and `//@targetengine name`) runs the script in a named engine that lasts for the session, and a later script that names it sees the globals and functions earlier ones left ([preprocessor directives](https://extendscript.docsforadobe.dev/extendscript-tools-features/preprocessor-directives/)); `$.engineName` gives the name ([the `$` object](https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/)). VectorCraft's own rules: a script without the line and `#targetengine main` get a new engine each run, the line comes once in the script itself before its code, a session keeps 8 named engines with 64 MiB of heap each, an error or a stop keeps the globals the run set while the documents go back, kept host functions act for the run that calls them, `script.engines` lists the engines and `script.engine.drop` drops one, and the web build has none. `crates/engine/src/tests/script_engines.rs`. - Scripts: a runtime error is shown at the line that was running ([the help page](https://extendscript.docsforadobe.dev/extendscript-toolkit/debugging-in-the-toolkit/)). VectorCraft's own rules: an error in code an earlier run of a named engine compiled, such as a function it defined, is reported at that code's file, line and column (the earlier run's script, a file it included or a file its `$.evalFile` ran), while the report and its console line keep the calling run's name; a script given as text is named by its run's name, and each engine keeps these places for 8 MiB of source maps, the oldest going first. An error in code whose place is gone, or in code that `eval` or `Function` compiled, is reported without a line and column, and the code still runs. `crates/engine/src/tests/script_engines.rs`. - - Scripts: `File` and `Folder` ([File object](https://extendscript.docsforadobe.dev/file-system-access/file-object/), [Folder object](https://extendscript.docsforadobe.dev/file-system-access/folder-object/)) name files and folders by platform or URI path, with `name`, `fsName`, `absoluteURI`, `relativeURI`, `parent`, `Folder.current` and `encode`/`decode`, and read them: `exists`, `length`, the dates, `getFiles` with a mask or a function, and `open('r')` with `read`, `readln`, `readch`, `seek`, `tell` and `close`, decoding by byte order mark, `encoding`, UTF-8 or CP1252. VectorCraft's own rules: a script reads only in its own folder and below (and inside the automation read roots when they are set); any other path and a network or device path are refused before anything is looked up, and a link that leads out is refused as well (`false` or `null`, with `error` set); a file is read whole up to 8 MiB and a run reads up to 32 MiB; writing, the file dialogs and `execute` are not available yet. `crates/engine/src/tests/script_io.rs`. + - Scripts: `File` and `Folder` ([File object](https://extendscript.docsforadobe.dev/file-system-access/file-object/), [Folder object](https://extendscript.docsforadobe.dev/file-system-access/folder-object/)) name files and folders by platform or URI path, with `name`, `fsName`, `absoluteURI`, `relativeURI`, `parent`, `Folder.current` and `encode`/`decode`, and read them: `exists`, `length`, the dates, `getFiles` with a mask or a function, and `open('r')` with `read`, `readln`, `readch`, `seek`, `tell` and `close`, decoding by byte order mark, `encoding`, UTF-8 or CP1252. VectorCraft's own rules: a script reads only in its own folder and below (and inside the automation read roots when they are set); any other path and a network or device path are refused before anything is looked up, and a link that leads out is refused as well (`false` or `null`, with `error` set); a file is read whole up to 8 MiB and a run reads up to 32 MiB; `execute` is not available. `crates/engine/src/tests/script_io.rs`. + - Scripts: `File` and `Folder` write ([File object](https://extendscript.docsforadobe.dev/file-system-access/file-object/), [Folder object](https://extendscript.docsforadobe.dev/file-system-access/folder-object/)): `open('w')`, `open('e')` and `open('a')` with `write` and `writeln` by `lineFeed`, `copy`, `remove` (a folder only when empty), `rename`, `folder.create()`, the `length` and `readonly` setters, and `File.openDialog`, `File.saveDialog`, `Folder.selectDialog`, `openDlg`, `saveDlg` and `selectDlg`, with a `filter` of file types or a filter function and `multiSelect`. VectorCraft's own rules: a script writes only in `Folder.temp` (one for the run, deleted when it ends), its own `Folder.userData` next to the settings, and what a person allowed it in a file dialog, once or always; Always keeps the grant for that script file with that text by its SHA-256 and for the sources the run evaluated (`$.evalFile`, `eval`, `Function`), so a run that evaluates other code, or whose named engine holds other code, loses it first; `script.grants` lists the grants and `script.grants.revoke` removes them; the settings folder is kept out of every grant; the commands a script runs with `vc.run` read and write only in the same places and the open documents' own files; a run with nobody to ask gets `null` from the dialogs; a file is written at close or when the run ends, 8 MiB a file and 32 MiB a run, and named in `written`, also after a run that failed. `crates/engine/src/tests/script_io.rs`. - Scripts: `#strict on` (and `//@strict on`) runs the script with the checks the [`$` object](https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/) help page gives for `$.strict`: an assignment to a read-only property throws a `TypeError`, and so does a new property on an object that takes none. VectorCraft's own rules: a getter-only property counts as read-only, the objects that take no new properties are the non-extensible ones (`Object.preventExtensions`, `seal`, `freeze`, and the frozen `vc` and `$` objects), the last `#strict` line of the script and its includes sets the whole run, a file `$.evalFile` runs keeps its own line's checks for its code, and the rest of ES5 strict mode stays with `'use strict'`. Without the line, runs are unchanged. `crates/engine/src/tests/script_include.rs` (`strict_on_*`, `strict_mode_in_eval_file_is_scoped`), `crates/js/src/interp_tests.rs` (`strict_writes_are_separate_from_es5_strict`). - Scripts folder: File › Scripts lists the `.js` and `.jsx` files of the `Scripts` folder next to the preferences, each named after its file without the extension, with each subfolder as a submenu, above Check Script… and Other Script… (https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/install-and-run-scripts.html). VectorCraft's own rules: the folder is read again when the window becomes active and when the File menu opens (in the macOS menu bar, when any of its menus opens, and the new listing shows the next time the menu opens), links are not followed, and one read stops at 2,048 entries, 512 scripts, 128 subfolders, 4 levels or 250 ms. `script.listInstalled` returns the listing. `crates/engine/src/tests/script_folder.rs`, `crates/ui-egui/src/tests/scripts_menu.rs`. - Open Recent Files under `--automation-read-root`: the control channel's `ui.menu.list` and `file.recentFiles` leave out the recent files outside the read roots, the other rows keep their ids, and `file.openRecentN` for one outside them answers `no such recent file`, as an empty slot does. `crates/ui-egui/src/tests/automation.rs`. From 1f64044f1c6c2d75b91a319bbd2d9faf45d40e57 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 05:45:25 -0800 Subject: [PATCH 007/176] Web: Korean and Hindi interface text draws with real glyphs The web build had no face for Hangul or Devanagari, so a Korean or Hindi interface, and a layer or file name in either script, drew as missing-glyph boxes. - crates/text/web-fonts.txt gains a `demand` kind: NanumGothic Regular and Noto Sans Devanagari Regular are served beside the wasm like the other web faces, and fetched only when the interface language or the interface's own text needs their script. They are not fetched at startup or in the background queue. - The interface reports the characters no loaded font covers (`on_missing_glyphs`), and keeps them so that they are looked for again when the font database changes. The frame after a face arrives adds it to the interface fonts, and the frame after that draws the characters painted before it with that face. - After a failed fetch the next try comes about 30 seconds later, and the wait doubles after each further failure, for at most five tries. - A new test checks that the two faces cover every Hangul and Devanagari character the catalogs use, where craft-fonts has them. Docs: gaps.md, localization-hi.md, localization-parity.md, target-app-parity.md. --- apps/vectorcraft-web/src/api.rs | 2 +- apps/vectorcraft-web/src/demand.rs | 110 +++++++++++++++++++++++ apps/vectorcraft-web/src/fonts.rs | 59 ++++++++++-- apps/vectorcraft-web/src/main.rs | 2 + apps/vectorcraft-web/src/web.rs | 5 ++ crates/text/build.rs | 7 +- crates/text/build/web_fonts.rs | 24 +++-- crates/text/src/craft_fonts.rs | 72 ++++++++++++++- crates/text/web-fonts.txt | 4 + crates/ui-egui/src/i18n.rs | 2 +- crates/ui-egui/src/i18n/tests.rs | 30 +++++++ crates/ui-egui/src/lib.rs | 1 + crates/ui-egui/src/ui_fonts.rs | 140 +++++++++++++++++++++++++---- docs/gaps.md | 3 +- docs/localization-hi.md | 11 ++- docs/localization-parity.md | 7 +- docs/target-app-parity.md | 1 + 17 files changed, 430 insertions(+), 50 deletions(-) create mode 100644 apps/vectorcraft-web/src/demand.rs diff --git a/apps/vectorcraft-web/src/api.rs b/apps/vectorcraft-web/src/api.rs index eddd04f1b7..1be921baf3 100644 --- a/apps/vectorcraft-web/src/api.rs +++ b/apps/vectorcraft-web/src/api.rs @@ -142,7 +142,7 @@ fn send(method: &str, params: Value) -> Pin>> { }) } -async fn sleep(ms: i32) { +pub(crate) async fn sleep(ms: i32) { let promise = js_sys::Promise::new(&mut |resolve, _| { if let Some(window) = web_sys::window() { let _ = window.set_timeout_with_callback_and_timeout_and_arguments_0(&resolve, ms); diff --git a/apps/vectorcraft-web/src/demand.rs b/apps/vectorcraft-web/src/demand.rs new file mode 100644 index 0000000000..cbab6014bf --- /dev/null +++ b/apps/vectorcraft-web/src/demand.rs @@ -0,0 +1,110 @@ +//! Which `demand` web faces (`crates/text/web-fonts.txt`) to fetch: each face is fetched at most +//! once at a time and never again once it loaded. A face whose fetch failed is fetched again after +//! a wait that doubles with each failure, and not after [`MAX_TRIES`] failures. + +/// The wait after a face's first failed fetch before it is fetched again (ms). +const RETRY_MS: i32 = 30_000; +/// Failed fetches of a face after which it is not fetched again this session. +pub(crate) const MAX_TRIES: u32 = 5; + +#[derive(Clone, Copy, Debug, PartialEq)] +enum State { + Idle, + /// Being fetched, after `tries` failed fetches. + Loading { + tries: u32, + }, + Loaded, + /// `tries` fetches failed; the next may start at `retry_at` (ms). + Failed { + tries: u32, + retry_at: f64, + }, +} + +/// The fetch state of each face of a web font list, by index. +#[derive(Debug, Default)] +pub(crate) struct Demand { + states: Vec, +} + +impl Demand { + /// Of the faces `wanted` (indexes into the list), the ones to fetch at time `now` (ms): not + /// loaded, not being fetched, and not waiting to be fetched again. They are marked as being + /// fetched. + pub(crate) fn start(&mut self, wanted: &[usize], now: f64) -> Vec { + let mut out = Vec::new(); + for &i in wanted { + if self.states.len() <= i { + self.states.resize(i + 1, State::Idle); + } + let Some(state) = self.states.get_mut(i) else { continue }; + let tries = match *state { + State::Idle => Some(0), + State::Loading { .. } | State::Loaded => None, + State::Failed { tries, retry_at } => (tries < MAX_TRIES && now >= retry_at).then_some(tries), + }; + if let Some(tries) = tries { + *state = State::Loading { tries }; + out.push(i); + } + } + out + } + + /// The fetch of face `i` started by [`Demand::start`] ended at `now` (ms): loaded when `ok`. + /// Returns the wait (ms) after which a failed face may be fetched again, or `None` when it + /// loaded or has failed [`MAX_TRIES`] times. + pub(crate) fn finished(&mut self, i: usize, ok: bool, now: f64) -> Option { + let state = self.states.get_mut(i)?; + let State::Loading { tries } = *state else { return None }; + if ok { + *state = State::Loaded; + return None; + } + let tries = tries + 1; + let wait = RETRY_MS << (tries - 1).min(4); + *state = State::Failed { tries, retry_at: now + f64::from(wait) }; + (tries < MAX_TRIES).then_some(wait) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_face_is_fetched_once_and_kept() { + let mut d = Demand::default(); + assert_eq!(d.start(&[2], 0.0), [2]); + assert!(d.start(&[2], 1.0).is_empty(), "already being fetched"); + assert_eq!(d.finished(2, true, 2.0), None, "loaded: no retry"); + assert!(d.start(&[2], 1e9).is_empty(), "loaded: never fetched again"); + assert_eq!(d.start(&[0, 2, 1], 3.0), [0, 1], "other faces start on their own"); + assert_eq!(d.finished(7, false, 4.0), None, "a face never started"); + } + + #[test] + fn a_failed_face_waits_longer_after_each_failure_and_then_stops() { + let mut d = Demand::default(); + let mut now = 0.0; + // The wait after the 1st, 2nd, ... failure: doubling, up to 16 times the first. + for wait in [1, 2, 4, 8].map(|k| k * RETRY_MS) { + assert_eq!(d.start(&[0], now), [0], "at {now}"); + assert_eq!(d.finished(0, false, now), Some(wait), "the wait after the failure at {now}"); + assert!(d.start(&[0], now + f64::from(wait) - 1.0).is_empty(), "waits {wait} ms after the failure at {now}"); + now += f64::from(wait); + } + // The fifth fetch, and after it fails, none. + assert_eq!(d.start(&[0], now), [0]); + assert_eq!(d.finished(0, false, now), None, "no retry after {MAX_TRIES} failures"); + assert!(d.start(&[0], now + 1e12).is_empty(), "no fetch after {MAX_TRIES} failures"); + // A later success after failures keeps the face. + let mut d = Demand::default(); + d.start(&[1], 0.0); + assert_eq!(d.finished(1, false, 0.0), Some(RETRY_MS)); + assert_eq!(d.start(&[1], f64::from(RETRY_MS)), [1]); + assert_eq!(d.finished(1, true, f64::from(RETRY_MS)), None); + assert!(d.start(&[1], 1e12).is_empty()); + } +} diff --git a/apps/vectorcraft-web/src/fonts.rs b/apps/vectorcraft-web/src/fonts.rs index 2677c11edf..d2403e8084 100644 --- a/apps/vectorcraft-web/src/fonts.rs +++ b/apps/vectorcraft-web/src/fonts.rs @@ -1,17 +1,22 @@ //! Craft-fonts faces served beside the wasm (`fonts//…`, copied by //! `cargo xtask web-fonts`) instead of embedded: [`load_startup_fonts`] fetches the `startup` -//! ones before the app starts, [`spawn_background_fonts`] the rest once it runs. The browser checks -//! each file against its SHA-256 (Subresource Integrity). A face that fails is logged and skipped: -//! the app runs without it. With `WEB_FONTS` empty (built without craft-fonts) both do nothing. +//! ones before the app starts, [`spawn_background_fonts`] the `background` ones once it runs, and +//! [`want_chars`] a `demand` face (Korean, Devanagari) when the interface language or the +//! interface's own text needs its script. The browser checks each file against its SHA-256 +//! (Subresource Integrity). A face that fails is logged and skipped: the app runs without it. With +//! `WEB_FONTS` empty (built without craft-fonts) these do nothing. -use std::cell::Cell; +use std::cell::{Cell, RefCell}; use std::rc::Rc; +use vectorcraft_text::craft_fonts::demand_fonts; use vectorcraft_text::{FontDb, WEB_FONTS, WebFont}; use wasm_bindgen::JsCast as _; use wasm_bindgen::closure::Closure; use wasm_bindgen_futures::JsFuture; +use crate::demand::Demand; + /// Per startup face: the page shows its loading text meanwhile. const STARTUP_TIMEOUT_MS: i32 = 20_000; /// Per background face. @@ -22,12 +27,49 @@ const BACKGROUND_PARALLEL: usize = 4; thread_local! { /// The background fetch runs once per page, though a graphics restart creates the app again. static BACKGROUND_STARTED: Cell = const { Cell::new(false) }; + /// The `demand` faces' fetches. + static DEMAND: RefCell = RefCell::new(Demand::default()); + /// The running app's context, asked for a frame when a `demand` face arrives (none before the + /// app starts: its first frame looks through the faces loaded by then). + static REPAINT: RefCell> = const { RefCell::new(None) }; +} + +/// Fetch, in the background, the `demand` faces for the scripts of `chars` that are not loaded or +/// being fetched. Each one that arrives asks the app for a frame, and the interface draws those +/// characters with it from then on. Set as the interface's missing-glyph handler +/// (`vectorcraft_ui_egui::on_missing_glyphs`), and called with the interface language's name +/// before the app starts. +pub fn want_chars(chars: &[char]) { + let wanted = demand_fonts(WEB_FONTS, chars.iter().copied()); + if !wanted.is_empty() { + fetch_demand(&wanted); + } +} + +/// Fetch the `demand` faces `wanted` (indexes into `WEB_FONTS`) that [`Demand::start`] lets start. +/// A face whose fetch fails is fetched again after the wait [`Demand::finished`] gives. +fn fetch_demand(wanted: &[usize]) { + for i in DEMAND.with(|d| d.borrow_mut().start(wanted, js_sys::Date::now())) { + let Some(f) = WEB_FONTS.get(i) else { continue }; + wasm_bindgen_futures::spawn_local(async move { + let ok = load(f, BACKGROUND_TIMEOUT_MS).await; + let retry = DEMAND.with(|d| d.borrow_mut().finished(i, ok, js_sys::Date::now())); + if ok && let Some(ctx) = REPAINT.with(|r| r.borrow().clone()) { + ctx.request_repaint(); + } + if let Some(wait) = retry { + // A second longer, so a clock the browser coarsens still reads the wait as over. + crate::api::sleep(wait.saturating_add(1_000)).await; + fetch_demand(&[i]); + } + }); + } } /// Fetch and register the `startup` faces (one after the other). Returns how many loaded. pub async fn load_startup_fonts() -> usize { let mut loaded = 0; - for f in WEB_FONTS.iter().filter(|f| f.startup) { + for f in WEB_FONTS.iter().filter(|f| f.startup && !f.demand) { if load(f, STARTUP_TIMEOUT_MS).await { loaded += 1; } @@ -36,13 +78,14 @@ pub async fn load_startup_fonts() -> usize { } /// Fetch and register the `background` faces, [`BACKGROUND_PARALLEL`] at a time, asking `ctx` for -/// a frame after each so the font menus and the canvas pick it up. Only the first call does -/// anything. +/// a frame after each so the font menus and the canvas pick it up. Only the first call fetches +/// anything; each call makes `ctx` the context a `demand` face asks for a frame. pub fn spawn_background_fonts(ctx: egui::Context) { + REPAINT.with(|r| *r.borrow_mut() = Some(ctx.clone())); if BACKGROUND_STARTED.with(|s| s.replace(true)) { return; } - let queue: Rc> = Rc::new(WEB_FONTS.iter().filter(|f| !f.startup).collect()); + let queue: Rc> = Rc::new(WEB_FONTS.iter().filter(|f| !f.startup && !f.demand).collect()); let next = Rc::new(Cell::new(0usize)); for _ in 0..BACKGROUND_PARALLEL.min(queue.len()) { let (queue, next, ctx) = (queue.clone(), next.clone(), ctx.clone()); diff --git a/apps/vectorcraft-web/src/main.rs b/apps/vectorcraft-web/src/main.rs index 3808c281f9..8943e47c76 100644 --- a/apps/vectorcraft-web/src/main.rs +++ b/apps/vectorcraft-web/src/main.rs @@ -21,6 +21,8 @@ #[cfg(target_arch = "wasm32")] mod api; +#[cfg(any(target_arch = "wasm32", test))] +mod demand; #[cfg(target_arch = "wasm32")] mod fonts; #[cfg(any(target_arch = "wasm32", test))] diff --git a/apps/vectorcraft-web/src/web.rs b/apps/vectorcraft-web/src/web.rs index 2de7f3b481..6d9e0cadd5 100644 --- a/apps/vectorcraft-web/src/web.rs +++ b/apps/vectorcraft-web/src/web.rs @@ -81,6 +81,11 @@ pub fn start() { return; }; detect_language(); + // The face for a Korean or Hindi browser language (or `?lang=`) starts loading now, beside the + // startup fonts, without holding up the start. Text in those scripts painted later (a saved + // interface language, another one chosen, a layer or file name) has its face fetched then. + vectorcraft_ui_egui::on_missing_glyphs(crate::fonts::want_chars); + crate::fonts::want_chars(&i18n::system_lang().name().chars().collect::>()); wasm_bindgen_futures::spawn_local(async move { // Before the first frame, which looks for copies a crash left behind. let locks = WebLocks::start(RECOVERY_PREFIX).await; diff --git a/crates/text/build.rs b/crates/text/build.rs index 412c471c11..5402ddbe07 100644 --- a/crates/text/build.rs +++ b/crates/text/build.rs @@ -125,16 +125,19 @@ fn web_font_entries(dir: &Path) -> Result<(String, Vec), String> { missing.push(format!("{} {}", e.family, e.style)); continue; }; - let (Some(file), Some(sha)) = (row.get(2), row.get(6)) else { + let (Some(file), Some(scripts), Some(sha)) = (row.get(2), row.get(3), row.get(6)) else { return Err(format!("malformed manifest row for {} {}", e.family, e.style)); }; let integrity = web_fonts::sri(sha).ok_or_else(|| format!("bad sha256 for {} {}", e.family, e.style))?; + let scripts: Vec = scripts.split(',').map(|s| format!("{:?}", s.trim())).collect(); let _ = writeln!( out, - " WebFont {{ family: {:?}, style: {:?}, startup: {}, url: {:?}, integrity: {:?} }},", + " WebFont {{ family: {:?}, style: {:?}, startup: {}, demand: {}, scripts: &[{}], url: {:?}, integrity: {:?} }},", e.family, e.style, e.startup, + e.demand, + scripts.join(", "), web_fonts::url(sha, file), integrity, ); diff --git a/crates/text/build/web_fonts.rs b/crates/text/build/web_fonts.rs index ccd387afab..ac58913afc 100644 --- a/crates/text/build/web_fonts.rs +++ b/crates/text/build/web_fonts.rs @@ -5,8 +5,11 @@ /// One line of `web-fonts.txt`: `when | family | style`. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct Listed<'a> { - /// `startup` (fetched before the app starts) rather than `background`. + /// `startup` (fetched before the app starts). pub startup: bool, + /// `demand` (fetched when the interface needs a character of one of the face's scripts). + /// Neither this nor `startup`: `background`. + pub demand: bool, pub family: &'a str, pub style: &'a str, } @@ -23,15 +26,16 @@ pub fn parse_list(text: &str) -> Result>, String> { let [when, family, style] = fields.as_slice() else { return Err(format!("web-fonts.txt line {}: expected `when | family | style`", i + 1)); }; - let startup = match *when { - "startup" => true, - "background" => false, - other => return Err(format!("web-fonts.txt line {}: `{other}` is neither startup nor background", i + 1)), + let (startup, demand) = match *when { + "startup" => (true, false), + "background" => (false, false), + "demand" => (false, true), + other => return Err(format!("web-fonts.txt line {}: `{other}` is not startup, background or demand", i + 1)), }; if family.is_empty() || style.is_empty() { return Err(format!("web-fonts.txt line {}: empty family or style", i + 1)); } - out.push(Listed { startup, family, style }); + out.push(Listed { startup, demand, family, style }); } Ok(out) } @@ -105,12 +109,14 @@ mod tests { #[test] fn list_parsing() { - let l = parse_list("# c\n\nstartup | Noto Sans Arabic | Regular\nbackground | Amiri | Bold Italic\n").unwrap(); + let l = + parse_list("# c\n\nstartup | Noto Sans Arabic | Regular\nbackground | Amiri | Bold Italic\ndemand | NanumGothic | Regular\n").unwrap(); assert_eq!( l, [ - Listed { startup: true, family: "Noto Sans Arabic", style: "Regular" }, - Listed { startup: false, family: "Amiri", style: "Bold Italic" } + Listed { startup: true, demand: false, family: "Noto Sans Arabic", style: "Regular" }, + Listed { startup: false, demand: false, family: "Amiri", style: "Bold Italic" }, + Listed { startup: false, demand: true, family: "NanumGothic", style: "Regular" } ] ); assert!(parse_list("soon | A | B").unwrap_err().contains("line 1")); diff --git a/crates/text/src/craft_fonts.rs b/crates/text/src/craft_fonts.rs index b15b77ec72..24eef3de40 100644 --- a/crates/text/src/craft_fonts.rs +++ b/crates/text/src/craft_fonts.rs @@ -19,8 +19,13 @@ pub struct CraftFont { pub struct WebFont { pub family: &'static str, pub style: &'static str, - /// Fetched before the app starts (a fallback the first frame needs), else in the background. + /// Fetched before the app starts (a fallback the first frame needs). pub startup: bool, + /// Fetched only when the interface needs a character of one of [`WebFont::scripts`] (see + /// [`demand_fonts`]). With neither this nor `startup`, fetched in the background. + pub demand: bool, + /// ISO 15924 scripts the face is for (its craft-fonts manifest row), e.g. `"Hang"`. + pub scripts: &'static [&'static str], /// Site-relative URL, `fonts//`. pub url: &'static str, /// Subresource Integrity value, `sha256-`; the browser rejects other bytes. @@ -106,10 +111,65 @@ pub fn japanese_ui_fonts(bold: bool) -> Vec<&'static CraftFont> { v } +/// The script of `c` that a `demand` web face is fetched for: `"Hang"` for Hangul (jamo, +/// compatibility jamo, syllables and the halfwidth forms) and `"Deva"` for Devanagari (with its +/// extended blocks and the Vedic extensions). `None` for every other character. +pub fn demand_script(c: char) -> Option<&'static str> { + match c as u32 { + 0x1100..=0x11FF | 0x3130..=0x318F | 0xA960..=0xA97F | 0xAC00..=0xD7FF | 0xFFA0..=0xFFDC => Some("Hang"), + 0x0900..=0x097F | 0x1CD0..=0x1CFF | 0xA8E0..=0xA8FF | 0x11B00..=0x11B5F => Some("Deva"), + _ => None, + } +} + +/// The indexes in `fonts` of the `demand` faces for the scripts of `chars` (by +/// [`demand_script`]), each once, in `fonts` order. +pub fn demand_fonts(fonts: &[WebFont], chars: impl IntoIterator) -> Vec { + let mut scripts: Vec<&str> = Vec::new(); + for s in chars.into_iter().filter_map(demand_script) { + if !scripts.contains(&s) { + scripts.push(s); + } + } + fonts.iter().enumerate().filter(|(_, f)| f.demand && f.scripts.iter().any(|s| scripts.contains(s))).map(|(i, _)| i).collect() +} + #[cfg(test)] mod tests { use super::*; + fn web_font(family: &'static str, startup: bool, demand: bool, scripts: &'static [&'static str]) -> WebFont { + WebFont { family, style: "Regular", startup, demand, scripts, url: "", integrity: "" } + } + + #[test] + fn demand_scripts_of_hangul_and_devanagari() { + for c in ['한', '국', 'ㄱ', 'ᄀ', 'ᄀ'] { + assert_eq!(demand_script(c), Some("Hang"), "{c}"); + } + for c in ['ह', 'ि', '्', '़', '।', '\u{A8F2}'] { + assert_eq!(demand_script(c), Some("Deva"), "{c}"); + } + for c in ['A', 'é', 'ا', 'ก', 'ა', '日', 'ロ', '中'] { + assert_eq!(demand_script(c), None, "{c}"); + } + } + + #[test] + fn demand_fonts_follow_the_scripts_painted() { + let fonts = [ + web_font("Arabic", true, false, &["Arab"]), + web_font("Picked", false, false, &["Hang"]), + web_font("Korean", false, true, &["Hang", "Kore"]), + web_font("Devanagari", false, true, &["Deva"]), + ]; + assert_eq!(demand_fonts(&fonts, "한국어".chars()), [2], "Korean fetches only the Korean face"); + assert_eq!(demand_fonts(&fonts, "हिन्दी".chars()), [3], "Hindi fetches only the Devanagari face"); + assert_eq!(demand_fonts(&fonts, "हिन्दी 한국어 Layer".chars()), [2, 3], "each once, in list order"); + assert!(demand_fonts(&fonts, "English العربية 日本語".chars()).is_empty(), "other scripts fetch nothing"); + assert!(demand_fonts(&[], "한국어".chars()).is_empty(), "built without craft-fonts: nothing to fetch"); + } + #[test] fn document_fonts_keep_script_priority_and_include_every_face_once() { let font = |family, style, scripts| CraftFont { family, style, scripts, bytes: &[] }; @@ -157,7 +217,9 @@ mod tests { .collect(); assert_eq!(WEB_FONTS.len(), listed.len()); for (l, w) in listed.iter().zip(WEB_FONTS) { - assert_eq!((l.family, l.style, l.startup), (w.family, w.style, w.startup)); + assert_eq!((l.family, l.style, l.startup, l.demand), (w.family, w.style, w.startup, w.demand)); + let face = CRAFT_FONTS.iter().find(|f| f.family == w.family && f.style == w.style); + assert_eq!(face.map(|f| f.scripts), Some(w.scripts), "{} {}: the manifest's scripts", w.family, w.style); let (dir, name) = w.url.strip_prefix("fonts/").and_then(|r| r.split_once('/')).unwrap(); assert!(dir.len() == 16 && dir.bytes().all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)), "{}", w.url); assert!(name.ends_with(".ttf") || name.ends_with(".otf"), "{}", w.url); @@ -169,5 +231,11 @@ mod tests { let expected: Vec<_> = ["Noto Sans Arabic", "Noto Sans Thai", "Noto Sans Georgian"].into_iter().filter(|n| CRAFT_FONTS.iter().any(|f| f.family == *n)).collect(); assert_eq!(startup, expected); + // Korean and Devanagari faces are fetched only on demand, never at startup or in the + // background queue every session runs. + let demand: Vec<_> = WEB_FONTS.iter().filter(|w| w.demand).map(|w| w.family).collect(); + let expected: Vec<_> = ["NanumGothic", "Noto Sans Devanagari"].into_iter().filter(|n| CRAFT_FONTS.iter().any(|f| f.family == *n)).collect(); + assert_eq!(demand, expected); + assert!(WEB_FONTS.iter().all(|w| !(w.startup && w.demand))); } } diff --git a/crates/text/web-fonts.txt b/crates/text/web-fonts.txt index 7dbb8953b3..235ba98e13 100644 --- a/crates/text/web-fonts.txt +++ b/crates/text/web-fonts.txt @@ -2,6 +2,8 @@ # One face per line: when | family | style (family and style as in craft-fonts' fonts/manifest.txt). # startup = fetched before the app starts (fallbacks the first frame needs) # background = fetched after the app starts (fonts users pick by name) +# demand = fetched only when the interface language or the interface's own text needs one of +# the face's scripts (Korean, Hindi) # Read by build.rs (the WEB_FONTS table) and `cargo xtask web-fonts` (copies the files, a Trunk hook). startup | Noto Sans Arabic | Regular startup | Noto Sans Thai | Regular @@ -36,3 +38,5 @@ background | Reem Kufi | Regular background | Aref Ruqaa | Regular background | Aref Ruqaa | Bold background | Gulzar | Regular +demand | NanumGothic | Regular +demand | Noto Sans Devanagari | Regular diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index 4ec89b8e32..7481197115 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -100,7 +100,7 @@ fn plural_polish(n: u64) -> usize { pub static LANGUAGES: [LangInfo; 28] = [ LangInfo { code: "en", name: "English", source: "", plural: plural_one_other, complete_menus: false, catalog: OnceLock::new() }, // Hindi shares the integer zero/one rule with French. Desktop UI fonts are loaded lazily - // from installed faces by ui_fonts; the web needs a Devanagari font in its font set. + // from installed faces by ui_fonts; the web fetches a Devanagari craft-fonts face on demand. LangInfo { code: "hi", name: "हिन्दी", diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 66caa1c3a4..df3666bd19 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -631,6 +631,36 @@ fn bundled_fonts_cover_the_catalogs() { assert!(missing.is_empty(), "characters without a glyph: {missing:#?}"); } +/// The faces the web build fetches on demand (`web-fonts.txt`: NanumGothic for Korean, Noto Sans +/// Devanagari for Hindi) cover every character of their scripts that a catalog or a language name +/// uses. Checked where the craft-fonts checkout has them (the desktop build embeds every face). +#[test] +fn web_demand_fonts_cover_the_catalogs() { + use vectorcraft_text::craft_fonts::demand_script; + let demand: Vec<_> = vectorcraft_text::WEB_FONTS.iter().filter(|w| w.demand).collect(); + if demand.is_empty() { + eprintln!("skipped: built without craft-fonts, or one without NanumGothic and Noto Sans Devanagari"); + return; + } + let mut chars: std::collections::BTreeSet = LANGUAGES.iter().flat_map(|l| l.name.chars()).collect(); + for l in LANGUAGES.iter().filter(|l| !l.source.is_empty()) { + let (entries, _) = parse_entries(l.source); + chars.extend(entries.iter().flat_map(|(_, _, tr)| tr.chars())); + } + let mut missing = std::collections::BTreeMap::new(); + for w in demand { + let Some(f) = vectorcraft_text::CRAFT_FONTS.iter().find(|f| f.family == w.family && f.style == w.style) else { continue }; + let db = vectorcraft_text::FontDb::with_font_dirs(vec![]); + db.add_font(f.bytes.to_vec()); + let face = db.face(f.family, f.style).expect("the craft-fonts face loads"); + let gone: String = chars.iter().filter(|c| demand_script(**c).is_some_and(|s| w.scripts.contains(&s)) && !face.covers(**c)).collect(); + if !gone.is_empty() { + missing.insert(w.family, gone); + } + } + assert!(missing.is_empty(), "characters the web's demand faces lack: {missing:#?}"); +} + /// The Traditional Chinese catalog holds no Simplified-only characters (a translation written /// in the wrong script would read as a typo to every user). #[test] diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index c4c6ded189..a785625da9 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -127,6 +127,7 @@ pub use services::{ }; use state::{GeometryStamp, InputGeneration, PendingScreenshot, QueuedScreenshot}; pub(crate) use state::{InputFrame, take_frame_once}; +pub use ui_fonts::on_missing_glyphs; pub struct VectorcraftApp { pub session: Session, diff --git a/crates/ui-egui/src/ui_fonts.rs b/crates/ui-egui/src/ui_fonts.rs index ac3f260e95..e9bae8b4af 100644 --- a/crates/ui-egui/src/ui_fonts.rs +++ b/crates/ui-egui/src/ui_fonts.rs @@ -6,52 +6,95 @@ //! don't have, an installed font covering it is looked for (in the background on native) and added //! to egui's families as their last fallback, on the baseline of each family's first face, from //! the next frame on. Text the UI fonts cover costs no font loading or memory. On the web, which -//! has no system fonts, such characters stay missing-glyph boxes (Japanese too, unless built with -//! craft-fonts). +//! has no system fonts, the shell is told which characters no loaded font covers +//! ([`on_missing_glyphs`]) and fetches a face for them (Korean, Devanagari) when it has one; until +//! a face arrives they stay missing-glyph boxes (Japanese too, unless built with craft-fonts). +//! Characters no font covered are looked for again whenever the font database changes. use std::collections::HashSet; -use std::sync::Arc; +use std::sync::{Arc, OnceLock}; use egui::epaint::Shape; use egui::epaint::text::{FontInsert, FontPriority, InsertFontFamily}; use egui::{FontData, FontDefinitions, FontFamily, FontId, FontTweak, LayerId}; use vectorcraft_text::{FontDb, FontFace}; +/// Called with the painted characters no loaded or installed font covers. +static MISSING_GLYPHS: OnceLock = OnceLock::new(); + +/// Have `f` called (on the UI thread, after a frame) with the characters the interface painted +/// that no loaded or installed font covers, so it can load a font for them: the web shell fetches +/// its `demand` craft-fonts faces. A character is reported again only after the fonts change and it +/// is still not covered. The first call sets it; later calls are ignored. +pub fn on_missing_glyphs(f: fn(&[char])) { + let _ = MISSING_GLYPHS.set(f); +} + +/// What one search for fallback faces found. +struct Found { + /// The faces covering the characters looked for, each once. + faces: Vec>, + /// The characters no face covers. + uncovered: Vec, + /// [`FontDb::generation`] when the search ended. + generation: u64, +} + #[derive(Default)] pub(crate) struct UiFonts { /// Characters looked at already: the UI fonts have them, a fallback was added (or is being /// looked for), or no font has them. seen: HashSet, + /// Characters no font covered at the last search: looked for again once the font database's + /// generation is no longer [`UiFonts::searched`]. + uncovered: HashSet, + /// The font database's generation when the last search ended. + searched: u64, /// The fonts added to egui, by name. added: HashSet, /// The faces covering the characters being looked for (native: looked for on a thread). #[cfg(not(target_arch = "wasm32"))] - pending: Option>>>, + pending: Option>, } impl UiFonts { /// After a frame is laid out: add the fallback fonts found since the last frame, and look for /// fonts covering the characters this frame painted that the UI fonts lack. pub(crate) fn frame(&mut self, ctx: &egui::Context) { + self.frame_in(ctx, FontDb::global(), MISSING_GLYPHS.get().copied().unwrap_or(|_| {})); + } + + /// [`UiFonts::frame`] looking through `db`, reporting uncovered characters to `report`. + fn frame_in(&mut self, ctx: &egui::Context, db: &'static FontDb, report: fn(&[char])) { #[cfg(not(target_arch = "wasm32"))] - if let Some(faces) = self.pending.as_ref().and_then(|rx| rx.try_recv().ok()) { + if let Some(found) = self.pending.as_ref().and_then(|rx| rx.try_recv().ok()) { self.pending = None; - self.install(ctx, &faces); + self.found(ctx, found, report); + } + let mut missing = self.missing(ctx); + #[cfg(not(target_arch = "wasm32"))] + let idle = self.pending.is_none(); + #[cfg(target_arch = "wasm32")] + let idle = true; + // A font added since (a web face fetched for them) may cover them now. + if idle && !self.uncovered.is_empty() && db.generation() != self.searched { + missing.extend(self.uncovered.drain()); + missing.sort_unstable(); + missing.dedup(); } - let missing = self.missing(ctx); if missing.is_empty() { return; } let find = move || { - let mut faces: Vec> = vec![]; + let (mut faces, mut uncovered): (Vec>, Vec) = (vec![], vec![]); for c in missing { - if let Some(f) = FontDb::global().face_covering(c) - && !faces.iter().any(|x| x.id() == f.id()) - { - faces.push(f); + match db.face_covering(c) { + Some(f) if !faces.iter().any(|x| x.id() == f.id()) => faces.push(f), + Some(_) => {} + None => uncovered.push(c), } } - faces + Found { faces, uncovered, generation: db.generation() } }; // Native: the installed fonts are read off the UI thread. Characters met meanwhile wait for // the next search (they aren't marked seen until then). @@ -70,7 +113,17 @@ impl UiFonts { } // The web has only the loaded fonts to look through: quick, on this thread. #[cfg(target_arch = "wasm32")] - self.install(ctx, &find()); + self.found(ctx, find(), report); + } + + /// Add the faces a search found, and keep (and report) the characters it found no face for. + fn found(&mut self, ctx: &egui::Context, found: Found, report: fn(&[char])) { + self.install(ctx, &found.faces); + self.searched = found.generation; + if !found.uncovered.is_empty() { + report(&found.uncovered); + self.uncovered.extend(found.uncovered); + } } /// Characters painted this frame that the UI fonts lack and haven't been looked for, now @@ -135,8 +188,14 @@ impl UiFonts { /// Wait for the font search running, if any, and add what it found (tests). #[cfg(test)] pub(crate) fn finish(&mut self, ctx: &egui::Context) { - if let Some(faces) = self.pending.take().and_then(|rx| rx.recv().ok()) { - self.install(ctx, &faces); + self.finish_with(ctx, |_| {}); + } + + /// [`UiFonts::finish`], reporting uncovered characters to `report` (tests). + #[cfg(test)] + fn finish_with(&mut self, ctx: &egui::Context, report: fn(&[char])) { + if let Some(found) = self.pending.take().and_then(|rx| rx.recv().ok()) { + self.found(ctx, found, report); } } } @@ -399,8 +458,53 @@ mod tests { for c in installed { assert!(has_glyph(&ctx, c), "{c} has a glyph"); } - // Looked for once: a later frame starts no search. + // Looked for once: a later frame starts no search, unless characters no font covered are + // looked for again because the fonts changed (other tests add fonts meanwhile). + let searched = fonts.searched; frame(&ctx, &mut fonts, text); - assert!(fonts.pending.is_none()); + assert!(fonts.pending.is_none() || FontDb::global().generation() != searched, "a search with the fonts unchanged"); + } + + thread_local! { + static REPORTED: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; + } + + fn report(chars: &[char]) { + REPORTED.with(|r| r.borrow_mut().extend_from_slice(chars)); + } + + /// Run a frame painting `text` with fallbacks looked for in `db`, then wait for the search. + fn frame_in(ctx: &egui::Context, fonts: &mut UiFonts, text: &str, db: &'static FontDb) { + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| { + ui.label(text); + fonts.frame_in(ui.ctx(), db, report); + }); + out.textures_delta.clear(); + fonts.finish_with(ctx, report); + } + + /// A character painted while no font covers it is reported once, and draws once a font that + /// covers it is added (as the web fetches one), with no further search while the fonts stay + /// the same. + #[test] + fn a_font_added_later_draws_characters_painted_before_it() { + use vectorcraft_text::test_fonts::{TALL_IDEOGRAPH_FAMILY, tall_ideograph_font}; + let db: &'static FontDb = Box::leak(Box::new(FontDb::with_font_dirs(vec![]))); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut fonts = UiFonts::default(); + frame_in(&ctx, &mut fonts, "Layer 编", db); + assert!(!has_glyph(&ctx, '编'), "no font covers 编 yet"); + assert_eq!(REPORTED.with(|r| r.borrow().clone()), ['编'], "reported once"); + frame_in(&ctx, &mut fonts, "Layer 编", db); + assert!(fonts.pending.is_none() && REPORTED.with(|r| r.borrow().len()) == 1, "no new search while the fonts are the same"); + db.add_font(tall_ideograph_font().expect("the test face builds")); + assert!(db.face(TALL_IDEOGRAPH_FAMILY, "Regular").is_some()); + // The next frame looks again and adds the face; the one after draws with it. + frame_in(&ctx, &mut fonts, "Layer 编", db); + frame_in(&ctx, &mut fonts, "Layer 编", db); + assert!(has_glyph(&ctx, '编'), "the added face draws 编"); + assert!(fonts.uncovered.is_empty()); + assert_eq!(REPORTED.with(|r| r.borrow().len()), 1, "a covered character is not reported again"); } } diff --git a/docs/gaps.md b/docs/gaps.md index d34956d4e0..6601892f04 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -775,7 +775,8 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi - **Evidence:** Brazilian Portuguese catalog complete under the tests (menus, literals, messages; one|other plurals; #1914). Vietnamese catalog complete under the tests (menus, literals, messages; one plural form). Czech render-site bypasses reduced in file dialogs, diagnostics, preset names and contributor tooltips; gradient grammar and printer-mark context corrected (see [localization-parity.md](localization-parity.md)). Native review and the remaining missing-language work remain. - **Missing:** Arabic catalog and right-to-left layout; current gaps in other catalogs and native - review; Hindi wording/layout review and a web Devanagari font; a Korean UI font for the web. + review; Hindi wording/layout review. The web build fetches NanumGothic for Korean and Noto Sans + Devanagari for Hindi when the interface needs them (`crates/text/web-fonts.txt`, `demand`). Hindi now has a catalog and the pinned egui fork shapes Devanagari. Indonesian already has a catalog (see [localization-parity.md](localization-parity.md)); it is not an absent language. - **Estimate:** 50–85 h plus human review (Brazilian Portuguese completed 2026-10-14). diff --git a/docs/localization-hi.md b/docs/localization-hi.md index c130a7b088..733cfe46f0 100644 --- a/docs/localization-hi.md +++ b/docs/localization-hi.md @@ -85,9 +85,12 @@ The pinned egui fork shapes Devanagari with HarfRust. The desktop's existing `Ui finds an installed covering face, such as Nirmala UI, Kohinoor Devanagari or Noto Sans Devanagari. If a `CRAFT_FONTS_DIR` build includes a face tagged `Deva`, it is also installed at the end of each UI font family. No font binaries are added to this repository. Without either an embedded -or installed covering face, Hindi cannot display correctly. The web has no system fonts and -needs a Devanagari face supplied through craft-fonts; this catalog alone does not supply one. +or installed covering face, Hindi cannot display correctly. The web has no system fonts. A web +build made with craft-fonts serves Noto Sans Devanagari Regular beside the wasm and fetches it +when the interface language is Hindi or the interface paints Devanagari +(`crates/text/web-fonts.txt`, `demand`); until it arrives, Devanagari draws as missing-glyph boxes. +Other languages do not fetch it. Before release: native-speaker review of the draft (especially less common labels and error -messages), visual checks for clipped labels and matras at different UI scales, and a web-font -build. Reviewers should use this glossary to make terminology corrections consistently. +messages), and visual checks for clipped labels and matras at different UI scales, on the +desktop and on the web. Reviewers should use this glossary to make terminology corrections consistently. diff --git a/docs/localization-parity.md b/docs/localization-parity.md index 25dd92d552..3108b32140 100644 --- a/docs/localization-parity.md +++ b/docs/localization-parity.md @@ -29,20 +29,19 @@ Chinese by `imachus`). Only Georgian is recorded as reviewed by a native speaker | English | `en` | source, 100% | all | Latin | — | full | — | | Simplified Chinese (Mandarin) | `zh-hans` | 5,102 rows, 791 of them `@msg` (counted 2026-10-21): menus, `tl!` literals and messages complete when counted | all | CJK UI font from craft-fonts (BIZ UDPGothic) when embedded, else a system font; IME with marked text at the caret; vertical type partial ([type-parity.md](type-parity.md)) | no | full | — (review) | | Spanish | `es` | 4,009 / 4,020 (99.7%) | all (604 messages) | Latin | no | full | — (review) | -| Hindi | `hi` | 7,877 rows (2026-11-06): 2,537 `@msg`, 45 `@msgplural`, 38 `@plural`; no gaps in the untranslated report | menus, dialogs, tooltips and scanned messages; contributor-approved loanword terminology; agent wording pass | UI and document text shape with HarfRust; installed desktop Devanagari fallback, or a `Deva` craft-fonts face; web font still needed | contributor terminology review; wider proofread welcome | complete catalog, machine-assisted draft | native review, layout and web font | +| Hindi | `hi` | 7,877 rows (2026-11-06): 2,537 `@msg`, 45 `@msgplural`, 38 `@plural`; no gaps in the untranslated report | menus, dialogs, tooltips and scanned messages; contributor-approved loanword terminology; agent wording pass | UI and document text shape with HarfRust; installed desktop Devanagari fallback, or a `Deva` craft-fonts face; the web fetches Noto Sans Devanagari when the interface needs it | contributor terminology review; wider proofread welcome | complete catalog, machine-assisted draft | native review and layout | | Arabic | `ar` | 0 | none | document text: bidi layout and Paragraph Direction; interface: no right-to-left layout, no Arabic shaping in egui | no | none | 25–40 | | French | `fr` | 4,020 / 4,020 (100%) | all | Latin | no | full | — (review) | | Portuguese | `pt-br` | 6,106 catalog entries (counted 2026-10-31 on `main` at `d26dd933a`): menus, `tl!` literals and messages complete when counted; one/other plurals | all | Latin | contributor is a Brazilian Portuguese speaker; further native review welcome | full | — (review) | | Indonesian | `id` | 5,279 rows, 750 of them `@msg` (counted 2026-10-21): menus and `tl!` literals complete when counted; its messages are partial; one plural form | dialogs and tooltips all; 750 message rows (French has 796) | Latin | no | full | — (review) | | Japanese | `ja` | 4,004 / 4,020 (99.6%) | all | CJK UI font as above; Japanese IME; vertical type partial; Japanese crop marks and composition settings | no | full | — (review) | | German | `de` | 3,952 / 4,020 (98%; menus, literals and messages complete when counted) | all (602 of 604 message rows; landed 2026-10-10) | Latin | contributor-written, not reviewed | full | — (review) | -| Korean | `ko` | 4,870 rows (counted 2026-10-21): menus, `tl!` literals and messages complete when counted; one plural form | all | Hangul from an installed system font on the desktop (Apple SD Gothic Neo, Malgun Gothic, Noto Sans CJK KR…); the web build has no Korean UI font yet (craft-fonts); IME path exists | no (AI-drafted) | full | — (review; web font) | +| Korean | `ko` | 4,870 rows (counted 2026-10-21): menus, `tl!` literals and messages complete when counted; one plural form | all | Hangul from an installed system font on the desktop (Apple SD Gothic Neo, Malgun Gothic, Noto Sans CJK KR…); the web build fetches NanumGothic from craft-fonts when the interface needs it; IME path exists | no (AI-drafted) | full | — (review) | | Vietnamese | `vi` | 4,886 rows (counted 2026-10-21): menus, `tl!` literals and messages complete when counted; one plural form; 4,046 plain + 18 `@plural` + 28 contextual + 794 `@msg` | all | Latin with Vietnamese diacritics (stacked marks attach in precomposed, decomposed and keyboard forms, #4491; glyph tests pass) | contributor is a Vietnamese speaker; AI-assisted draft, further native review welcome | full | — (review) | **Historical 12-language score: ~82%** (equal weights: 100 + 85 + 100 + 0 + 0 + 100 + 100 + 100 + 100 + 98 + 100 + 100, over 12). **To `full` for all twelve: ~50–85 h** (historical estimate, not re-scored here). Hindi now has -a complete catalog and UI shaping; its remaining work is native review, layout checking and the -web font. Arabic still needs its catalog and right-to-left interface. Each new Latin-script catalog is ~4,000 rows; the existing ones were written in a few agent hours each +a complete catalog and UI shaping; its remaining work is native review and layout checking. Arabic still needs its catalog and right-to-left interface. Each new Latin-script catalog is ~4,000 rows; the existing ones were written in a few agent hours each plus review. Native-speaker review is human work and isn't in the hours. ## Other shipped languages diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f04ee3c910..dd5fb374e4 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1293,6 +1293,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur With Line-end Punctuation Half Width, both composers measure a line with its last character set as narrow as Mojikumi sets it ([the help page](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/use-mojikumi-for-japanese-text-composition.html)): a closing bracket, comma or full stop that fits at half width ends the line, and the character before it no longer goes to the next line with it. A mark that already lost its half to the punctuation after it and a line that ends in a hyphen take nothing more off, and the quarter em between Japanese and Latin text counts only where the line ends there. Kinsoku Shori Type and Burasagari Regular measure lines the same way; right-to-left lines and Mojikumi None break as before. In a frame that is not a rectangle, or with text wrap, a line's first word is measured as it is set (an opening bracket at its start flush, its last character narrowed) when layout looks for a line wide enough for it, and it ends only where the line may break, so kinsoku keeps an opening bracket with the character after it and a No Break run counts whole (`crates/text/src/layout/wrapping_tests.rs`, `crates/text/src/tests/vertical.rs`). Scores and estimates are unchanged. The Paragraph panel's Mojikumi Set lists the five predefined sets the help page names (None, YakumonoHankaku, GyomatsuYakumonoHankaku, GyomatsuYakumonoZenkaku and YakumonoZenkaku), then Line-end Punctuation Half Width, and `text.setFormat {mojikumi}` takes each of them. YakumonoHankaku sets every bracket, comma and full stop half width and takes a quarter em off each side of a middle dot; GyomatsuYakumonoHankaku keeps punctuation full width inside a line, sets an opening bracket flush at a line's start and a closing mark half width at its end, and takes the quarter em after a middle dot off at a line's end; GyomatsuYakumonoZenkaku keeps punctuation full width and adds a quarter em between Japanese and Latin text; YakumonoZenkaku sets characters as None does. These widths are VectorCraft's own rules, from the help page's one-line description of each set. Both composers and vertical type measure each line as it is set, the sets save with the document and paragraph styles, and a `.ai` save reports the new sets as left out (`crates/text/src/tests/vertical.rs`, `crates/ui-egui/src/panels/paragraph/tests.rs`). Scores and estimates are unchanged. Interface text in characters the interface's fonts lack, drawn in a bundled Japanese, Georgian or Devanagari face or in an installed font that covers them, sits on the baseline of the Latin text beside it, monospace text included (#5816; `crates/ui-egui/src/ui_fonts.rs`, `crates/ui-egui/src/theme.rs`). + On the web, Korean and Hindi interface text draws with real glyphs: a web build made with craft-fonts fetches NanumGothic for Hangul (about 2 MB) or Noto Sans Devanagari (about 280 KB) only when the interface language or the interface's own text (a layer or file name, the language picker) needs that script. The frame after the face arrives adds it to the interface fonts, and the frame after that draws the characters painted before it with that face. Sessions in other languages do not download them at startup. After a failed fetch the next try comes about 30 seconds later, and the wait doubles after each further failure, for at most five tries (`crates/text/web-fonts.txt`, `apps/vectorcraft-web/src/fonts.rs`, `apps/vectorcraft-web/src/demand.rs`, `crates/ui-egui/src/ui_fonts.rs`). Character panel menu › Standard Vertical Roman Alignment (with the East Asian options; `text.setFormat` or `text.setRangeStyle {standardVerticalRoman}`, off by default) stands the selected Latin letters, digits and other half-width characters upright one below the other in vertical type instead of rotating them ([formatting Asian characters](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html)); spaces keep their width, tate-chu-yoko blocks stay across the column, and Character Style Options gives it its own checkbox beside Character Alignment. Character panel menu › Tate-chu-yoko Settings… (with the East Asian options; `ui.tateChuYokoSettings`, `text.setFormat` or `text.setRangeStyle {tcyUpDown, tcyLeftRight}`, in points, 0 by default) moves a marked tate-chu-yoko block in vertical type up by a positive Up/Down and right by a positive Left/Right ([format East Asian characters in vertical text](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/format-east-asian-characters-in-vertical-text.html), [formatting Asian characters](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html)); the block moves as one piece with its first character's values and keeps its one em down the column, on a vertical path it moves toward the path's start and to the path's left, automatic digit blocks do not move, Reset Panel sets both back to 0, and character styles and the native file keep them. A file whose character styles hold a Tate-chu-yoko Up/Down or Left/Right offset past the coordinate limit (`MAX_COORD`) either way opens with the nearer end, as the type's own offsets do; an offset within it stays as saved. From db26ce4a945368723aec538608c6c595626609ef Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 07:11:22 -0800 Subject: [PATCH 008/176] Tests: the script report test allows its script the folder it writes in A script now writes only in its own folders and in what a person allowed it, so the ui.inspect script report test picks the test folder in the script's folder dialog before the script exports into it. --- crates/ui-egui/src/tests/automation.rs | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/tests/automation.rs b/crates/ui-egui/src/tests/automation.rs index d7f438d285..3683ec1ae7 100644 --- a/crates/ui-egui/src/tests/automation.rs +++ b/crates/ui-egui/src/tests/automation.rs @@ -1004,22 +1004,26 @@ fn ui_inspect_keeps_text_that_only_looks_like_a_library_id() { let _ = std::fs::remove_dir_all(base); } -/// `ui.inspect`'s `scriptReport` names a file the person's script wrote outside the read root, and -/// the included file a failed run stopped in (also in its error line), by its file name; the person -/// sees the paths. +/// `ui.inspect`'s `scriptReport` names a file the person's script wrote outside the read root (in +/// the folder the person allowed it), and the included file a failed run stopped in (also in its +/// error line), by its file name; the person sees the paths. #[test] fn ui_inspect_script_report_leaves_out_files_outside_the_read_root() { let (mut app, tx, base) = confined("inspect-script-report"); let (kept, hidden) = (s(base.join("in/kept.svg")), s(base.join("outside/hidden.svg"))); app.session.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); let source = format!( - "vc.run('document.export', {{path: {kept}, format: 'svg'}}); vc.run('document.export', {{path: {hidden}, format: 'svg'}});", + "Folder.selectDialog('Folder'); vc.run('document.export', {{path: {kept}, format: 'svg'}}); vc.run('document.export', {{path: {hidden}, format: 'svg'}});", kept = json!(kept), hidden = json!(hidden) ); let finish = |app: &mut VectorcraftApp, params: Value| { app.session.execute("script.run", ¶ms).unwrap(); for _ in 0..10_000 { + if app.session.script_picker().is_some() { + let paths = vec![s(base.clone())]; + assert!(app.session.script_pick(vectorcraft_engine::script::files::PickAnswer::Allow { paths, always: false })); + } if app.session.script_pump().is_some() { break; } From 3b072ad0785756deb10a46e25c64f9cd1c9e12d6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 07:19:20 -0800 Subject: [PATCH 009/176] Tests: the font-added-later test uses a character no craft-fonts face covers MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit a_font_added_later_draws_characters_painted_before_it painted 编, which Noto Sans CJK SC covers. With craft-fonts embedded (as in CI), the test's font database already held that face, so nothing was reported and the test failed. It now paints U+F0000, a private-use character, drawn by a new test face (test_fonts::private_use_font) that maps only it. --- crates/text/src/test_fonts.rs | 13 +++++++++++++ crates/ui-egui/src/ui_fonts.rs | 24 +++++++++++++----------- 2 files changed, 26 insertions(+), 11 deletions(-) diff --git a/crates/text/src/test_fonts.rs b/crates/text/src/test_fonts.rs index 8c53e29a04..07af6e2d8d 100644 --- a/crates/text/src/test_fonts.rs +++ b/crates/text/src/test_fonts.rs @@ -1322,6 +1322,19 @@ fn remapped_source_sans(family: &str, postscript: &str, mapping: &[(char, char)] Some(builder.build()) } +/// The family of [`private_use_font`]. +pub const PRIVATE_USE_FAMILY: &str = "Private Use Sans"; + +/// The character [`private_use_font`] maps: the first code point of Supplementary Private Use +/// Area-A, which no bundled or craft-fonts face covers. +pub const PRIVATE_USE_CHAR: char = '\u{F0000}'; + +/// A face that maps only [`PRIVATE_USE_CHAR`] to the bundled Source Sans 3 `H` outline, for tests +/// that need a character no other font covers, with or without craft-fonts. +pub fn private_use_font() -> Option> { + remapped_source_sans(PRIVATE_USE_FAMILY, "PrivateUseSans-Regular", &[(PRIVATE_USE_CHAR, 'H')]) +} + /// The family of [`tall_ideograph_font`]. pub const TALL_IDEOGRAPH_FAMILY: &str = "Tall Ideograph Sans"; diff --git a/crates/ui-egui/src/ui_fonts.rs b/crates/ui-egui/src/ui_fonts.rs index e9bae8b4af..63ac7b5fc2 100644 --- a/crates/ui-egui/src/ui_fonts.rs +++ b/crates/ui-egui/src/ui_fonts.rs @@ -485,25 +485,27 @@ mod tests { /// A character painted while no font covers it is reported once, and draws once a font that /// covers it is added (as the web fetches one), with no further search while the fonts stay - /// the same. + /// the same. The character is a private-use one, which no craft-fonts face covers either (the + /// database holds them when the build embeds craft-fonts). #[test] fn a_font_added_later_draws_characters_painted_before_it() { - use vectorcraft_text::test_fonts::{TALL_IDEOGRAPH_FAMILY, tall_ideograph_font}; + use vectorcraft_text::test_fonts::{PRIVATE_USE_CHAR, PRIVATE_USE_FAMILY, private_use_font}; let db: &'static FontDb = Box::leak(Box::new(FontDb::with_font_dirs(vec![]))); let ctx = egui::Context::default(); crate::theme::install_fonts(&ctx); let mut fonts = UiFonts::default(); - frame_in(&ctx, &mut fonts, "Layer 编", db); - assert!(!has_glyph(&ctx, '编'), "no font covers 编 yet"); - assert_eq!(REPORTED.with(|r| r.borrow().clone()), ['编'], "reported once"); - frame_in(&ctx, &mut fonts, "Layer 编", db); + let text = format!("Layer {PRIVATE_USE_CHAR}"); + frame_in(&ctx, &mut fonts, &text, db); + assert!(!has_glyph(&ctx, PRIVATE_USE_CHAR), "no font covers the character yet"); + assert_eq!(REPORTED.with(|r| r.borrow().clone()), [PRIVATE_USE_CHAR], "reported once"); + frame_in(&ctx, &mut fonts, &text, db); assert!(fonts.pending.is_none() && REPORTED.with(|r| r.borrow().len()) == 1, "no new search while the fonts are the same"); - db.add_font(tall_ideograph_font().expect("the test face builds")); - assert!(db.face(TALL_IDEOGRAPH_FAMILY, "Regular").is_some()); + db.add_font(private_use_font().expect("the test face builds")); + assert!(db.face(PRIVATE_USE_FAMILY, "Regular").is_some()); // The next frame looks again and adds the face; the one after draws with it. - frame_in(&ctx, &mut fonts, "Layer 编", db); - frame_in(&ctx, &mut fonts, "Layer 编", db); - assert!(has_glyph(&ctx, '编'), "the added face draws 编"); + frame_in(&ctx, &mut fonts, &text, db); + frame_in(&ctx, &mut fonts, &text, db); + assert!(has_glyph(&ctx, PRIVATE_USE_CHAR), "the added face draws the character"); assert!(fonts.uncovered.is_empty()); assert_eq!(REPORTED.with(|r| r.borrow().len()), 1, "a covered character is not reported again"); } From d4912493296dd7889c94a792894681ba18b8aefb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 07:41:08 -0800 Subject: [PATCH 010/176] Web: a clock set back after a failed font fetch no longer stops its retry The demand-font retry deadlines were read from the wall clock. If the system clock went back after a fetch failed, the retry timer fired but the deadline still lay ahead, so the face was never fetched again that session. The deadlines now use the monotonic clock (now_ms), and a retry also starts when the clock reads earlier than the failure. --- apps/vectorcraft-web/src/demand.rs | 20 +++++++++++++++++--- apps/vectorcraft-web/src/fonts.rs | 4 ++-- 2 files changed, 19 insertions(+), 5 deletions(-) diff --git a/apps/vectorcraft-web/src/demand.rs b/apps/vectorcraft-web/src/demand.rs index cbab6014bf..d2a2317bd3 100644 --- a/apps/vectorcraft-web/src/demand.rs +++ b/apps/vectorcraft-web/src/demand.rs @@ -15,9 +15,11 @@ enum State { tries: u32, }, Loaded, - /// `tries` fetches failed; the next may start at `retry_at` (ms). + /// `tries` fetches failed, the last at `failed_at` (ms); the next may start at `retry_at`, or + /// at once when the clock reads earlier than `failed_at`. Failed { tries: u32, + failed_at: f64, retry_at: f64, }, } @@ -42,7 +44,7 @@ impl Demand { let tries = match *state { State::Idle => Some(0), State::Loading { .. } | State::Loaded => None, - State::Failed { tries, retry_at } => (tries < MAX_TRIES && now >= retry_at).then_some(tries), + State::Failed { tries, failed_at, retry_at } => (tries < MAX_TRIES && (now >= retry_at || now < failed_at)).then_some(tries), }; if let Some(tries) = tries { *state = State::Loading { tries }; @@ -64,7 +66,7 @@ impl Demand { } let tries = tries + 1; let wait = RETRY_MS << (tries - 1).min(4); - *state = State::Failed { tries, retry_at: now + f64::from(wait) }; + *state = State::Failed { tries, failed_at: now, retry_at: now + f64::from(wait) }; (tries < MAX_TRIES).then_some(wait) } } @@ -107,4 +109,16 @@ mod tests { assert_eq!(d.finished(1, true, f64::from(RETRY_MS)), None); assert!(d.start(&[1], 1e12).is_empty()); } + + /// A clock that reads earlier than the failure (one set back meanwhile) does not hold the + /// retry back: the timer that asks for it has waited already. + #[test] + fn a_clock_set_back_after_a_failure_does_not_stop_the_retry() { + let mut d = Demand::default(); + let failed_at = 1e12; + d.start(&[0], failed_at); + assert_eq!(d.finished(0, false, failed_at), Some(RETRY_MS)); + assert!(d.start(&[0], failed_at + 1.0).is_empty(), "still waiting"); + assert_eq!(d.start(&[0], failed_at - 3_600_000.0), [0], "the clock went back an hour"); + } } diff --git a/apps/vectorcraft-web/src/fonts.rs b/apps/vectorcraft-web/src/fonts.rs index d2403e8084..873474f6c3 100644 --- a/apps/vectorcraft-web/src/fonts.rs +++ b/apps/vectorcraft-web/src/fonts.rs @@ -49,11 +49,11 @@ pub fn want_chars(chars: &[char]) { /// Fetch the `demand` faces `wanted` (indexes into `WEB_FONTS`) that [`Demand::start`] lets start. /// A face whose fetch fails is fetched again after the wait [`Demand::finished`] gives. fn fetch_demand(wanted: &[usize]) { - for i in DEMAND.with(|d| d.borrow_mut().start(wanted, js_sys::Date::now())) { + for i in DEMAND.with(|d| d.borrow_mut().start(wanted, vectorcraft_ui_egui::now_ms())) { let Some(f) = WEB_FONTS.get(i) else { continue }; wasm_bindgen_futures::spawn_local(async move { let ok = load(f, BACKGROUND_TIMEOUT_MS).await; - let retry = DEMAND.with(|d| d.borrow_mut().finished(i, ok, js_sys::Date::now())); + let retry = DEMAND.with(|d| d.borrow_mut().finished(i, ok, vectorcraft_ui_egui::now_ms())); if ok && let Some(ctx) = REPAINT.with(|r| r.borrow().clone()) { ctx.request_repaint(); } From eb1f29f94bcc66f4362b9dd448f43b3012005afe Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 07:56:02 -0800 Subject: [PATCH 011/176] Scripts: a script in the settings folder reads only its own file there A script run from a file directly in the settings folder could read every file in that folder, Script Grants.json included, because its own folder was left open inside the fence. Only folders below the settings folder stay open now, and a script in the settings folder itself reads only its own file there. --- crates/engine/src/script/files.rs | 10 ++++++++-- crates/engine/src/tests/script_io.rs | 19 +++++++++++++++++++ 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index 37f3b93213..258d5a2863 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -79,7 +79,7 @@ use std::sync::atomic::{AtomicU32, Ordering}; use vectorcraft_js::{Data, HostError, HostItem, Realm, RunError}; use super::{Host, bump}; -use crate::file_access::{ScriptRead, ScriptScope}; +use crate::file_access::{ScriptRead, ScriptScope, path_inside}; /// The most bytes of one file a script opens. pub const MAX_FILE_BYTES: usize = 8 << 20; @@ -331,7 +331,13 @@ impl Disk { let _ = d.saw(hash); } if let Some(f) = fenced { - let own = d.scope.roots().to_vec(); + // A script's folder inside the settings folder stays open; the settings folder itself + // does not, only the script's own file there. + let roots = d.scope.roots(); + let mut own: Vec = roots.iter().filter(|r| !path_inside(&f, r)).cloned().collect(); + if roots.iter().any(|r| path_inside(r, &f) && path_inside(&f, r)) { + own.extend(d.script.as_ref().map(|(p, _)| p.clone())); + } d.scope.fence(f.clone(), &own); d.writes.fence(f, &[]); } diff --git a/crates/engine/src/tests/script_io.rs b/crates/engine/src/tests/script_io.rs index 0d09bd2796..e3e7ade3a2 100644 --- a/crates/engine/src/tests/script_io.rs +++ b/crates/engine/src/tests/script_io.rs @@ -1108,6 +1108,25 @@ fn script_files_in_a_folder_above_the_settings_folder_do_not_reach_it() { let _ = std::fs::remove_dir_all(base); } +/// A script run from the settings folder itself reads its own file there, but no other file in the +/// settings folder. +#[test] +fn script_files_in_the_settings_folder_do_not_reach_it() { + let base = folder("insettings"); + let mut s = Session::new(); + s.attach_script_data(base.join("main/Script Data")); + write(&base.join("main/Script Grants.json"), b"{\"version\": 1, \"grants\": []}"); + let r = run_in( + &mut s, + &base, + "var a = new File('main.jsx'), g = new File('Script Grants.json');\n\ + var out = [a.open('r'), a.read().length > 0]; a.close(); out.push(g.open('r'), g.error, g.exists); vc.log(out);", + ) + .unwrap(); + assert_eq!(r["log"], json!([[true, true, false, DENIED, false]])); + let _ = std::fs::remove_dir_all(base); +} + /// The settings folder is kept out of every grant also before it has been made. #[test] fn script_file_grants_never_reach_a_settings_folder_not_made_yet() { From 679d4ac03c1bdd8d58d2bb3893139e3eb6cd10a5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 08:22:54 -0800 Subject: [PATCH 012/176] UI fonts: a font added during a fallback search has its characters looked for again The search for fallback faces now reads the font database's generation before its lookups instead of after them. When a font is added while the search runs, the generation kept is older than the database's, so the next frame looks again for the characters the search did not find. --- crates/ui-egui/src/ui_fonts.rs | 60 ++++++++++++++++++++++++++-------- 1 file changed, 47 insertions(+), 13 deletions(-) diff --git a/crates/ui-egui/src/ui_fonts.rs b/crates/ui-egui/src/ui_fonts.rs index 63ac7b5fc2..fd994fa6bf 100644 --- a/crates/ui-egui/src/ui_fonts.rs +++ b/crates/ui-egui/src/ui_fonts.rs @@ -36,10 +36,26 @@ struct Found { faces: Vec>, /// The characters no face covers. uncovered: Vec, - /// [`FontDb::generation`] when the search ended. + /// [`FontDb::generation`] when the search started. generation: u64, } +/// Look in `db` for the faces covering `chars`, each through `lookup`. +fn search(db: &FontDb, chars: Vec, lookup: impl Fn(&FontDb, char) -> Option>) -> Found { + // Read before the lookups: when a font is added during them, the generation kept is older than + // the database's, and the characters not found are looked for again. + let generation = db.generation(); + let (mut faces, mut uncovered): (Vec>, Vec) = (vec![], vec![]); + for c in chars { + match lookup(db, c) { + Some(f) if !faces.iter().any(|x| x.id() == f.id()) => faces.push(f), + Some(_) => {} + None => uncovered.push(c), + } + } + Found { faces, uncovered, generation } +} + #[derive(Default)] pub(crate) struct UiFonts { /// Characters looked at already: the UI fonts have them, a fallback was added (or is being @@ -48,7 +64,7 @@ pub(crate) struct UiFonts { /// Characters no font covered at the last search: looked for again once the font database's /// generation is no longer [`UiFonts::searched`]. uncovered: HashSet, - /// The font database's generation when the last search ended. + /// The font database's generation when the last search started. searched: u64, /// The fonts added to egui, by name. added: HashSet, @@ -85,17 +101,7 @@ impl UiFonts { if missing.is_empty() { return; } - let find = move || { - let (mut faces, mut uncovered): (Vec>, Vec) = (vec![], vec![]); - for c in missing { - match db.face_covering(c) { - Some(f) if !faces.iter().any(|x| x.id() == f.id()) => faces.push(f), - Some(_) => {} - None => uncovered.push(c), - } - } - Found { faces, uncovered, generation: db.generation() } - }; + let find = move || search(db, missing, FontDb::face_covering); // Native: the installed fonts are read off the UI thread. Characters met meanwhile wait for // the next search (they aren't marked seen until then). #[cfg(not(target_arch = "wasm32"))] @@ -491,6 +497,9 @@ mod tests { fn a_font_added_later_draws_characters_painted_before_it() { use vectorcraft_text::test_fonts::{PRIVATE_USE_CHAR, PRIVATE_USE_FAMILY, private_use_font}; let db: &'static FontDb = Box::leak(Box::new(FontDb::with_font_dirs(vec![]))); + // Scanned first, as the app's database is at startup: a first scan during the search would + // change the generation and start one more search. + db.families(); let ctx = egui::Context::default(); crate::theme::install_fonts(&ctx); let mut fonts = UiFonts::default(); @@ -509,4 +518,29 @@ mod tests { assert!(fonts.uncovered.is_empty()); assert_eq!(REPORTED.with(|r| r.borrow().len()), 1, "a covered character is not reported again"); } + + /// A font added while a search runs (another thread loading one) leaves the search's generation + /// older than the database's, so the next frame looks again for the characters it did not find. + #[test] + fn a_font_added_during_a_search_has_its_characters_looked_for_again() { + use vectorcraft_text::test_fonts::{PRIVATE_USE_CHAR, private_use_font}; + let db: &'static FontDb = Box::leak(Box::new(FontDb::with_font_dirs(vec![]))); + let found = search(db, vec![PRIVATE_USE_CHAR], |db, c| { + let face = db.face_covering(c); + db.add_font(private_use_font().expect("the test face builds")); + face + }); + assert_eq!(found.uncovered, [PRIVATE_USE_CHAR], "the lookup ran before the font was added"); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut fonts = UiFonts::default(); + fonts.found(&ctx, found, |_| {}); + // Painted before: the character is looked for again only because the fonts changed. + fonts.seen.insert(PRIVATE_USE_CHAR); + let text = format!("Layer {PRIVATE_USE_CHAR}"); + frame_in(&ctx, &mut fonts, &text, db); + frame_in(&ctx, &mut fonts, &text, db); + assert!(has_glyph(&ctx, PRIVATE_USE_CHAR), "the added face draws the character"); + assert!(fonts.uncovered.is_empty()); + } } From ea21d344c9f133f590a90b1a04ea4cee88fafe72 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 08:36:36 -0800 Subject: [PATCH 013/176] i18n: Dutch rows for script file access messages --- crates/ui-egui/src/i18n/nl.tsv | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index df8847ea77..f1e6c1fc37 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -83,6 +83,27 @@ @msg Script file path exceeds 32,767 characters Het pad van het scriptbestand is langer dan 32.767 tekens @msg Script folder mask takes too many steps to match Het masker van de scriptmap vraagt te veel stappen om te vergelijken @msg the script opened more file data than one run may open (32 MiB) het script heeft meer bestandsgegevens geopend dan één uitvoering mag openen (32 MiB) +@msg Script file access denied: {path} Toegang tot het scriptbestand geweigerd: {path} +@msg Script file access to the app's own folders is not allowed Scriptbestanden mogen geen toegang krijgen tot de eigen mappen van de app +@msg Script file cannot encode the text Het scriptbestand kan de tekst niet coderen +@msg Script file could not be written Het scriptbestand kon niet worden geschreven +@msg Script file dialogs need a person to answer them Dialoogvensters voor scriptbestanden moeten door een persoon worden beantwoord +@msg Script file is not open for writing Het scriptbestand is niet geopend voor schrijven +@msg Script file name is already in use De naam van het scriptbestand is al in gebruik +@msg Script file name must be a name without a folder De naam van het scriptbestand moet een naam zonder map zijn +@msg Script file permission can be kept only for a script run from a file Toestemming voor scriptbestanden kan alleen worden bewaard voor een script dat vanuit een bestand wordt uitgevoerd +@msg Script file permission could not be saved De toestemming voor het scriptbestand kon niet worden opgeslagen +@msg Script folder is not empty De scriptmap is niet leeg +@msg Script files cannot make aliases Scriptbestanden kunnen geen aliassen maken +@msg Script file hidden setting cannot be changed De instelling Verborgen van het scriptbestand kan niet worden gewijzigd +@msg {name}: a file dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: een bestandsdialoogvenster kan niet worden geopend binnen een callback van een ingebouwde functie, een getter, een conversie of een bestand dat door $.evalFile wordt uitgevoerd; roep het aan vanuit de eigen code van het script +@msg the script wrote more file data than one run may write (32 MiB) het script heeft meer bestandsgegevens geschreven dan één uitvoering mag schrijven (32 MiB) +@msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` voor het bestandsdialoogvenster van een script moet een van deze waarden zijn: once, always, deny, stop +@msg choose a file or folder first, or deny kies eerst een bestand of map, of weiger +@msg the script file permissions could not be saved: {e} de toestemmingen voor scriptbestanden konden niet worden opgeslagen: {e} +@msg this script's file access can be allowed only once de bestandstoegang van dit script kan maar één keer worden toegestaan +@msg Only the person at the keyboard can allow a script's file access Alleen de persoon aan het toetsenbord kan de bestandstoegang van een script toestaan +@msg A script is given at most 2,048 files: the files picked after them were left out Een script krijgt maximaal 2.048 bestanden: de bestanden die daarna zijn gekozen, zijn weggelaten @msg File.seek: takes a position and a mode File.seek: verwacht een positie en een modus @msg vc.run: give a command id, as a string vc.run: geef een opdracht-id, als string @msg vc.run: takes a command id and an object of parameters vc.run: verwacht een opdracht-id en een object met parameters From 4f8e1d5ed2d59ce6c0c4f5d2f50a4fe8075546dc Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 08:48:48 -0800 Subject: [PATCH 014/176] i18n: Hindi script file messages use the glossary term for save --- crates/ui-egui/src/i18n/hi.tsv | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index b01e66ed4f..07ff5595c2 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -6614,7 +6614,7 @@ antiAlias Sharp शार्प @msg Script file name is already in use स्क्रिप्ट फ़ाइल का नाम पहले से उपयोग में है @msg Script file name must be a name without a folder स्क्रिप्ट फ़ाइल का नाम बिना फ़ोल्डर वाला नाम होना चाहिए @msg Script file permission can be kept only for a script run from a file फ़ाइल अनुमति केवल फ़ाइल से चलाई गई स्क्रिप्ट के लिए रखी जा सकती है -@msg Script file permission could not be saved स्क्रिप्ट की फ़ाइल अनुमति सहेजी नहीं जा सकी +@msg Script file permission could not be saved स्क्रिप्ट की फ़ाइल अनुमति सेव नहीं की जा सकी @msg Script folder is not empty स्क्रिप्ट फ़ोल्डर खाली नहीं है @msg Script files cannot make aliases स्क्रिप्ट फ़ाइलें उपनाम नहीं बना सकतीं @msg Script file hidden setting cannot be changed स्क्रिप्ट फ़ाइल की छिपी सेटिंग बदली नहीं जा सकती @@ -6622,7 +6622,7 @@ antiAlias Sharp शार्प @msg the script wrote more file data than one run may write (32 MiB) स्क्रिप्ट ने एक रन में लिखे जा सकने वाले फ़ाइल डेटा से अधिक लिखा (32 MiB) @msg `answer` for a script's file dialog must be one of: once, always, deny, stop स्क्रिप्ट के फ़ाइल डायलॉग के लिए `answer` इनमें से एक होना चाहिए: once, always, deny, stop @msg choose a file or folder first, or deny पहले कोई फ़ाइल या फ़ोल्डर चुनें, या अस्वीकार करें -@msg the script file permissions could not be saved: {e} स्क्रिप्ट की फ़ाइल अनुमतियाँ सहेजी नहीं जा सकीं: {e} +@msg the script file permissions could not be saved: {e} स्क्रिप्ट की फ़ाइल अनुमतियाँ सेव नहीं की जा सकीं: {e} @msg this script's file access can be allowed only once इस स्क्रिप्ट की फ़ाइल पहुँच केवल एक बार दी जा सकती है @msg Only the person at the keyboard can allow a script's file access किसी स्क्रिप्ट को फ़ाइल पहुँच केवल कीबोर्ड पर मौजूद व्यक्ति दे सकता है @msg A script is given at most 2,048 files: the files picked after them were left out किसी स्क्रिप्ट को अधिकतम 2,048 फ़ाइलें दी जाती हैं: उनके बाद चुनी गई फ़ाइलें छोड़ दी गईं From 44c3ef4f56233a76ee9feea1ed543195d10a6309 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 09:06:12 -0800 Subject: [PATCH 015/176] UI fonts: a font search that cannot start keeps its characters When the thread for a fallback font search could not be created, the characters taken for that search were lost. Characters no font covered were already removed from the retry list, and characters met that frame were already marked seen, so neither was looked for again. Now the characters no font covered go back to the retry list, and the ones met that frame are looked for when they are painted again. A web test also checks that a face fetched again after a failure is not fetched a second time at once, whether the interface asks for its script again or the retry timer fires. --- apps/vectorcraft-web/src/demand.rs | 15 ++++++++ crates/ui-egui/src/ui_fonts.rs | 58 ++++++++++++++++++++++++++++-- 2 files changed, 70 insertions(+), 3 deletions(-) diff --git a/apps/vectorcraft-web/src/demand.rs b/apps/vectorcraft-web/src/demand.rs index d2a2317bd3..7583248701 100644 --- a/apps/vectorcraft-web/src/demand.rs +++ b/apps/vectorcraft-web/src/demand.rs @@ -110,6 +110,21 @@ mod tests { assert!(d.start(&[1], 1e12).is_empty()); } + /// While a face is fetched again after a failure, neither the interface asking for its script + /// again nor the retry timer starts a second fetch of it. + #[test] + fn a_face_being_fetched_again_is_not_fetched_twice_at_once() { + let mut d = Demand::default(); + d.start(&[0], 0.0); + assert_eq!(d.finished(0, false, 0.0), Some(RETRY_MS)); + let retry = f64::from(RETRY_MS); + assert_eq!(d.start(&[0, 0], retry), [0], "one fetch for a face wanted twice"); + assert!(d.start(&[0], retry + 1.0).is_empty(), "the interface asking again"); + assert!(d.start(&[0], retry + 1_000.0).is_empty(), "the retry timer"); + assert_eq!(d.finished(0, true, retry + 2_000.0), None); + assert!(d.start(&[0], 1e12).is_empty(), "loaded"); + } + /// A clock that reads earlier than the failure (one set back meanwhile) does not hold the /// retry back: the timer that asks for it has waited already. #[test] diff --git a/crates/ui-egui/src/ui_fonts.rs b/crates/ui-egui/src/ui_fonts.rs index fd994fa6bf..73c1a30891 100644 --- a/crates/ui-egui/src/ui_fonts.rs +++ b/crates/ui-egui/src/ui_fonts.rs @@ -71,6 +71,9 @@ pub(crate) struct UiFonts { /// The faces covering the characters being looked for (native: looked for on a thread). #[cfg(not(target_arch = "wasm32"))] pending: Option>, + /// The search thread can't be created (tests). + #[cfg(all(test, not(target_arch = "wasm32")))] + spawn_fails: bool, } impl UiFonts { @@ -93,14 +96,18 @@ impl UiFonts { #[cfg(target_arch = "wasm32")] let idle = true; // A font added since (a web face fetched for them) may cover them now. - if idle && !self.uncovered.is_empty() && db.generation() != self.searched { - missing.extend(self.uncovered.drain()); + let retry: Vec = + if idle && !self.uncovered.is_empty() && db.generation() != self.searched { self.uncovered.drain().collect() } else { vec![] }; + if !retry.is_empty() { + missing.extend_from_slice(&retry); missing.sort_unstable(); missing.dedup(); } if missing.is_empty() { return; } + #[cfg(not(target_arch = "wasm32"))] + let looked_for = missing.clone(); let find = move || search(db, missing, FontDb::face_covering); // Native: the installed fonts are read off the UI thread. Characters met meanwhile wait for // the next search (they aren't marked seen until then). @@ -108,13 +115,20 @@ impl UiFonts { { let (tx, rx) = std::sync::mpsc::channel(); let repaint = ctx.clone(); - let spawned = std::thread::Builder::new().name("ui-font-fallback".into()).spawn(move || { + let spawned = self.spawn_search(move || { // The receiver is gone only when the app is. let _ = tx.send(find()); repaint.request_repaint(); }); if spawned.is_ok() { self.pending = Some(rx); + } else { + // Not looked for: the characters met this frame are looked for when painted again, + // and the ones no font covered wait for the fonts to change again. + for c in looked_for.iter().filter(|c| !retry.contains(c)) { + self.seen.remove(c); + } + self.uncovered.extend(retry); } } // The web has only the loaded fonts to look through: quick, on this thread. @@ -122,6 +136,16 @@ impl UiFonts { self.found(ctx, find(), report); } + /// Run `search` on a thread of its own. + #[cfg(not(target_arch = "wasm32"))] + fn spawn_search(&self, search: impl FnOnce() + Send + 'static) -> std::io::Result<()> { + #[cfg(test)] + if self.spawn_fails { + return Err(std::io::Error::other("no thread for the font search")); + } + std::thread::Builder::new().name("ui-font-fallback".into()).spawn(search).map(|_| ()) + } + /// Add the faces a search found, and keep (and report) the characters it found no face for. fn found(&mut self, ctx: &egui::Context, found: Found, report: fn(&[char])) { self.install(ctx, &found.faces); @@ -543,4 +567,32 @@ mod tests { assert!(has_glyph(&ctx, PRIVATE_USE_CHAR), "the added face draws the character"); assert!(fonts.uncovered.is_empty()); } + + /// A search whose thread can't be created leaves its characters to be looked for later: a + /// character painted for the first time is looked for when it is painted again, and one no font + /// covered stays waiting for the fonts to change. + #[test] + fn a_search_that_cannot_start_keeps_its_characters() { + use vectorcraft_text::test_fonts::{PRIVATE_USE_CHAR, private_use_font}; + let db: &'static FontDb = Box::leak(Box::new(FontDb::with_font_dirs(vec![]))); + db.families(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut fonts = UiFonts { spawn_fails: true, ..UiFonts::default() }; + let text = format!("Layer {PRIVATE_USE_CHAR}"); + frame_in(&ctx, &mut fonts, &text, db); + assert!(fonts.pending.is_none() && !fonts.seen.contains(&PRIVATE_USE_CHAR), "not looked for yet"); + fonts.spawn_fails = false; + frame_in(&ctx, &mut fonts, &text, db); + assert!(fonts.uncovered.contains(&PRIVATE_USE_CHAR), "looked for when painted again"); + db.add_font(private_use_font().expect("the test face builds")); + fonts.spawn_fails = true; + frame_in(&ctx, &mut fonts, &text, db); + assert!(fonts.uncovered.contains(&PRIVATE_USE_CHAR), "still waiting to be looked for again"); + fonts.spawn_fails = false; + frame_in(&ctx, &mut fonts, &text, db); + frame_in(&ctx, &mut fonts, &text, db); + assert!(has_glyph(&ctx, PRIVATE_USE_CHAR), "the added face draws the character"); + assert!(fonts.uncovered.is_empty()); + } } From dbfffc8ecb155e7f95ae9bcee3d88d6555c66796 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 10:09:27 -0800 Subject: [PATCH 016/176] Scripts: commands read through the gate in runs the person starts, and the grants file is not written over when it cannot be read - A command a script runs reads only where the script may, also in a run the person started; only reads of the app's own folders inside the command are exempt. - Always and script.grants.revoke leave a grants file they cannot read as it is, and fail. - script.grants names a path outside the automation read roots by its file name alone. - copy reads the source once, within the 8 MiB limit, writes those bytes, and gives the copy the source's permissions. - write joins its values as UTF-16 before making them text, so a surrogate pair split between two values is one character. --- crates/engine/src/cmd/scripts.rs | 12 ++++- crates/engine/src/file_access.rs | 45 ++++++++++++----- crates/engine/src/script/files.rs | 68 +++++++++++++++++++------- crates/engine/src/tests/script_io.rs | 62 +++++++++++++++++++++++ crates/engine/src/tests/script_run.rs | 6 ++- crates/js/src/file_classes.rs | 12 +++-- crates/ui-egui/src/tests/script_run.rs | 14 +++++- docs/mcp.md | 10 ++-- 8 files changed, 186 insertions(+), 43 deletions(-) diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index 623ab8a87f..a620d398c8 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -341,7 +341,17 @@ fn list_installed(s: &mut Session, _: &Value) -> Result { fn grants(s: &mut Session, _: &Value) -> Result { let Some(dir) = s.script_data_dir() else { return Ok(json!({"grants": [], "file": null})) }; let file = dir.with_file_name(script::files::GRANTS_FILE); - Ok(json!({"grants": script::files::stored_grants(dir), "file": file.to_string_lossy()})) + // A script or a granted path outside the automation read roots is named by its file name alone. + let mut grants = script::files::stored_grants(dir); + for g in &mut grants { + for key in ["script", "path"] { + if let Some(name) = g[key].as_str().and_then(hidden_name) { + g[key] = json!(name); + } + } + } + let file = file.to_string_lossy(); + Ok(json!({"grants": grants, "file": super::fileio::shown_path(&file)})) } fn grants_revoke(s: &mut Session, p: &Value) -> Result { diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index 9aaeb58dab..8979914d43 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -176,7 +176,7 @@ fn with_scope(scope: Option, f: impl FnOnce() -> T) -> T { /// Run `f` with `roots` in force on this thread (`None`: as things stand). pub fn confine(roots: Option<&Arc>, f: impl FnOnce() -> T) -> T { match roots { - Some(r) => with_scope(Some(Scope::Confined(r.clone())), f), + Some(r) => with_gate_reads_exempt(false, || with_scope(Some(Scope::Confined(r.clone())), f)), None => f(), } } @@ -184,24 +184,44 @@ pub fn confine(roots: Option<&Arc>, f: impl FnOnce() -> T) - /// Run `f` with no roots in force on this thread: what the person at the keyboard does, and the /// app's own folders. pub fn unconfined(f: impl FnOnce() -> T) -> T { - with_scope(Some(Scope::Unconfined), f) + with_gate_reads_exempt(true, || with_scope(Some(Scope::Unconfined), f)) +} + +thread_local! { + /// Are reads on this thread exempt from the gate of the script command it runs? Only inside an + /// [`unconfined`] entered after the gate was put in force ([`with_script_gate`]). + static GATE_READS_EXEMPT: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// Puts the exemption it replaced back when dropped (also when `f` panics). +struct RestoreExempt(bool); + +impl Drop for RestoreExempt { + fn drop(&mut self) { + GATE_READS_EXEMPT.with(|e| e.set(self.0)); + } +} + +fn with_gate_reads_exempt(exempt: bool, f: impl FnOnce() -> T) -> T { + let _restore = RestoreExempt(GATE_READS_EXEMPT.with(|e| e.replace(exempt))); + f() } /// This thread's scope, with the gate of the script command it runs, to carry to work it hands to /// another thread ([`ScopeHandle::run`]). #[derive(Clone, Debug)] -pub struct ScopeHandle(Option, Option>); +pub struct ScopeHandle(Option, Option>, bool); impl ScopeHandle { /// The scope of the calling thread. pub fn capture() -> Self { - Self(SCOPE.with(|s| s.borrow().clone()), GATE.with(|g| g.borrow().clone())) + Self(SCOPE.with(|s| s.borrow().clone()), GATE.with(|g| g.borrow().clone()), GATE_READS_EXEMPT.with(std::cell::Cell::get)) } /// Run `f` in the captured scope. pub fn run(self, f: impl FnOnce() -> T) -> T { - let Self(scope, gate) = self; - with_gate(gate, || with_scope(scope, f)) + let Self(scope, gate, exempt) = self; + with_gate(gate, || with_gate_reads_exempt(exempt, || with_scope(scope, f))) } } @@ -252,17 +272,18 @@ fn with_gate(gate: Option>, f: impl FnOnce() -> T) -> T { } /// Runs `f`, a command a script runs, with `gate` in force on this thread: every path it reads or -/// writes must pass the gate as well as the automation roots. Reads of the app's own folders, -/// inside [`unconfined`], are not checked; writes there are, so a script's command does not save -/// into the app's libraries. +/// writes must pass the gate as well as the automation roots, also when the run itself is +/// [`unconfined`] (one the person started). Reads of the app's own folders, inside an +/// [`unconfined`] the command enters, are not checked; writes there are, so a script's command +/// does not save into the app's libraries. pub(crate) fn with_script_gate(gate: ScriptGate, f: impl FnOnce() -> T) -> T { - with_gate(Some(Arc::new(gate)), f) + with_gate(Some(Arc::new(gate)), || with_gate_reads_exempt(false, f)) } /// May `path` be read (or written) by the script command this thread runs? Always outside one, -/// and for a read inside [`unconfined`]. +/// and for a read inside an [`unconfined`] the command entered. fn check_gate(path: &str, access: Access) -> Result<(), String> { - if matches!(access, Access::Read) && SCOPE.with(|s| matches!(*s.borrow(), Some(Scope::Unconfined))) { + if matches!(access, Access::Read) && GATE_READS_EXEMPT.with(std::cell::Cell::get) { return Ok(()); } GATE.with(|g| g.borrow().clone()).map_or(Ok(()), |g| g.check(path, access)) diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index 258d5a2863..ddc574ee71 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -431,7 +431,7 @@ impl Disk { } let (Some((script, hash)), Some(store)) = (&self.script, self.store_path()) else { return }; let (script, code) = (shown(script), self.ran.iter().cloned().collect::>()); - let mut grants = read_store(&store); + let Ok(mut grants) = try_read_store(&store) else { return }; for g in &mut grants { let ours = g["script"] == *script && g["sha256"] == *hash @@ -565,7 +565,8 @@ impl Disk { /// takes its place. fn keep(&self, paths: &[std::path::PathBuf], write: bool, folder: bool) -> Result<(), &'static str> { let (Some((script, hash)), Some(store)) = (&self.script, self.store_path()) else { return Err(NO_ALWAYS) }; - let mut grants = read_store(&store); + // A grants file that is there but cannot be read is left as it is. + let mut grants = try_read_store(&store).map_err(|_| NOT_SAVED)?; let script = shown(script); let code: Vec<&String> = self.ran.iter().collect(); for p in paths { @@ -880,15 +881,34 @@ fn read_head(real: &Path, max: usize) -> std::io::Result> { Ok(bytes) } -/// The grants the grants file at `store` holds; none when it is missing or cannot be read. +/// The grants the grants file at `store` holds; none when it is missing or cannot be read. A grant +/// that is not well formed is left out. fn read_store(store: &Path) -> Vec { - let Ok(bytes) = read_head(store, MAX_STORE_BYTES) else { return Vec::new() }; + load_store(store, false).unwrap_or_default() +} + +/// The grants the grants file at `store` holds, to change and write back; none when it is missing, +/// and `Err` when it is there but cannot be read, is too large, is not a grants file of this +/// version, or holds a grant that is not well formed or more grants than may be kept, so that a +/// change is not written over it. +fn try_read_store(store: &Path) -> std::io::Result> { + load_store(store, true) +} + +/// The grants file at `store` read as [`read_store`] reads it, or with `strict` as +/// [`try_read_store`] does. +fn load_store(store: &Path, strict: bool) -> std::io::Result> { + let bytes = match read_head(store, MAX_STORE_BYTES) { + Ok(bytes) => bytes, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()), + Err(e) => return Err(e), + }; if bytes.len() > MAX_STORE_BYTES { - return Vec::new(); + return Err(std::io::Error::other("the grants file is too large")); } - let Ok(v) = serde_json::from_slice::(&bytes) else { return Vec::new() }; + let v = serde_json::from_slice::(&bytes).map_err(std::io::Error::other)?; if v["version"] != 1 { - return Vec::new(); + return Err(std::io::Error::other("the grants file has another version")); } let valid = |g: &serde_json::Value| { g["script"].is_string() @@ -898,7 +918,14 @@ fn read_store(store: &Path) -> Vec { && g["write"].is_boolean() && g["folder"].is_boolean() }; - v["grants"].as_array().map(|a| a.iter().filter(|g| valid(g)).take(MAX_STORED_GRANTS).cloned().collect()).unwrap_or_default() + if strict { + let grants = v["grants"].as_array().ok_or_else(|| std::io::Error::other("the grants file holds no list of grants"))?; + if grants.len() > MAX_STORED_GRANTS || !grants.iter().all(valid) { + return Err(std::io::Error::other("the grants file holds a grant that cannot be read")); + } + return Ok(grants.clone()); + } + Ok(v["grants"].as_array().map(|a| a.iter().filter(|g| valid(g)).take(MAX_STORED_GRANTS).cloned().collect()).unwrap_or_default()) } /// Writes `grants` as the grants file at `store`: to a file beside it, which then takes its place. @@ -930,7 +957,7 @@ pub(crate) fn stored_grants(data_dir: &Path) -> Vec { /// → how many were removed. pub(crate) fn revoke_grants(data_dir: &Path, script: Option<&str>, path: Option<&str>) -> std::io::Result { let store = data_dir.with_file_name(GRANTS_FILE); - let grants = read_store(&store); + let grants = try_read_store(&store)?; let before = grants.len(); let kept: Vec = grants.into_iter().filter(|g| !(script.is_none_or(|s| g["script"] == *s) && path.is_none_or(|p| g["path"] == *p))).collect(); @@ -1636,28 +1663,33 @@ fn copy(host: &Host, a: &[Data]) -> Result { if let Err(m) = ids.iter().try_for_each(|id| disk.flush(*id)) { return Ok(error(m)); } - let n = std::fs::metadata(&source).map_or(0, |m| m.len()); - if n > MAX_FILE_BYTES as u64 { - return Ok(error(TOO_LARGE)); - } + // The bytes are read once, no more than the limit, and those bytes are what is charged and + // written: a source that grows after it is read does not copy more. + let copied = match read_head(&source, MAX_FILE_BYTES) { + Ok(bytes) if bytes.len() > MAX_FILE_BYTES => return Ok(error(TOO_LARGE)), + Ok(bytes) => bytes, + Err(_) => return Ok(error(READ_FAILED)), + }; // The target's open objects each take a copy of the bytes, which count as written too, as does // the copy itself when it is written. let holders = disk.open.values().filter(|o| o.target.as_deref() == Some(target.as_path())).count(); - disk.charge_write(usize::try_from(n).unwrap_or(usize::MAX).saturating_mul(holders.saturating_add(usize::from(!itself))))?; - let r = if itself { Ok(n) } else { std::fs::copy(&source, &target) }; + disk.charge_write(copied.len().saturating_mul(holders.saturating_add(usize::from(!itself))))?; + // The copy takes the source's permissions, as `std::fs::copy` gives them. + let permissions = std::fs::metadata(&source).map(|m| m.permissions()); + let r = + if itself { Ok(()) } else { std::fs::write(&target, &copied).and_then(|()| permissions.and_then(|p| std::fs::set_permissions(&target, p))) }; if !itself && (r.is_ok() || target.exists()) { disk.wrote(&target); } // Open objects of the target hold the copy, so closing them does not write their older bytes. - if r.is_ok() && disk.open.values().any(|o| o.target.as_deref() == Some(target.as_path())) { - let copied = read_head(&target, MAX_FILE_BYTES).unwrap_or_default(); + if r.is_ok() { for file in disk.open.values_mut().filter(|o| o.target.as_deref() == Some(target.as_path())) { file.bytes.clone_from(&copied); file.pos = file.pos.min(copied.len()); file.dirty = false; } } - Ok(done(r.map(drop).map_err(|_| WRITE_FAILED))) + Ok(done(r.map_err(|_| WRITE_FAILED))) } /// `remove(path)`: the file, or the folder when it is empty; a link itself, never what it leads to. diff --git a/crates/engine/src/tests/script_io.rs b/crates/engine/src/tests/script_io.rs index e3e7ade3a2..b9bb6a2162 100644 --- a/crates/engine/src/tests/script_io.rs +++ b/crates/engine/src/tests/script_io.rs @@ -730,6 +730,34 @@ fn script_file_copy_of_an_open_file_has_its_changes() { let _ = std::fs::remove_dir_all(base); } +/// `copy` gives the copy the source's permissions: the copy of a read-only file is read-only. +#[test] +fn script_file_copy_keeps_the_source_read_only() { + let base = folder("copyreadonly"); + let r = run( + &base, + "var d = Folder.temp.fsName, s = new File(d + '/s.txt'); s.open('w'); s.write('x'); s.close(); s.readonly = true;\n\ + var out = [s.copy(d + '/t.txt'), new File(d + '/t.txt').readonly, new File(d + '/t.txt').length];\n\ + s.readonly = false; new File(d + '/t.txt').readonly = false; vc.log(out);", + ); + assert_eq!(r["log"], json!([[true, true, 1]])); + let _ = std::fs::remove_dir_all(base); +} + +/// `write` with several values joins them before making them text, so a surrogate pair split +/// between two values is written as one character. +#[test] +fn script_file_write_joins_a_surrogate_pair_split_between_values() { + let base = folder("surrogates"); + let r = run( + &base, + "var f = new File(Folder.temp.fsName + '/s.txt'); f.encoding = 'UTF-8'; f.open('w'); f.write('\\uD83D', '\\uDE00'); f.close();\n\ + f.open('r'); var t = f.read(); f.close(); vc.log([t === '\\uD83D\\uDE00', t.length]);", + ); + assert_eq!(r["log"], json!([[true, 2]])); + let _ = std::fs::remove_dir_all(base); +} + /// A grant that would make the grants file larger than it may be read is not kept, and the grants /// file keeps the grants it had. #[test] @@ -754,6 +782,34 @@ fn script_file_grants_file_stays_within_its_size_limit() { let _ = std::fs::remove_dir_all(base); } +/// A grants file that is there but cannot be read (another version, not JSON, a grant that is not +/// well formed, or no list of grants) is not written over: a grant picked with Always is not kept, and a revoke fails, so the grants it holds stay. +#[test] +fn script_file_grants_file_that_cannot_be_read_is_left_as_it_is() { + let cases = [ + ("newer", br#"{"version": 2, "grants": [{"script": "x"}]}"#.as_slice()), + ("broken", b"{ not json".as_slice()), + ("malformed", br#"{"version": 1, "grants": [{"script": "x"}]}"#.as_slice()), + ("nolist", br#"{"version": 1, "grants": {}}"#.as_slice()), + ]; + for (name, held) in cases { + let base = folder(&format!("store-{name}")); + let out = base.join("picked/out.txt"); + std::fs::create_dir_all(out.parent().unwrap()).unwrap(); + let store = base.join("settings/Script Grants.json"); + write(&store, held); + let mut s = with_data(&base); + start_framed(&mut s, &base, "var f = File.saveDialog('p'); vc.log(f === null ? null : f.fsName);"); + assert!(pump_to_picker(&mut s).is_none()); + assert!(s.script_pick(crate::script::files::PickAnswer::Allow { paths: vec![out.to_string_lossy().into_owned()], always: true })); + let _ = pump_to_picker(&mut s).unwrap(); + assert_eq!(std::fs::read(&store).unwrap(), held, "{name}: the grants file is left as it was"); + assert!(s.execute("script.grants.revoke", &json!({"all": true})).is_err(), "{name}"); + assert_eq!(std::fs::read(&store).unwrap(), held, "{name}: a revoke leaves it too"); + let _ = std::fs::remove_dir_all(base); + } +} + /// `copy` of a file over 8 MiB is refused, as opening one is. #[test] fn script_file_copy_is_held_to_the_file_limit() { @@ -1387,6 +1443,12 @@ fn script_file_dialog_grants_are_kept_for_the_same_script_text() { let grants = s.execute("script.grants", &json!({})).unwrap(); assert_eq!(grants["grants"].as_array().unwrap().len(), 1, "{grants}"); assert_eq!(grants["grants"][0]["write"], true); + // Under automation read roots, a path outside them is named by its file name alone. + let roots = AutomationRoots::new(&[&base.join("main")], &[]).unwrap(); + let hidden = confine(roots.as_ref(), || s.execute("script.grants", &json!({}))).unwrap(); + assert_eq!(hidden["grants"][0]["path"], "out.txt", "{hidden}"); + assert_eq!(hidden["grants"][0]["script"], grants["grants"][0]["script"], "the script inside the roots is named whole: {hidden}"); + assert_eq!(hidden["file"], "Script Grants.json", "{hidden}"); start_framed(&mut s, &base, &text); let r = pump_to_picker(&mut s).unwrap().unwrap(); diff --git a/crates/engine/src/tests/script_run.rs b/crates/engine/src/tests/script_run.rs index 0a4037a0d8..ab8345e6cb 100644 --- a/crates/engine/src/tests/script_run.rs +++ b/crates/engine/src/tests/script_run.rs @@ -316,7 +316,8 @@ fn an_export_that_fails_names_no_file() { } /// The commands a script runs read and write only where its `File` and `Folder` objects may (its -/// temporary folder and what a person allowed it, here), and the files of the open documents. +/// temporary folder and what a person allowed it, here), and the files of the open documents, +/// also in a run the person started. #[test] fn a_scripts_commands_reach_only_its_own_places_and_the_open_documents() { let dir = fresh_folder("gate"); @@ -354,6 +355,9 @@ fn a_scripts_commands_reach_only_its_own_places_and_the_open_documents() { let r = run(&mut s, &source).unwrap(); assert_eq!(r["log"], json!(["ok", "ok", "denied", "denied"]), "an open document's own file, and no other: {r}"); assert!(!outside.join("other.svg").exists()); + let source = format!("{}{}", call("document.open", &own), call("document.open", &outside.join("copy.svg"))); + let r = crate::file_access::unconfined(|| run(&mut s, &source)).unwrap(); + assert_eq!(r["log"], json!(["ok", "denied"]), "a run the person starts reads through the gate as well: {r}"); std::fs::remove_file(&own).unwrap(); let r = run(&mut s, &call("document.save", &own)).unwrap(); assert_eq!(r["log"], json!(["ok"]), "a document's own file that was removed is made again: {r}"); diff --git a/crates/js/src/file_classes.rs b/crates/js/src/file_classes.rs index f6d87de964..0d8d997a91 100644 --- a/crates/js/src/file_classes.rs +++ b/crates/js/src/file_classes.rs @@ -542,19 +542,21 @@ fn write_values(i: &mut Interp, this: &Value, args: &[Value], what: &str, line: Value::Number(n) if n.is_finite() && n >= 0.0 => (n as usize).saturating_mul(2), _ => usize::MAX, }; - let mut text = String::new(); - let mut units = 0usize; + // The values are joined as UTF-16 code units and made text once, so a surrogate pair split + // between two values is one character. + let mut joined: Vec = Vec::new(); for a in args { i.use_fuel()?; let s = i.to_str(a)?; - units = units.saturating_add(s.len()); - if units > max { + if joined.len().saturating_add(s.len()) > max { let m = message(i, "tooLarge")?; set_slot(i, o, ERROR, m)?; return Ok(Value::Bool(false)); } - text.push_str(&s.to_rust_string()); + joined.extend_from_slice(&s.flat()); } + let mut text = String::from_utf16_lossy(&joined); + drop(joined); if line { text.push_str(line_end(i, o)?); } diff --git a/crates/ui-egui/src/tests/script_run.rs b/crates/ui-egui/src/tests/script_run.rs index ba6553e068..202ac35c6f 100644 --- a/crates/ui-egui/src/tests/script_run.rs +++ b/crates/ui-egui/src/tests/script_run.rs @@ -553,10 +553,18 @@ fn enter_in_a_scripts_file_dialog_denies() { assert_eq!(app.session.script_report().unwrap()["log"], json!([null])); } -/// Enter on the file dialog's focused Choose… button goes to that button and does not deny. +/// Enter on the file dialog's focused Choose… button goes to that button, which opens the folder +/// picker once, and does not deny. #[test] fn enter_on_a_focused_choose_button_does_not_deny() { - let mut app = app(); + let asked = std::rc::Rc::new(std::cell::Cell::new(0usize)); + let counted = asked.clone(); + let pick_folder: Box Option> = Box::new(move || { + counted.set(counted.get() + 1); + None + }); + let mut app = VectorcraftApp::new(Session::new(), crate::Services { pick_folder: Some(pick_folder), ..Default::default() }); + app.run("file.new", json!({})).unwrap(); app.session.prefs.show_external_script_warning = false; menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": "vc.log(Folder.selectDialog('Pick'));" })).unwrap().unwrap(); script_runs::poll(&mut app); @@ -571,8 +579,10 @@ fn enter_on_a_focused_choose_button_does_not_deny() { frame(&mut app, events); } assert!(ctx.memory(|m| m.focused().is_some()), "Tab gives a button the keyboard focus"); + assert_eq!(asked.get(), 0); frame(&mut app, vec![key(egui::Key::Enter)]); frame(&mut app, vec![]); + assert_eq!(asked.get(), 1, "Enter chose the focused Choose… button"); assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(dialogs::script_run::PICKER_KIND), "the dialog stays open"); assert!(app.session.script_picker().is_some(), "the run still waits"); dialogs::cancel(&mut app); diff --git a/docs/mcp.md b/docs/mcp.md index 481961c67f..8fefe75b07 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2263,7 +2263,7 @@ The help page's writing members work as it describes - `open('w')` empties the file, or makes it, `open('e')` opens a file that is there, and `open('a')` opens it at its end. `write(...values)` writes the values as `String(value)` gives them, and `writeln(...values)` adds the line end `lineFeed` names: CR LF for `Windows`, CR for `Macintosh` and LF for `Unix`. A byte order mark is written only - when the script writes ``. + when the script writes `\uFEFF`. - `copy(target)` copies the file to a path or a `File` and replaces a file that is there. `remove()` deletes a file, or a folder only when it is empty (`Script folder is not empty`), at once and without the trash. `rename(name)` takes a name without a folder; a name that is in use gives `Script file name is already in use`, and the object @@ -2345,10 +2345,12 @@ VectorCraft writes files by these rules of its own: the SHA-256 of each evaluated source (of its UTF-16 code units in little-endian order), `folder` true for a folder's grant, which covers everything in the folder (a file's grant covers its own path only, also when a folder later takes its place), and `file` the grants -file's path, or `null` without a settings folder. `script.grants.revoke {script?, path?, all?}` removes the grants of +file's path, or `null` without a settings folder. Under automation read roots, a `script`, `path` or `file` outside them +is given as its file name alone. `script.grants.revoke {script?, path?, all?}` removes the grants of a script file, of a path, of both together, or with `all: true` every grant, and returns `{removed}`. While a script -runs it is refused with the busy error, as the run keeps the grants it started with. A script cannot run either -command. +runs it is refused with the busy error, as the run keeps the grants it started with. A grants file that is there but +cannot be read is left as it is: `script.grants.revoke` fails, and a grant picked with Always is not kept. A script +cannot run either command. ```json {"name":"run_command","arguments":{"command":"script.grants.revoke","params":{"all":true}}} From b153a3d7a673fab8f0baf2f294917a2004e1a1fb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 10:31:59 -0800 Subject: [PATCH 017/176] Scripts: a file whose close could not write it stays open, so a later close tries again --- crates/engine/src/tests/script_io.rs | 15 +++++++++++++++ crates/js/src/file_classes.rs | 7 +++++-- docs/mcp.md | 3 ++- 3 files changed, 22 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/tests/script_io.rs b/crates/engine/src/tests/script_io.rs index b9bb6a2162..4fae8d33b8 100644 --- a/crates/engine/src/tests/script_io.rs +++ b/crates/engine/src/tests/script_io.rs @@ -730,6 +730,21 @@ fn script_file_copy_of_an_open_file_has_its_changes() { let _ = std::fs::remove_dir_all(base); } +/// A file whose `close` could not write it stays open, so a later `close` writes it. +#[test] +fn script_file_close_that_fails_can_be_tried_again() { + let base = folder("closeagain"); + let r = run( + &base, + "var d = Folder.temp.fsName, f = new File(d + '/f.txt'); f.open('w'); f.write('kept');\n\ + new File(f.fsName).readonly = true; var out = [f.close(), f.error];\n\ + new File(f.fsName).readonly = false; out.push(f.close());\n\ + var g = new File(f.fsName); g.open('r'); out.push(g.read()); g.close(); vc.log(out);", + ); + assert_eq!(r["log"], json!([[false, "Script file could not be written", true, "kept"]])); + let _ = std::fs::remove_dir_all(base); +} + /// `copy` gives the copy the source's permissions: the copy of a read-only file is read-only. #[test] fn script_file_copy_keeps_the_source_read_only() { diff --git a/crates/js/src/file_classes.rs b/crates/js/src/file_classes.rs index 0d8d997a91..7ebcc7bfae 100644 --- a/crates/js/src/file_classes.rs +++ b/crates/js/src/file_classes.rs @@ -220,14 +220,17 @@ fn is_open(i: &Interp, o: ObjId) -> JsResult> { } /// Closes the object's open file, if it has one, which writes what the script wrote to it. → false -/// after setting `error` when that could not be written. +/// after setting `error` when that could not be written; the file then stays open, so a later +/// `close` tries again. fn close_open(i: &mut Interp, o: ObjId) -> JsResult { let mut written = true; if let Some(h) = is_open(i, o)? { let r = host(i, "close", &[h])?; written = outcome(i, o, &r)?; } - set_slot(i, o, HANDLE, Value::Number(-1.0))?; + if written { + set_slot(i, o, HANDLE, Value::Number(-1.0))?; + } Ok(written) } diff --git a/docs/mcp.md b/docs/mcp.md index 8fefe75b07..1b642340cb 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2300,7 +2300,8 @@ VectorCraft writes files by these rules of its own: `Script file access denied`. - What a script writes is written when it closes the file or when the run ends, also when the run fails. At the run's end the files left open are written in the order they were opened. A file - that `close` could not write is written again when the run ends, and a `write` that would pass the run's limit + that `close` could not write stays open, so a later `close` tries again, and is written again when the run ends; a + `write` that would pass the run's limit is not written. A run that would otherwise succeed fails when a changed file it left open cannot be written, with `Error: the script left open files that could not be written` and the files' paths. One file From 3ef3ed568a0d97ee6e3c3d0f31fe3c43659baa26 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 10:55:29 -0800 Subject: [PATCH 018/176] Scripts: script.grants.revoke does not look up a path outside the automation read roots --- crates/engine/src/cmd/scripts.rs | 13 +++++++++---- crates/engine/src/tests/script_io.rs | 19 +++++++++++++++++-- docs/mcp.md | 3 ++- 3 files changed, 28 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/cmd/scripts.rs b/crates/engine/src/cmd/scripts.rs index a620d398c8..3af4f351f1 100644 --- a/crates/engine/src/cmd/scripts.rs +++ b/crates/engine/src/cmd/scripts.rs @@ -104,7 +104,7 @@ pub fn specs() -> Vec { "Revoke Script File Permissions", [], None, - "{script?: a script file's path, path?: an allowed file or folder's path, all?: true (exactly one of all and the other two)} remove the kept file access of that script, of that path, of both together, or every one; a path is matched as script.grants lists it, after its links are followed; refused with the busy error while a script runs, as the run keeps the grants it started with → {removed: how many}", + "{script?: a script file's path, path?: an allowed file or folder's path, all?: true (exactly one of all and the other two)} remove the kept file access of that script, of that path, of both together, or every one; a path is matched as script.grants lists it, after its links are followed (a path outside the automation read roots is matched as given); refused with the busy error while a script runs, as the run keeps the grants it started with → {removed: how many}", always, grants_revoke ), @@ -358,9 +358,14 @@ fn grants_revoke(s: &mut Session, p: &Value) -> Result { const C: &str = "script.grants.revoke"; let path_of = |key: &str| match p.get(key) { None => Ok(None), - Some(Value::String(t)) if !t.is_empty() => { - Ok(Some(std::fs::canonicalize(t).map_or_else(|_| t.clone(), |real| crate::cmd::findfiles::plain(real).to_string_lossy().into_owned()))) - } + // A path the request may not read (outside the automation read roots, a network path among + // them) is compared as written, without looking it up. + Some(Value::String(t)) if !t.is_empty() => Ok(Some( + crate::file_access::check_read(t) + .ok() + .and_then(|()| std::fs::canonicalize(t).ok()) + .map_or_else(|| t.clone(), |real| crate::cmd::findfiles::plain(real).to_string_lossy().into_owned()), + )), Some(_) => Err(bad(C, format!("`{key}` must be a path"))), }; let (script_path, path) = (path_of("script")?, path_of("path")?); diff --git a/crates/engine/src/tests/script_io.rs b/crates/engine/src/tests/script_io.rs index 4fae8d33b8..39276d737f 100644 --- a/crates/engine/src/tests/script_io.rs +++ b/crates/engine/src/tests/script_io.rs @@ -1492,8 +1492,23 @@ fn script_file_dialog_grants_are_kept_for_the_same_script_text() { assert!(s.script_pick(crate::script::files::PickAnswer::Deny)); assert!(pump_to_picker(&mut s).is_some(), "the run ends"); - let removed = s.execute("script.grants.revoke", &json!({"path": out.to_string_lossy()})).unwrap(); - assert_eq!(removed["removed"], 1); + // Under automation read roots, a path outside them is not looked up: a link there to the + // granted file does not name it. + #[cfg(unix)] + { + let link = base.join("link.txt"); + std::os::unix::fs::symlink(&out, &link).unwrap(); + let roots = AutomationRoots::new(&[&base.join("main")], &[]).unwrap(); + let r = confine(roots.as_ref(), || s.execute("script.grants.revoke", &json!({"path": link.to_string_lossy()}))).unwrap(); + assert_eq!(r["removed"], 0, "{r}"); + let r = s.execute("script.grants.revoke", &json!({"path": link.to_string_lossy()})).unwrap(); + assert_eq!(r["removed"], 1, "without roots the link is followed: {r}"); + } + #[cfg(not(unix))] + { + let removed = s.execute("script.grants.revoke", &json!({"path": out.to_string_lossy()})).unwrap(); + assert_eq!(removed["removed"], 1); + } assert_eq!(s.execute("script.grants", &json!({})).unwrap()["grants"], json!([])); assert!(s.execute("script.grants.revoke", &json!({})).is_err()); assert!(!base.join("settings/Script Grants.json.part").exists()); diff --git a/docs/mcp.md b/docs/mcp.md index 1b642340cb..2e8843ce07 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2348,7 +2348,8 @@ grant, which covers everything in the folder (a file's grant covers its own path takes its place), and `file` the grants file's path, or `null` without a settings folder. Under automation read roots, a `script`, `path` or `file` outside them is given as its file name alone. `script.grants.revoke {script?, path?, all?}` removes the grants of -a script file, of a path, of both together, or with `all: true` every grant, and returns `{removed}`. While a script +a script file, of a path, of both together, or with `all: true` every grant, and returns `{removed}`. A path is +matched after its links are followed; under automation read roots, a path outside them is matched as given. While a script runs it is refused with the busy error, as the run keeps the grants it started with. A grants file that is there but cannot be read is left as it is: `script.grants.revoke` fails, and a grant picked with Always is not kept. A script cannot run either command. From 0300f7095079cdfaa8dd4e49363bc0783e7ffc41 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 14:45:05 -0800 Subject: [PATCH 019/176] Scripts: file and folder dialogs are native functions that pause the script File.openDialog, File.saveDialog, Folder.selectDialog and the openDlg, saveDlg and selectDlg methods are now built-ins written in Rust instead of JavaScript source compiled when File and Folder are installed. The interpreter gains a native function form that asks the host for a value: it gives the host call to make and a function that takes the answer. When the host waits, the run pauses at the call, and the answer goes to that function before the next instruction, so a filter function or an exception it throws runs at the dialog's call. Arguments, filters, multiSelect, the start folder and the null and error answers work as before. --- crates/js/src/builtins.rs | 11 +- crates/js/src/file_classes.rs | 297 ++++++++++++++++++++++++---------- crates/js/src/heap.rs | 4 +- crates/js/src/interp.rs | 83 ++++++++++ crates/js/src/realm.rs | 6 +- 5 files changed, 313 insertions(+), 88 deletions(-) diff --git a/crates/js/src/builtins.rs b/crates/js/src/builtins.rs index 92db4e6502..98327a2b61 100644 --- a/crates/js/src/builtins.rs +++ b/crates/js/src/builtins.rs @@ -38,6 +38,15 @@ pub(crate) fn native(interp: &mut Interp, name: &'static str, f: NativeFn, lengt Ok(o) } +/// A built-in function object that may wait for the host ([`crate::interp::Pause`]), defined as +/// `name` on `on` the way [`method`] defines one. +pub(crate) fn pausable_method(interp: &mut Interp, on: ObjId, name: &'static str, f: crate::interp::PausableFn, length: u32) -> JsResult<()> { + let proto = interp.intrinsics.function_proto; + let m = alloc(interp, Class::Function(Func::Pausable { f, name }), Some(proto)); + interp.define(m, key("length"), Prop::Data { value: Value::Number(f64::from(length)), flags: 0 })?; + interp.define(on, key(name), Prop::Data { value: Value::Object(m), flags: HIDDEN }) +} + pub(crate) fn method(interp: &mut Interp, on: ObjId, name: &'static str, f: NativeFn, length: u32) -> JsResult<()> { let m = native(interp, name, f, length, NativeKind::Plain, false)?; interp.define(on, key(name), Prop::Data { value: Value::Object(m), flags: HIDDEN }) @@ -514,7 +523,7 @@ fn function_to_string(interp: &mut Interp, this: Value, _: &[Value], _: bool) -> interp.heap.bytes = interp.heap.bytes.saturating_add(bytes); return Ok(Value::String(Str::from_units(units.to_vec()))); } - Some(Func::Native { name, .. }) => format!("function {name}() {{ [native code] }}"), + Some(Func::Native { name, .. } | Func::Pausable { name, .. }) => format!("function {name}() {{ [native code] }}"), Some(Func::Host { name, .. } | Func::Data { name, .. } | Func::Eval { 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/file_classes.rs b/crates/js/src/file_classes.rs index 7ebcc7bfae..f1bba51291 100644 --- a/crates/js/src/file_classes.rs +++ b/crates/js/src/file_classes.rs @@ -14,8 +14,8 @@ //! //! `write` and `writeln` join their values as `String(value)` gives them, and `writeln` adds the //! line end `lineFeed` names: CRLF for `Windows`, CR for `Macintosh` and LF otherwise. The file -//! dialogs are functions of script code that call the host's `pick`, so that a run can wait there -//! for the person's answer; they give a `File`, a `Folder`, an array of `File`s or `null`. +//! dialogs are built-ins that ask the host's `pick` and may pause the run until the person answers +//! ([`crate::interp::Pause`]); they give a `File`, a `Folder`, an array of `File`s or `null`. //! //! A method whose host call fails sets `error` and returns `false`, `null` or an empty string. A //! count or position that is not a finite number, a negative count and a seek mode other than 0, 1 @@ -24,11 +24,10 @@ //! true value for; every entry takes fuel. use crate::HostItem; -use crate::builtins::{arg, constructor, data, method, native, put_at}; -use crate::bytecode::CodeKind; +use crate::builtins::{arg, constructor, data, method, native, pausable_method, put_at}; use crate::heap::{CONFIGURABLE, Class, HIDDEN, NativeFn, NativeKind, OBJECT_BYTES, ObjId, Object, PROP_BYTES, Prop, key, string_bytes}; -use crate::interp::{Abrupt, ErrorType, Interp, JsResult}; -use crate::value::Value; +use crate::interp::{Abrupt, ErrorType, Interp, JsResult, Pause}; +use crate::value::{Value, index_key}; /// The objects of `File` and `Folder`, kept by the realm, and `Folder.current`. #[derive(Clone, Debug)] @@ -579,69 +578,79 @@ fn writeln(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult JsResult { - let kind = arg(args, 0); - let start = match arg(args, 1) { - Value::Null => Value::str(""), - s => this_path(i, &s, "dialog")?.1, +/// Asks the host's `pick` for the dialog `kind` (`open`, `save` or `folder`), with the arguments +/// `[kind, prompt, multi, start, types]`. `me` is the `File` or `Folder` whose `openDlg`, `saveDlg` +/// or `selectDlg` was called, or `None` for the class's own dialog: the dialog starts at its path, +/// and an `{error}` answer sets its `error`. The prompt is `String(prompt)`, or `""` for +/// `undefined` and `null`. A `filter` that is a string gives the file types; one that is a function +/// is called with each file picked ([`picked`]). The run may pause at `pick` until the person +/// answers. +fn ask_pick(i: &mut Interp, kind: &'static str, me: Option<&Value>, prompt: &Value, multi: bool, filter: &Value) -> JsResult { + let start = match me { + None => Value::str(""), + Some(me) => this_path(i, me, "dialog")?.1, }; - let prompt = match arg(args, 2) { + let prompt = match prompt { Value::Undefined | Value::Null => Value::str(""), - p => Value::String(i.to_str(&p)?), + p => Value::String(i.to_str(p)?), }; - let multi = Value::Bool(arg(args, 3).truthy()); - let filter = match arg(args, 4) { - f @ Value::String(_) => f, + let types = match filter { + f @ Value::String(_) => f.clone(), _ => Value::str(""), }; - i.rooted(&[kind.clone(), start.clone(), prompt.clone(), filter.clone()], |i| { - i.reserve_heap(OBJECT_BYTES + 5 * PROP_BYTES)?; - let proto = i.intrinsics.array_proto; - let out = i.heap.alloc_object(Object::new(Class::Array { length: 0, length_writable: true }, Some(proto))); + let pick = host_value(i, "pick")?; + Ok(Pause { + host: pick, + args: vec![Value::str(kind), prompt, Value::Bool(multi), start, types], + keep: vec![Value::Bool(kind == "folder"), me.cloned().unwrap_or(Value::Null), filter.clone()], + resume: picked, + }) +} + +/// What a file dialog gives for `pick`'s `answer`, with `[folder, me, filter]` kept from +/// [`ask_pick`]: the objects [`wrap`] makes, of which a `filter` that is a function keeps the +/// files it gives a true value for, or `null` when it keeps none. +fn picked(i: &mut Interp, keep: &[Value], answer: Value) -> JsResult { + let files = wrap(i, arg(keep, 0).truthy(), &arg(keep, 1), answer)?; + let filter = arg(keep, 2); + if !i.is_callable(&filter) { + return Ok(files); + } + let Some(o) = files.as_object() else { return Ok(files) }; + let length = match &i.object(o)?.class { + Class::Array { length, .. } => Some(*length), + _ => None, + }; + let Some(length) = length else { + let kept = i.rooted(std::slice::from_ref(&files), |i| i.call(&filter, &Value::Undefined, std::slice::from_ref(&files)))?; + return Ok(if kept.truthy() { files } else { Value::Null }); + }; + i.rooted(std::slice::from_ref(&files), |i| { + i.reserve_heap(OBJECT_BYTES)?; + let array_proto = i.intrinsics.array_proto; + let out = i.heap.alloc_object(Object::new(Class::Array { length: 0, length_writable: true }, Some(array_proto))); i.rooted(&[Value::Object(out)], |i| { - for (at, v) in [kind.clone(), prompt.clone(), multi.clone(), start.clone(), filter.clone()].into_iter().enumerate() { - put_at(i, out, at as f64, v)?; + let mut n = 0.0; + for at in 0..length { + i.use_fuel()?; + let file = i.get_value(&files, &index_key(at))?; + let kept = i.rooted(std::slice::from_ref(&file), |i| i.call(&filter, &Value::Undefined, std::slice::from_ref(&file)))?; + if kept.truthy() { + put_at(i, out, n, file)?; + n += 1.0; + } } - Ok(Value::Object(out)) + Ok(if n > 0.0 { Value::Object(out) } else { Value::Null }) }) }) } -/// `wrap(kind, self, answer)`: the `File` (a `Folder` for a folder dialog) for each path `pick` -/// gave, an array of them for a list, `null` for `null`, and `null` after setting `self`'s `error` -/// for `{error}`. -fn wrap(i: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { +/// The `File` (a `Folder` for a `folder` dialog) for each path `pick` gave in `answer`, an array of +/// them for a list, `null` for `null`, and `null` after setting the `error` of `me`, when it is a +/// `File` or `Folder`, for `{error}`. +fn wrap(i: &mut Interp, folder: bool, me: &Value, answer: Value) -> JsResult { let c = classes(i)?; - let proto = if matches!(arg(args, 0), Value::String(s) if s.to_rust_string() == "folder") { c.folder_proto } else { c.file_proto }; - let answer = arg(args, 2); + let proto = if folder { c.folder_proto } else { c.file_proto }; match &answer { Value::String(_) => return instance(i, proto, answer.clone()), Value::Object(_) => {} @@ -649,7 +658,7 @@ fn wrap(i: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { } let error = i.rooted(std::slice::from_ref(&answer), |i| field(i, &answer, "error"))?; if matches!(error, Value::String(_)) { - if let Some(o) = arg(args, 1).as_object() + if let Some(o) = me.as_object() && matches!(slot(i, o, PATH)?, Value::String(_)) { set_slot(i, o, ERROR, error)?; @@ -676,33 +685,44 @@ fn wrap(i: &mut Interp, _: Value, args: &[Value], _: bool) -> JsResult { }) } +/// `File.openDialog(prompt, filter, multiSelect)`. +fn open_dialog(i: &mut Interp, _: Value, args: &[Value]) -> JsResult { + ask_pick(i, "open", None, &arg(args, 0), arg(args, 2).truthy(), &arg(args, 1)) +} + +/// `File.saveDialog(prompt, filter)`. +fn save_dialog(i: &mut Interp, _: Value, args: &[Value]) -> JsResult { + ask_pick(i, "save", None, &arg(args, 0), false, &arg(args, 1)) +} + +/// `File.prototype.openDlg(prompt, filter, multiSelect)`. +fn open_dlg(i: &mut Interp, this: Value, args: &[Value]) -> JsResult { + ask_pick(i, "open", Some(&this), &arg(args, 0), arg(args, 2).truthy(), &arg(args, 1)) +} + +/// `File.prototype.saveDlg(prompt, filter)`. +fn save_dlg(i: &mut Interp, this: Value, args: &[Value]) -> JsResult { + ask_pick(i, "save", Some(&this), &arg(args, 0), false, &arg(args, 1)) +} + +/// `Folder.selectDialog(prompt)`. +fn select_dialog(i: &mut Interp, _: Value, args: &[Value]) -> JsResult { + ask_pick(i, "folder", None, &arg(args, 0), false, &Value::Null) +} + +/// `Folder.prototype.selectDlg(prompt)`. +fn select_dlg(i: &mut Interp, this: Value, args: &[Value]) -> JsResult { + ask_pick(i, "folder", Some(&this), &arg(args, 0), false, &Value::Null) +} + /// Defines the file dialogs on `File`, `Folder` and their prototypes. fn dialogs(i: &mut Interp, file: ObjId, file_proto: ObjId, folder: ObjId, folder_proto: ObjId) -> JsResult<()> { - let units = i.encode_source(DIALOGS).map_err(|e| i.compile_error_to_abrupt(e))?; - let code = i.compile_source(&units, false, CodeKind::Eval).map_err(|e| i.compile_error_to_abrupt(e))?; - let make = i.run_global(code, true)?; - let c = classes(i)?; - let pick = i.rooted(std::slice::from_ref(&make), |i| i.get_value(&Value::Object(c.host), &key("pick")))?; - let ask = native(i, "ask", ask, 5, NativeKind::Plain, false)?; - let made = i.rooted(&[make.clone(), pick.clone(), Value::Object(ask)], |i| { - let wrap = native(i, "wrap", wrap, 3, NativeKind::Plain, false)?; - i.call(&make, &Value::Undefined, &[Value::Object(ask), pick.clone(), Value::Object(wrap)]) - })?; - let on = [ - (file, "openDialog"), - (file, "saveDialog"), - (file_proto, "openDlg"), - (file_proto, "saveDlg"), - (folder, "selectDialog"), - (folder_proto, "selectDlg"), - ]; - i.rooted(std::slice::from_ref(&made), |i| { - for (at, (target, name)) in on.into_iter().enumerate() { - let f = i.get_value(&made, &crate::value::number_to_str(at as f64).flat())?; - data(i, target, name, f, HIDDEN)?; - } - Ok(()) - }) + pausable_method(i, file, "openDialog", open_dialog, 3)?; + pausable_method(i, file, "saveDialog", save_dialog, 2)?; + pausable_method(i, file_proto, "openDlg", open_dlg, 3)?; + pausable_method(i, file_proto, "saveDlg", save_dlg, 2)?; + pausable_method(i, folder, "selectDialog", select_dialog, 1)?; + pausable_method(i, folder_proto, "selectDlg", select_dlg, 1) } fn text_static(i: &mut Interp, name: &str, args: &[Value]) -> JsResult { @@ -1084,13 +1104,51 @@ pub(crate) fn install(i: &mut Interp, items: Vec<(String, HostItem)>) -> JsResul #[cfg(test)] mod tests { + use std::cell::RefCell; use std::rc::Rc; - use crate::{Data, HostItem, JsValue, Realm}; + use crate::{Data, HostError, HostItem, JsValue, Progress, Realm}; /// A host whose paths are `/` and a name, where `/d` is a folder holding `a` and `b` and every /// other path is missing. fn realm() -> Realm { + realm_with(|_| Vec::new()) + } + + /// [`realm`] with a `pick` that waits where it can and throws where it cannot. → the arguments + /// of each call, joined with `|`. + fn dialog_realm() -> (Realm, Rc>>) { + let asked: Rc>> = Rc::default(); + let calls = asked.clone(); + let r = realm_with(move |r| { + let can_wait = r.wait_flag(); + let pick = move |a: Vec| -> Result { + let text = |d: &Data| match d { + Data::String(s) => s.clone(), + Data::Bool(b) => b.to_string(), + other => format!("{other:?}"), + }; + calls.borrow_mut().push(a.iter().map(text).collect::>().join("|")); + if can_wait.get() { Err(HostError::Wait) } else { Err(HostError::Error("cannot wait here".into())) } + }; + vec![("pick".into(), HostItem::Function(Rc::new(pick)))] + }); + (r, asked) + } + + /// Advances the run until it waits or ends. → its value when it ended. + fn until_wait(r: &mut Realm) -> Option { + for _ in 0..10_000 { + match r.advance(1_000).unwrap() { + Progress::Done(v) => return Some(v), + Progress::Paused if r.waits() => return None, + Progress::Paused => {} + } + } + panic!("the run neither waited nor ended") + } + + fn realm_with(more: impl FnOnce(&Realm) -> Vec<(String, HostItem)>) -> Realm { let f = |g: fn(&[Data]) -> Data| HostItem::Function(Rc::new(move |a: Vec| Ok(g(&a)))); let text = |a: &[Data], i: usize| match a.get(i) { Some(Data::String(s)) => s.clone(), @@ -1120,7 +1178,7 @@ mod tests { Ok(obj(vec![("entries", Data::Array(vec![e("a"), e("b")]))])) }; let mut r = Realm::new(); - let items: Vec<(String, HostItem)> = vec![ + let mut items: Vec<(String, HostItem)> = vec![ ("text".into(), HostItem::Object(messages.to_vec())), ("system".into(), HostItem::Value(Data::String("Unix".into()))), ("lineFeed".into(), HostItem::Value(Data::String("Unix".into()))), @@ -1131,10 +1189,79 @@ mod tests { ("tempName".into(), f(|_| Data::String("/tmp1".into()))), ("locations".into(), f(|_| Data::Object(vec![]))), ]; + items.extend(more(&r)); r.define_file_classes(items).unwrap(); r } + #[test] + fn a_dialog_pauses_the_run_and_its_answer_becomes_files() { + let (mut r, asked) = dialog_realm(); + let v = r.run("[File.openDialog.length, File.prototype.saveDlg.length, String(Folder.selectDialog).indexOf('[native code]') > 0].join()"); + assert_eq!(v.unwrap(), JsValue::String("3,2,true".into()), "the dialogs are built-ins"); + r.start("var f = File.openDialog('Pick', 'Text:*.txt', 1); [f.length, f[0].name, f[1].fsName, f[1] instanceof File].join()").unwrap(); + assert_eq!(until_wait(&mut r), None); + assert_eq!(*asked.borrow(), ["open|Pick|true||Text:*.txt"]); + r.answer(Data::Array(vec![Data::String("/a".into()), Data::String("/b".into())])).unwrap(); + assert_eq!(until_wait(&mut r), Some(JsValue::String("2,a,/b,true".into()))); + r.start("var g = new Folder('d').selectDlg(5); [g.name, g instanceof Folder].join()").unwrap(); + assert_eq!(until_wait(&mut r), None); + assert_eq!(asked.borrow()[1], "folder|5|false|/d|", "the folder's own dialog starts at its path"); + r.answer(Data::String("/e".into())).unwrap(); + assert_eq!(until_wait(&mut r), Some(JsValue::String("e,true".into()))); + } + + #[test] + fn a_canceled_dialog_gives_null_and_an_error_answer_sets_error() { + let (mut r, asked) = dialog_realm(); + r.start( + "var d = new File('x'); var a = File.saveDialog(); var b = d.saveDlg('Save', function () { return true; }); [a, b, d.error].join('|')", + ) + .unwrap(); + assert_eq!(until_wait(&mut r), None); + r.answer(Data::Null).unwrap(); + assert_eq!(until_wait(&mut r), None, "a canceled dialog lets the run go on to the next one"); + assert_eq!(asked.borrow()[1], "save|Save|false|/x|", "a filter that is not a string gives no file types"); + r.answer(Data::Object(vec![("error".into(), Data::String("denied".into()))])).unwrap(); + assert_eq!(until_wait(&mut r), Some(JsValue::String("||denied".into()))); + r.start("File.openDialog(); 'went on'").unwrap(); + assert_eq!(until_wait(&mut r), None); + r.end(); + assert!(!r.waits() && !r.is_running(), "a run ended at a dialog drops it"); + assert_eq!(r.run("'next'").unwrap(), JsValue::String("next".into())); + let e = r.run("File.openDialog()").unwrap_err(); + assert!(e.message.contains("cannot wait here"), "a run that cannot pause does not wait: {e:?}"); + let e = r.run("File.prototype.openDlg.call({})").unwrap_err(); + assert!(e.message.contains("is not a File or a Folder"), "{e:?}"); + } + + #[test] + fn a_dialog_in_a_function_or_a_loop_resumes_where_it_was_called() { + let (mut r, asked) = dialog_realm(); + let script = "var seen = []; + function pickOne(n) { + try { var f = File.openDialog('n' + n, function (f) { return f.name !== 'skip'; }); return f === null ? 'none' : f.name; } + finally { seen.push('f' + n); } + } + for (var k = 0; k < 3; k++) seen.push(pickOne(k)); + var many = File.openDialog('m', function (f) { return f.name !== 'b'; }, true); + var thrown; + try { File.openDialog('t', function () { throw new Error('no'); }); } catch (e) { thrown = e.message; } + seen.concat([many.length, many[1].name, thrown]).join()"; + r.start(script).unwrap(); + for answer in ["/a", "/skip", "/c"] { + assert_eq!(until_wait(&mut r), None); + r.answer(Data::String(answer.into())).unwrap(); + } + assert_eq!(until_wait(&mut r), None); + r.answer(Data::Array(["/a", "/b", "/c"].map(|p| Data::String(p.into())).to_vec())).unwrap(); + assert_eq!(until_wait(&mut r), None); + r.collect_garbage(); + r.answer(Data::String("/a".into())).unwrap(); + assert_eq!(until_wait(&mut r), Some(JsValue::String("f0,a,f1,none,f2,c,2,c,no".into()))); + assert_eq!(asked.borrow().len(), 5, "each dialog asked once"); + } + #[test] fn objects_keep_their_classes_through_collections() { let mut r = realm(); diff --git a/crates/js/src/heap.rs b/crates/js/src/heap.rs index dea53c557f..3b96953e8d 100644 --- a/crates/js/src/heap.rs +++ b/crates/js/src/heap.rs @@ -177,11 +177,13 @@ pub(crate) enum NativeKind { /// 15.3.4.5): calling it calls `target` with `this` and `args` before the arguments it is given. /// `Data` is a host function given [`crate::Data`], its arguments read as `read` says. `Eval` is a /// host function that gives source to run as global code ([`crate::HostItem::Evaluator`]); `end` -/// is called when that code ends. +/// is called when that code ends. `Pausable` is a built-in that may ask the host for a value the +/// run to wait for ([`crate::interp::Pause`]). #[derive(Clone)] pub(crate) enum Func { Closure { code: Rc, env: EnvId }, Native { f: NativeFn, kind: NativeKind, constructor: bool, name: &'static str }, + Pausable { f: crate::interp::PausableFn, name: &'static str }, Host { f: Rc, name: Rc }, Data { f: DataFn, name: Rc, read: crate::host::ArgRead }, Eval { f: DataFn, end: Rc, strict_writes: Rc Option>, name: Rc }, diff --git a/crates/js/src/interp.rs b/crates/js/src/interp.rs index b6bf85bfcc..bb1de36694 100644 --- a/crates/js/src/interp.rs +++ b/crates/js/src/interp.rs @@ -165,6 +165,31 @@ type ThrowSite = (Rc, usize); /// What [`crate::Realm::observe_code`] calls with each source evaluated at run time. pub(crate) type CodeObserver = Rc; +/// A built-in function that may wait for the host ([`crate::heap::Func::Pausable`]): it is given +/// `this` and the arguments, and gives the host call it makes. +pub(crate) type PausableFn = fn(&mut Interp, Value, &[Value]) -> JsResult; + +/// What a [`PausableFn`] does with the host's answer: it is given the values it kept and the +/// answer, and gives the result of its call. +pub(crate) type ResumeFn = fn(&mut Interp, &[Value], Value) -> JsResult; + +/// The host call a [`PausableFn`] makes: the host function `host` with `args`. Its answer goes to +/// `resume` with `keep`, at once when the host answers at once. When the host waits +/// ([`crate::HostError::Wait`]), the run pauses at the call, and `resume` runs when the run goes on +/// after [`crate::Realm::answer`]; a run ended while it waits ([`crate::Realm::end`]) drops it. +pub(crate) struct Pause { + pub(crate) host: Value, + pub(crate) args: Vec, + pub(crate) keep: Vec, + pub(crate) resume: ResumeFn, +} + +/// A [`Pause`] whose host call waits for its answer. +pub(crate) struct Resumption { + resume: ResumeFn, + keep: Vec, +} + pub(crate) struct Interp { pub(crate) heap: Heap, pub(crate) stack: Vec, @@ -225,6 +250,9 @@ pub(crate) struct Interp { pub(crate) can_wait: Rc>, /// A host function's call waits for its result: the value on top of the stack stands in for it. pub(crate) waiting: bool, + /// The built-in that waits with the host's call ([`Pause::Ask`]): it takes the answer before + /// the next instruction runs. + pub(crate) resuming: Option, /// 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. @@ -472,6 +500,7 @@ impl Interp { in_slice: false, can_wait: Rc::default(), waiting: false, + resuming: None, host_abort: None, data_limits: crate::DataLimits::default(), source_tag: crate::realm::UNKNOWN_SOURCE, @@ -682,6 +711,7 @@ impl Interp { let mut roots = Roots::default(); roots.values.extend(self.stack.iter()); roots.values.extend(self.temp_roots.iter()); + roots.values.extend(self.resuming.iter().flat_map(|r| r.keep.iter())); roots.values.push(&self.last_thrown); roots.values.push(&self.last_error); roots.values.push(&self.passing); @@ -746,6 +776,14 @@ impl Interp { fn step(&mut self) -> JsResult> { self.tick()?; + // A built-in that waited for the host takes the answer on top of the stack before the + // instruction after its call runs; what it throws is thrown at that call. + if let Some(r) = self.resuming.take() { + let answer = self.pop()?; + let v = self.resume(r, answer)?; + self.push(v)?; + return Ok(None); + } let frame = self.frame_mut()?; let Some(&op) = frame.code.ops.get(frame.pc) else { return internal("ran past the end of the code") }; frame.pc += 1; @@ -2159,6 +2197,16 @@ impl Interp { self.temp_roots.truncate(mark); return Ok(Prepared::Done(r?)); } + Func::Pausable { f: native, .. } => { + let mark = self.temp_roots.len(); + self.temp_roots.push(this.clone()); + self.temp_roots.extend(args.iter().cloned()); + let held = self.held_bytes; + let r = native(self, this, &args).and_then(|p| self.ask(p)); + self.held_bytes = held; + self.temp_roots.truncate(mark); + return Ok(Prepared::Done(r?)); + } Func::Data { f, name, read } => { // The arguments are read before the function runs, and a result being built // keeps itself reachable. @@ -2384,6 +2432,41 @@ impl Interp { Ok(a) } + /// Makes the host call a [`PausableFn`] gave, whose answer goes to its resume function. A host + /// function is called as the script's own code calls it, so it may wait; then the resume + /// function is kept for the answer [`crate::Realm::answer`] gives, and the value that stands + /// in for that answer is the call's result for now. + fn ask(&mut self, p: Pause) -> JsResult { + let Pause { host, args, keep, resume } = p; + let mark = self.temp_roots.len(); + self.temp_roots.push(host.clone()); + self.temp_roots.extend(args.iter().cloned()); + self.temp_roots.extend(keep.iter().cloned()); + let was_waiting = self.waiting; + let answer = match self.func_of(&host) { + Some(Func::Data { f, name, read }) => self.call_data(&f, &name, &args, &read), + _ => self.call(&host, &Value::Undefined, &args), + }; + self.temp_roots.truncate(mark); + let answer = answer?; + let r = Resumption { resume, keep }; + if self.waiting && !was_waiting { + self.resuming = Some(r); + return Ok(answer); + } + self.resume(r, answer) + } + + /// Gives a [`PausableFn`]'s kept values and the host's `answer` to its resume function. + fn resume(&mut self, r: Resumption, answer: Value) -> JsResult { + let mark = self.temp_roots.len(); + self.temp_roots.push(answer.clone()); + self.temp_roots.extend(r.keep.iter().cloned()); + let v = (r.resume)(self, &r.keep, answer); + self.temp_roots.truncate(mark); + v + } + /// Calls `f` from Rust and returns its result, running the loop again for a function written /// in JavaScript. pub(crate) fn call(&mut self, f: &Value, this: &Value, args: &[Value]) -> JsResult { diff --git a/crates/js/src/realm.rs b/crates/js/src/realm.rs index 72a85fb66f..0a1006a23c 100644 --- a/crates/js/src/realm.rs +++ b/crates/js/src/realm.rs @@ -251,6 +251,7 @@ impl Realm { interp.last_error = Value::Null; interp.host_abort = None; interp.waiting = false; + interp.resuming = None; interp.error_tag = UNKNOWN_SOURCE; interp.thrown_mark = None; interp.finally_marks.clear(); @@ -286,6 +287,7 @@ impl Realm { interp.temp_roots.clear(); interp.join_stack.clear(); interp.waiting = false; + interp.resuming = None; interp.passing = Value::Undefined; match result { Ok(v) => Ok(interp.to_js_value(&v)), @@ -375,7 +377,9 @@ impl Realm { } /// Gives the call that waits ([`crate::HostError::Wait`]) its result `d`; the next - /// [`Realm::advance`] goes on from there. A result past the heap limit ends the run with that + /// [`Realm::advance`] goes on from there. When a built-in such as `File.openDialog` made the + /// call, the built-in takes `d` first and gives its own result, and what it throws is thrown + /// at its call. A result past the heap limit ends the run with that /// limit, and with no call waiting this gives an internal error. pub fn answer(&mut self, d: crate::Data) -> Result<(), RunError> { let interp = &mut self.interp; From fb12ddb7598d3570d6c95b9c1fc7fd98e477fe4c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 15:06:11 -0800 Subject: [PATCH 020/176] Scripts: a renamed file's old path is named in the report's written rename named only the new path in written, so a run that renamed a file an earlier run wrote did not name the path it emptied. It now names both, as remove names the path it deletes. --- crates/engine/src/script/files.rs | 2 ++ crates/engine/src/tests/script_io.rs | 23 +++++++++++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index ddc574ee71..ba2f5ec4dc 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -1763,6 +1763,8 @@ fn rename(host: &Host, a: &[Data]) -> Result { file.target = Some(if rest.as_os_str().is_empty() { to.clone() } else { to.join(rest) }); } } + // The old path no longer holds the file, so the report names it as well as the new one. + disk.wrote(&from); disk.wrote(&to); Ok(Data::Object(vec![("fs".into(), Data::String(new))])) } diff --git a/crates/engine/src/tests/script_io.rs b/crates/engine/src/tests/script_io.rs index 39276d737f..75abff6956 100644 --- a/crates/engine/src/tests/script_io.rs +++ b/crates/engine/src/tests/script_io.rs @@ -513,6 +513,29 @@ fn script_files_write_in_the_temporary_and_data_folders() { let _ = std::fs::remove_dir_all(base); } +/// `rename` of a file an earlier run wrote names both its old and its new path in `written`. +#[test] +fn a_renamed_file_names_its_old_and_new_paths_in_written() { + let base = folder("renamed"); + let mut s = with_data(&base); + let first = run_in(&mut s, &base, "var u = new File(Folder.userData.fsName + '/old.txt'); u.open('w'); u.write('x'); vc.log(u.close());"); + assert_eq!(first.unwrap()["log"], json!([true])); + let r = run_in( + &mut s, + &base, + "var u = new File(Folder.userData.fsName + '/old.txt'); var before = u.fsName;\n\ + vc.log(u.rename('new.txt')); vc.log(before); vc.log(u.fsName);", + ) + .unwrap(); + assert_eq!(r["log"][0], json!(true)); + let written: Vec<&str> = r["written"].as_array().unwrap().iter().filter_map(Value::as_str).collect(); + for at in [1, 2] { + let path = r["log"][at].as_str().unwrap(); + assert!(written.contains(&path), "{path} in {written:?}"); + } + let _ = std::fs::remove_dir_all(base); +} + /// The open modes, the encodings that cannot hold a character, `copy` over a file, `remove` of a /// folder only when it is empty, `rename` refusing a name in use, `create`, and setting `length` and /// `readonly`. From 9811cafc25bc27f07de793413ea0872556bb506d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 15:39:59 -0800 Subject: [PATCH 021/176] Scripts: copy reads its source under the rules for reading copy read the source's real path as it was when looked up, so a file replaced by a link before the read could copy a file from outside the script's places, and a link given as the source that was pointed elsewhere copied the old target. copy now reads the path as given through the same checks open uses and refuses the copy with Script file access denied when the path no longer leads to the file it was looked up as. --- crates/engine/src/script/files.rs | 29 ++++++++++--- crates/engine/src/tests/script_io.rs | 63 ++++++++++++++++++++++++++++ 2 files changed, 86 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index ba2f5ec4dc..6340912cb8 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -1663,12 +1663,19 @@ fn copy(host: &Host, a: &[Data]) -> Result { if let Err(m) = ids.iter().try_for_each(|id| disk.flush(*id)) { return Ok(error(m)); } - // The bytes are read once, no more than the limit, and those bytes are what is charged and - // written: a source that grows after it is read does not copy more. - let copied = match read_head(&source, MAX_FILE_BYTES) { - Ok(bytes) if bytes.len() > MAX_FILE_BYTES => return Ok(error(TOO_LARGE)), - Ok(bytes) => bytes, - Err(_) => return Ok(error(READ_FAILED)), + #[cfg(test)] + if let Some(hook) = BEFORE_COPY_READ.with(|h| h.borrow_mut().take()) { + hook(Path::new(&from), &source); + } + // The bytes are read once, no more than the limit, under the rules for reading, and those bytes + // are what is charged and written: a source that grows after it is read does not copy more, + // and a path that leads somewhere else than when it was looked up is refused. + let copied = match disk.scope.read(Path::new(&from), MAX_FILE_BYTES) { + Ok((at, bytes)) if at == source => bytes, + Ok(_) | Err(ScriptRead::Refused) => return Ok(error(ACCESS_DENIED)), + Err(ScriptRead::TooLarge) => return Ok(error(TOO_LARGE)), + Err(ScriptRead::Missing) => return Ok(error(NOT_FOUND)), + Err(ScriptRead::Failed(_)) => return Ok(error(READ_FAILED)), }; // The target's open objects each take a copy of the bytes, which count as written too, as does // the copy itself when it is written. @@ -2195,6 +2202,16 @@ pub(super) fn install(realm: &mut Realm, link: &super::Link) -> Result<(), RunEr realm.define_file_classes(items) } +/// Tests: what the next `copy` does with its source's path, as given and as its real path, after +/// looking it up and before reading it. +#[cfg(test)] +pub(crate) type CopyHook = Box; + +#[cfg(test)] +thread_local! { + pub(crate) static BEFORE_COPY_READ: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/engine/src/tests/script_io.rs b/crates/engine/src/tests/script_io.rs index 75abff6956..fdd75c8c57 100644 --- a/crates/engine/src/tests/script_io.rs +++ b/crates/engine/src/tests/script_io.rs @@ -513,6 +513,69 @@ fn script_files_write_in_the_temporary_and_data_folders() { let _ = std::fs::remove_dir_all(base); } +/// `copy` reads its source under the rules for reading: a source that a link to a file outside the +/// script's places replaced after it was looked up is refused, and nothing is copied. +#[cfg(unix)] +#[test] +fn a_copy_whose_source_becomes_a_link_outside_copies_nothing() { + let base = folder("copy-link"); + let mut s = with_data(&base); + let secret = base.join("secret.txt"); + write(&secret, b"secret"); + crate::script::files::BEFORE_COPY_READ.with(|h| { + *h.borrow_mut() = Some(Box::new(move |_: &Path, source: &Path| { + std::fs::remove_file(source).unwrap(); + std::os::unix::fs::symlink(&secret, source).unwrap(); + })); + }); + let r = run_in( + &mut s, + &base, + "var d = Folder.userData.fsName, a = new File(d + '/a.txt'); a.open('w'); a.write('mine'); a.close();\n\ + vc.log([a.copy(d + '/b.txt'), a.error, new File(d + '/b.txt').exists]);", + ) + .unwrap(); + crate::script::files::BEFORE_COPY_READ.with(|h| h.borrow_mut().take()); + assert_eq!(r["log"], json!([[false, "Script file access denied", false]])); + let _ = std::fs::remove_dir_all(base); +} + +/// `copy` of a link whose target changes after it was looked up is refused, also when both files +/// are in the script's places. +#[cfg(unix)] +#[test] +fn a_copy_of_a_link_that_leads_elsewhere_after_it_was_looked_up_copies_nothing() { + let base = folder("copy-relink"); + let mut s = with_data(&base); + let first = run_in( + &mut s, + &base, + "var d = Folder.userData.fsName;\n\ + ['a', 'c'].forEach(function (n) { var f = new File(d + '/' + n + '.txt'); f.open('w'); f.write(n); f.close(); });\n\ + vc.log(d);", + ) + .unwrap(); + let data = PathBuf::from(first["log"][0].as_str().unwrap()); + std::os::unix::fs::symlink(data.join("a.txt"), data.join("link.txt")).unwrap(); + let other = data.join("c.txt"); + crate::script::files::BEFORE_COPY_READ.with(|h| { + *h.borrow_mut() = Some(Box::new(move |given: &Path, _: &Path| { + std::fs::remove_file(given).unwrap(); + std::os::unix::fs::symlink(&other, given).unwrap(); + })); + }); + let r = run_in( + &mut s, + &base, + "var d = Folder.userData.fsName, l = new File(d + '/link.txt');\n\ + vc.log([l.copy(d + '/b.txt'), l.error, new File(d + '/b.txt').exists]);", + ) + .unwrap(); + crate::script::files::BEFORE_COPY_READ.with(|h| h.borrow_mut().take()); + assert_eq!(r["log"], json!([[false, "Script file access denied", false]])); + let _ = std::fs::remove_dir_all(base); +} + /// `rename` of a file an earlier run wrote names both its old and its new path in `written`. #[test] fn a_renamed_file_names_its_old_and_new_paths_in_written() { From e9baf43e1a893bf2c658edb1f487e1eba8e77494 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 16:04:00 -0800 Subject: [PATCH 022/176] Tests: a script in the settings Scripts folder reads the files beside it The settings folder is closed to scripts except for a script's own folder inside it. The test runs a script from settings/Scripts, reads a file beside it and is refused a file elsewhere in the settings folder. --- crates/engine/src/tests/script_io.rs | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/crates/engine/src/tests/script_io.rs b/crates/engine/src/tests/script_io.rs index fdd75c8c57..2f2d7fe6f5 100644 --- a/crates/engine/src/tests/script_io.rs +++ b/crates/engine/src/tests/script_io.rs @@ -1850,6 +1850,21 @@ fn script_file_grants_never_reach_the_settings_folder() { let _ = std::fs::remove_dir_all(base); } +/// A script in the Scripts folder inside the settings folder reads the files beside it, while the +/// rest of the settings folder stays closed to it. +#[test] +fn a_script_in_the_settings_scripts_folder_reads_its_own_folder() { + let base = folder("installed"); + let mut s = with_data(&base); + write(&base.join("settings/Scripts/x.txt"), b"beside"); + write(&base.join("settings/other.txt"), b"settings"); + let main = base.join("settings/Scripts/main.jsx"); + write(&main, b"var f = new File('x.txt'), g = new File(f.parent.parent.fsName + '/other.txt'); vc.log([f.open('r'), f.read(), g.open('r')]);"); + let r = s.execute("script.run", &json!({"path": main.to_string_lossy()})).unwrap(); + assert_eq!(r["log"], json!([[true, "beside", false]])); + let _ = std::fs::remove_dir_all(base); +} + /// A file dialog inside a built-in's callback throws in the app, where it cannot wait. #[test] fn script_file_dialog_in_a_callback_throws() { From a315b7ef6b2c10b4057f13a09f116d4b58cdeff2 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 17:25:12 -0800 Subject: [PATCH 023/176] Tools: setting a tool option with a bad value returns an error tool.setOption checks every option it is given before it sets any. An option the tool does not have, a value of the wrong type, a number outside the tool's range or an unknown choice is an error that names the tool and the option, for example "tool `smooth`: `fidelity` must be a number from 0.05 to 100". On an error no option, saved preference or undo step changes, also when another option in the same call is good. `{}` reads the options and sets nothing. A `tool` that is not a string, a `values` that is not an object, a `key` without a `value` and an option given both as `key` and in `values` are errors too. - Tool::check_option (and check_options for options set together) is added beside set_option, and every tool with options implements it. A tool without options takes none. Most checks use the range the setter clamped to. The Arc tool's lengthX and lengthY now take a number greater than 0 and at most 1e6, and the Line tool's length 0 to 1e6; before, a negative length was taken as its absolute value and the Arc lengths had no upper limit. The Live Paint tools and the Shape Builder use check_builder_options, so their width and gapLength are still clamped to their range. - A Place `current` given with a new `queue` is an index into that queue, and the queue is set first. A parametric shape's `kind` is set before the values given with it, and those values are checked against the new kind's ranges. - Tool Options dialogs (freehand, Liquify, Symbolism, Live Paint, Shape Builder, Objects on Path, Flare, the grid, arc and line tools and the path add-ons) stay open when an option is refused. - docs/control-protocol.md, docs/mcp.md and the tool.setOption params text describe the errors. --- crates/engine/src/tests/draw2.rs | 16 +- crates/engine/src/tests/toolsettings.rs | 102 ++++++++++++ crates/engine/src/tooling.rs | 28 +++- crates/mcp/src/tests/liquify.rs | 15 ++ crates/mcp/src/ui_catalog.rs | 2 +- crates/tools/src/addons/anchor_eraser.rs | 10 ++ crates/tools/src/addons/box3d.rs | 29 ++++ crates/tools/src/addons/contour.rs | 9 + crates/tools/src/addons/corner_tool.rs | 10 ++ crates/tools/src/addons/extend_path.rs | 8 + crates/tools/src/addons/parametric_shape.rs | 26 +++ crates/tools/src/addons/shared_edge.rs | 10 ++ crates/tools/src/addons/smart_pen.rs | 4 + crates/tools/src/builder.rs | 3 + crates/tools/src/builder/live_paint.rs | 8 + crates/tools/src/cropimage.rs | 13 ++ crates/tools/src/cut.rs | 9 + crates/tools/src/dimension.rs | 7 + crates/tools/src/distort/liquify.rs | 19 +++ crates/tools/src/distort/puppet.rs | 9 + crates/tools/src/draw2/family.rs | 19 +++ crates/tools/src/draw2/gesture.rs | 20 +++ crates/tools/src/extra.rs | 12 ++ crates/tools/src/intertwine.rs | 4 + crates/tools/src/lib.rs | 13 ++ crates/tools/src/objects_on_path.rs | 9 + crates/tools/src/option_check.rs | 154 ++++++++++++++++++ crates/tools/src/place.rs | 56 +++++++ crates/tools/src/shape.rs | 14 ++ crates/tools/src/symbolism.rs | 12 ++ crates/tools/src/text/tool.rs | 19 +++ crates/tools/src/xform/artboard.rs | 12 ++ crates/tools/src/xform/eyedropper.rs | 10 ++ crates/tools/src/xform/free.rs | 9 + crates/tools/src/xform/transform.rs | 9 + crates/ui-egui/src/addons/pathtools.rs | 7 +- crates/ui-egui/src/dialogs.rs | 10 ++ crates/ui-egui/src/dialogs/flare_options.rs | 15 +- crates/ui-egui/src/dialogs/freehand.rs | 4 +- crates/ui-egui/src/dialogs/freehand/tests.rs | 18 ++ crates/ui-egui/src/dialogs/liquify.rs | 4 +- .../ui-egui/src/dialogs/live_paint_bucket.rs | 4 +- .../src/dialogs/live_paint_selection.rs | 4 +- .../src/dialogs/objects_on_path_options.rs | 4 +- .../src/dialogs/shape_builder_options.rs | 4 +- crates/ui-egui/src/dialogs/shapes.rs | 18 +- .../ui-egui/src/dialogs/symbolism_options.rs | 4 +- .../src/dialogs/tests_rectangular_grid.rs | 14 ++ crates/ui-egui/src/menus/ui_commands.rs | 2 +- crates/ui-egui/src/toolbar.rs | 2 +- docs/control-protocol.md | 6 +- docs/mcp.md | 12 ++ docs/target-app-parity.md | 1 + 53 files changed, 796 insertions(+), 46 deletions(-) create mode 100644 crates/tools/src/option_check.rs diff --git a/crates/engine/src/tests/draw2.rs b/crates/engine/src/tests/draw2.rs index 79dbd366f6..ea6e382b5f 100644 --- a/crates/engine/src/tests/draw2.rs +++ b/crates/engine/src/tests/draw2.rs @@ -5185,14 +5185,20 @@ fn pencil_at_the_lowest_fidelity_takes_degenerate_strokes() { } } -/// The Pencil's Fidelity option takes 0.01, and the Smooth tool's stays at 0.05 or more. +/// The Pencil's Fidelity option takes 0.01, and the Smooth tool's 0.05 or more: a lower Fidelity is +/// an error that leaves the option as it was. #[test] fn pencil_option_takes_a_hundredth_and_smooth_keeps_its_floor() { let mut s = session(); - for (tool, want) in [("pencil", 0.01), ("paintbrush", 0.01), ("smooth", 0.05)] { - s.set_tool_option_cmd(&json!({"tool": tool, "values": {"fidelity": 0.001}})).unwrap(); - assert_eq!(s.tool_options_of(tool)["fidelity"].as_f64(), Some(want), "{tool}"); - s.set_tool_option_cmd(&json!({"tool": tool, "values": {"fidelity": 0.02}})).unwrap(); + for (tool, floor) in [("pencil", 0.01), ("paintbrush", 0.01), ("smooth", 0.05)] { + let before = s.tool_options_of(tool)["fidelity"].clone(); + let e = s.set_tool_option_cmd(&json!({"tool": tool, "values": {"fidelity": 0.001}})).unwrap_err(); + assert_eq!(e, format!("tool `{tool}`: `fidelity` must be a number from {floor} to 100")); + assert_eq!(s.tool_options_of(tool)["fidelity"], before, "{tool}"); + s.set_tool_option_cmd(&json!({"tool": tool, "values": {"fidelity": floor}})).unwrap(); + assert_eq!(s.tool_options_of(tool)["fidelity"].as_f64(), Some(floor), "{tool}"); + let hundredth = s.set_tool_option_cmd(&json!({"tool": tool, "values": {"fidelity": 0.02}})); + assert_eq!(hundredth.is_ok(), tool != "smooth", "{tool}"); assert_eq!(s.tool_options_of(tool)["fidelity"].as_f64(), Some(if tool == "smooth" { 0.05 } else { 0.02 }), "{tool}"); } } diff --git a/crates/engine/src/tests/toolsettings.rs b/crates/engine/src/tests/toolsettings.rs index e896a0ab32..eae2a16aa4 100644 --- a/crates/engine/src/tests/toolsettings.rs +++ b/crates/engine/src/tests/toolsettings.rs @@ -324,3 +324,105 @@ fn alt_smoothing_takes_the_smooth_tools_fidelity() { assert_eq!(s.tool_options()["fidelity"], json!(3.0), "{id}"); } } + +/// `tool.setOption` with a value of the wrong type, a number out of range, an unknown value or an +/// option the tool doesn't have is an error naming the tool and the option. Nothing is set, also +/// when another option given with it is good, and nothing is saved or recorded for undo. +#[test] +fn bad_option_values_are_errors_that_set_nothing() { + let mut s = session(); + select(&mut s, "smooth"); + let (options, saved, undo) = (s.tool_options(), s.prefs.tool_settings.clone(), s.doc().unwrap().history.undo.len()); + let fidelity = "tool `smooth`: `fidelity` must be a number from 0.05 to 100"; + for bad in [json!("abc"), json!(true), json!(-3), json!(1e9), json!(null), json!([2])] { + assert_eq!(s.set_tool_option_cmd(&json!({"key": "fidelity", "value": bad})).unwrap_err(), fidelity, "{bad}"); + } + let cases = [ + (json!({"key": "bogus", "value": 1}), "tool `smooth`: unknown option `bogus`"), + (json!({"tool": "pencil", "values": {"closeWithin": 5, "fidelity": "x"}}), "tool `pencil`: `fidelity` must be a number from 0.01 to 100"), + (json!({"tool": "pencil", "key": "fill", "value": "yes"}), "tool `pencil`: `fill` must be true or false"), + (json!({"tool": "blobBrush", "key": "sizeMode", "value": "huge"}), "tool `blobBrush`: `sizeMode` must be one of `fixed`, `pressure`"), + (json!({"tool": "eraser", "key": "fidelity", "value": 4}), "tool `eraser`: unknown option `fidelity`"), + (json!({"tool": "polygon", "key": "sides", "value": 2}), "tool `polygon`: `sides` must be a whole number from 3 to 1000"), + ( + json!({"tool": "mirrorCut", "key": "axis", "value": "diagonal"}), + "tool `mirrorCut`: `axis` must be one of `vertical`, `horizontal`, `free`", + ), + (json!({"tool": "selection", "key": "fidelity", "value": 4}), "tool `selection`: unknown option `fidelity`"), + (json!({"values": [1]}), "`values` must be an object"), + (json!({"tool": 3, "key": "fidelity", "value": 4}), "`tool` must be a tool id"), + (json!({"key": "fidelity"}), "`value` is missing for `fidelity`"), + ]; + for (p, want) in cases { + assert_eq!(s.set_tool_option_cmd(&p).unwrap_err(), want, "{p}"); + } + assert_eq!(s.tool_options_of("pencil")["closeWithin"], session().tool_options_of("pencil")["closeWithin"]); + assert_eq!((s.tool_options(), &s.prefs.tool_settings, s.doc().unwrap().history.undo.len()), (options, &saved, undo)); + // A good value after the errors is set and read back. + assert_eq!(s.set_tool_option_cmd(&json!({"key": "fidelity", "value": 9})).unwrap()["fidelity"], json!(9.0)); +} + +/// `tool.setOption {}` reads the options, of the active tool or of the tool named, and saves nothing. +#[test] +fn an_empty_set_option_reads_and_saves_nothing() { + let mut s = session(); + select(&mut s, "smooth"); + let saved = s.prefs.tool_settings.clone(); + assert_eq!(s.set_tool_option_cmd(&json!({})).unwrap(), s.tool_options()); + assert_eq!(s.set_tool_option_cmd(&json!({"tool": "flare"})).unwrap(), s.tool_options_of("flare")); + assert_eq!(s.prefs.tool_settings, saved); +} + +/// A Place queue with a malformed entry is an error, and the queue held stays as it was. +#[test] +fn a_malformed_place_queue_is_an_error() { + let mut s = session(); + select(&mut s, "place"); + let entry = json!({"params": {"svg": ""}, "name": "a", "width": 10, "height": 10}); + s.set_tool_option_cmd(&json!({"key": "queue", "value": {"entries": [entry]}})).unwrap(); + let bad = json!({"params": {}, "name": "b", "width": "wide", "height": 10}); + let e = s.set_tool_option_cmd(&json!({"key": "queue", "value": {"entries": [entry, bad]}})).unwrap_err(); + assert!(e.starts_with("tool `place`: `queue` must be"), "{e}"); + assert_eq!(s.tool_options()["names"], json!(["a"])); + assert_eq!( + s.set_tool_option_cmd(&json!({"key": "current", "value": 1})).unwrap_err(), + "tool `place`: `current` must be the index of a queued file, from 0 to 0" + ); +} + +/// A `current` given with a new Place queue picks among the files of that queue. +#[test] +fn a_place_queue_and_its_current_file_set_together() { + let mut s = session(); + select(&mut s, "place"); + let entry = |name: &str| json!({"params": {"svg": ""}, "name": name, "width": 10, "height": 10}); + let queue = json!({"entries": [entry("a"), entry("b"), entry("c")]}); + let out = s.set_tool_option_cmd(&json!({"values": {"queue": queue, "current": 2}})).unwrap(); + assert_eq!((out["names"].clone(), out["current"].clone()), (json!(["a", "b", "c"]), json!(2))); + let short = json!({"entries": [entry("d")]}); + let e = s.set_tool_option_cmd(&json!({"values": {"queue": short, "current": 2}})).unwrap_err(); + assert_eq!(e, "tool `place`: `current` must be the index of a queued file, from 0 to 0"); + assert_eq!(s.tool_options()["names"], json!(["a", "b", "c"]), "a refused call keeps the queue held"); +} + +/// A value given with a parametric shape's new `kind` is checked against that kind's range and +/// set on it, whether the tool is chosen or not. +#[test] +fn a_parametric_shape_kind_and_its_values_set_together() { + for active in [false, true] { + let mut s = session(); + if active { + select(&mut s, "parametricShape"); + } + let set = |s: &mut Session, values: serde_json::Value| s.set_tool_option_cmd(&json!({"tool": "parametricShape", "values": values})); + set(&mut s, json!({"kind": "polygon"})).unwrap(); + let out = set(&mut s, json!({"kind": "star", "a": 0.8})).unwrap(); + assert_eq!((out["kind"].clone(), out["a"].clone()), (json!("star"), json!(0.8)), "active {active}"); + set(&mut s, json!({"kind": "ring"})).unwrap(); + let out = set(&mut s, json!({"kind": "star", "a": 1.0})).unwrap(); + assert_eq!((out["kind"].clone(), out["a"].clone()), (json!("star"), json!(1.0)), "active {active}"); + let e = set(&mut s, json!({"kind": "ring", "a": 1.0})).unwrap_err(); + assert!(e.contains("`a`"), "{e}"); + assert_eq!(s.tool_options_of("parametricShape")["kind"], json!("star"), "a refused call sets nothing"); + } +} diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index 4dedfe7b28..df7ef4b1d8 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -1273,9 +1273,14 @@ impl Session { } let active = id.is_none_or(|id| id == self.tool.id()); self.tool_set_since_reset |= active; + // The Place queue and a parametric shape's kind are set first: setting the queue starts + // again at its first file, and a `current` given with it is an index into it; setting the + // kind puts the shape's other numbers back to that kind's, and those given with it are its. + let first = |k: &str| k == "queue" || k == "kind"; + let ordered = || values.iter().filter(|(k, _)| first(k)).chain(values.iter().filter(|(k, _)| !first(k))); let mut other = (!active).then(|| self.make_tool(id.unwrap_or_default())); let t = other.as_deref_mut().unwrap_or(self.tool.as_mut()); - for (k, v) in values { + for (k, v) in ordered() { t.set_option(k, v); } Self::store_tool_settings(&mut self.prefs, t); @@ -1287,7 +1292,7 @@ impl Session { // active tool. if let Some(lender) = self.lender.as_deref_mut() { if lender.id() == other.id() { - for (k, v) in values { + for (k, v) in ordered() { lender.set_option(k, v); } } @@ -1303,17 +1308,20 @@ impl Session { /// `tool.setOption {tool?, key?, value?, values?}` (a command of the desktop app and of the /// headless host): set one option (`key`, `value`) or several (`values`) of `tool` (default: - /// the active tool) → its options. + /// the active tool) → its options. With no option given, the options are read and nothing is + /// set. Every option given is checked first ([`vectorcraft_tools::Tool::check_option`]): an + /// unknown option, a value of the wrong type or a number out of range is an error that sets + /// none of them. pub fn set_tool_option_cmd(&mut self, p: &Value) -> std::result::Result { - let tool = p.get("tool").and_then(Value::as_str); + let (tool, values) = vectorcraft_tools::option_check::set_option_params(p)?; if let Some(t) = tool && vectorcraft_tools::tool_info(t).is_none() { return Err(format!("unknown tool `{t}`")); } - let mut values = p.get("values").and_then(Value::as_object).cloned().unwrap_or_default(); - if let Some(k) = p.get("key").and_then(Value::as_str) { - values.insert(k.to_string(), p.get("value").cloned().unwrap_or(Value::Null)); + let active = tool.is_none_or(|t| t == self.tool.id()); + if values.is_empty() { + return Ok(self.tool_options_of(tool.unwrap_or(self.tool.id()))); } // Every value is checked before any is set, so an invalid one changes nothing. vectorcraft_tools::builder::check_builder_options(tool.unwrap_or(self.tool.id()), &values)?; @@ -1334,8 +1342,12 @@ impl Session { return Err("Unknown dimension mode".into()); } } + match tool.filter(|_| !active) { + Some(id) => vectorcraft_tools::option_check::check_values(self.make_tool(id).as_ref(), &values)?, + None => vectorcraft_tools::option_check::check_values(self.tool.as_ref(), &values)?, + } // The active tool's merge being computed is applied with the options it was started with. - if tool.is_none_or(|t| t == self.tool.id()) { + if active { self.finish_tool_edit_later().map_err(|e| e.to_string())?; } Ok(self.set_tool_options(tool, &values)) diff --git a/crates/mcp/src/tests/liquify.rs b/crates/mcp/src/tests/liquify.rs index 4760380bc2..c6d3862384 100644 --- a/crates/mcp/src/tests/liquify.rs +++ b/crates/mcp/src/tests/liquify.rs @@ -28,6 +28,21 @@ fn tool_options_are_set_headless_and_kept_across_tool_switches() { assert_eq!(command(&mut h, "tool.setOption", json!({}))["detail"], json!(6.0)); } +/// A value the tool refuses is an error result naming the tool and the option, and the options +/// stay as they were, the good value given with it included. +#[test] +fn a_refused_option_value_is_an_error_result() { + let mut h = Headless::with_document(); + command(&mut h, "tool.select", json!({"tool": "warp"})); + let before = command(&mut h, "tool.setOption", json!({})); + for values in [json!({"width": 64, "detail": 99}), json!({"width": 64, "detail": "fine"})] { + let r = call_tool(&mut h, "run_command", &json!({"command": "tool.setOption", "params": {"values": values}})); + assert!(r.is_error, "{r:?}"); + assert!(format!("{:?}", r.content).contains("tool `warp`: `detail` must be a number from 1 to 10"), "{r:?}"); + } + assert_eq!(command(&mut h, "tool.setOption", json!({})), before); +} + #[test] fn pointer_gestures_carry_pen_pressure() { let bloat = |pressure: f64| { diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 037f8cd89b..7783f72f1f 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -775,7 +775,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "tool.setOption", "Tool Option", "", - "{key, value} | {values: {key: value…}}, tool?: id (default: the active tool) → the tool's options (`{}` reads them). The options a tool keeps (Liquify brush and tool options, Mirror & Cut, Puppet Warp, drawing tools…) last across tool switches and are saved with the preferences; another tool's are stored for when it is chosen", + "{key, value} | {values: {key: value…}}, tool?: id (default: the active tool) → the tool's options (`{}` reads them). The options a tool keeps (Liquify brush and tool options, Mirror & Cut, Puppet Warp, drawing tools…) last across tool switches and are saved with the preferences; another tool's are stored for when it is chosen. Every option is checked before any is set: an option the tool doesn't have, a value of the wrong type, a number out of the tool's range or an unknown choice is an error naming the tool and the option, and nothing changes. The Live Paint tools' width and the Shape Builder's gapLength are set to the nearest end of their range instead", ), ( "tool.toggleTouchMode", diff --git a/crates/tools/src/addons/anchor_eraser.rs b/crates/tools/src/addons/anchor_eraser.rs index 1eae255bc2..114e2b8e7a 100644 --- a/crates/tools/src/addons/anchor_eraser.rs +++ b/crates/tools/src/addons/anchor_eraser.rs @@ -152,6 +152,16 @@ impl Tool for AnchorEraserTool { _ => {} } } + + fn check_option(&self, key: &str, v: &Value) -> Result<(), String> { + use crate::option_check as c; + match key { + "size" => c::number(key, v, SIZE_RANGE.0, SIZE_RANGE.1), + "tolerance" => c::number(key, v, TOLERANCE_RANGE.0, TOLERANCE_RANGE.1), + "pressure" => c::boolean(key, v), + _ => Err(c::unknown(key)), + } + } } #[cfg(test)] diff --git a/crates/tools/src/addons/box3d.rs b/crates/tools/src/addons/box3d.rs index b0ecdc350e..e4f4b272c5 100644 --- a/crates/tools/src/addons/box3d.rs +++ b/crates/tools/src/addons/box3d.rs @@ -729,4 +729,33 @@ impl Tool for Box3dTool { _ => {} } } + + /// The options within their ranges. Any finite arc angle is taken: it is kept from 0 to 360°. + fn check_option(&self, key: &str, v: &Value) -> Result<(), String> { + use crate::option_check as c; + let max_radius = crate::shape::MAX_CORNER_RADIUS; + match key { + "shape" => c::one_of(key, v, &["box3d", "rectangle", "ellipse", "polygon", "star", "spiral"]), + "cornerRadius" => c::number(key, v, 0.0, max_radius), + "cornerRadii" => { + let radii = v.as_array().filter(|a| a.len() == 4); + if radii.is_some_and(|a| a.iter().all(|r| r.as_f64().is_some_and(|r| r.is_finite() && (0.0..=max_radius).contains(&r)))) { + Ok(()) + } else { + Err(format!("`cornerRadii` must be four numbers from 0 to {max_radius}")) + } + } + "arcStart" | "arcEnd" => c::finite(key, v), + "arcMode" => c::one_of(key, v, &["whole", "pie", "chord", "arc"]), + "sides" | "points" => c::whole(key, v, 3, 1000), + "starRatio" => c::number(key, v, 0.01, 1.0), + "rounded" | "randomized" => c::number(key, v, -10.0, 10.0), + "turns" => c::number(key, v, 0.01, 1024.0), + "divergence" => c::number(key, v, 0.0, 1000.0), + "innerRadius" => c::number(key, v, 0.0, 0.999), + "angleX" | "angleY" | "angleZ" => c::number(key, v, -180.0, 180.0), + "cornerSymmetry" | "polyIsStar" | "clockwise" | "parallelX" | "parallelY" | "parallelZ" => c::boolean(key, v), + _ => Err(c::unknown(key)), + } + } } diff --git a/crates/tools/src/addons/contour.rs b/crates/tools/src/addons/contour.rs index e77bb29eed..3bac5a6649 100644 --- a/crates/tools/src/addons/contour.rs +++ b/crates/tools/src/addons/contour.rs @@ -248,6 +248,15 @@ impl Tool for ContourTool { } } + fn check_option(&self, key: &str, value: &Value) -> Result<(), String> { + match key { + "corners" if value.as_str().and_then(Corners::parse).is_some() => Ok(()), + "corners" => Err("`corners` must be one of `sharp`, `round`, `square`".into()), + "miterLimit" => crate::option_check::number(key, value, 1.0, 500.0), + _ => Err(crate::option_check::unknown(key)), + } + } + fn busy(&self) -> bool { self.drag.is_some() } diff --git a/crates/tools/src/addons/corner_tool.rs b/crates/tools/src/addons/corner_tool.rs index 177926837e..a92f327d93 100644 --- a/crates/tools/src/addons/corner_tool.rs +++ b/crates/tools/src/addons/corner_tool.rs @@ -381,6 +381,16 @@ impl Tool for CornerTool { _ => {} } } + + fn check_option(&self, key: &str, v: &Value) -> Result<(), String> { + use crate::option_check as c; + match key { + "radius" => c::number(key, v, 0.0, MAX_RADIUS), + "kind" if serde_json::from_value::(v.clone()).is_ok() => Ok(()), + "kind" => Err("`kind` must be one of `round`, `invertedRound`, `chamfer`".into()), + _ => Err(c::unknown(key)), + } + } } #[cfg(test)] diff --git a/crates/tools/src/addons/extend_path.rs b/crates/tools/src/addons/extend_path.rs index d1f54861ca..b53d52d3e8 100644 --- a/crates/tools/src/addons/extend_path.rs +++ b/crates/tools/src/addons/extend_path.rs @@ -203,6 +203,14 @@ impl Tool for ExtendPathTool { self.mode = Mode(m); } } + + fn check_option(&self, key: &str, v: &Value) -> Result<(), String> { + if key != "mode" { + return Err(crate::option_check::unknown(key)); + } + let ids: Vec<&str> = ExtendMode::ALL.iter().map(|m| m.id()).collect(); + crate::option_check::one_of(key, v, &ids) + } } #[cfg(test)] diff --git a/crates/tools/src/addons/parametric_shape.rs b/crates/tools/src/addons/parametric_shape.rs index d16cb63935..61ce83ecde 100644 --- a/crates/tools/src/addons/parametric_shape.rs +++ b/crates/tools/src/addons/parametric_shape.rs @@ -434,6 +434,32 @@ impl Tool for ParametricShapeTool { self.next = s; } } + + /// The numbers [`Self::options`] shows, each as [`apply`] checks it; null is not a value. + fn check_option(&self, key: &str, v: &Value) -> Result<(), String> { + if self.options().get(key).is_none() { + return Err(crate::option_check::unknown(key)); + } + if v.is_null() { + return Err(format!("`{key}` must not be null")); + } + apply(self.next, &json!({ key: v })).map(|_| ()) + } + + /// The options together, as [`apply`] takes them: a `kind` given with them sets the kind + /// first, and the other values are checked against that kind's ranges. + fn check_options(&self, values: &serde_json::Map) -> Result<(), String> { + let options = self.options(); + for (key, v) in values { + if options.get(key).is_none() { + return Err(crate::option_check::unknown(key)); + } + if v.is_null() { + return Err(format!("`{key}` must not be null")); + } + } + apply(self.next, &Value::Object(values.clone())).map(|_| ()) + } } #[cfg(test)] diff --git a/crates/tools/src/addons/shared_edge.rs b/crates/tools/src/addons/shared_edge.rs index d11261800a..703e8e6f3f 100644 --- a/crates/tools/src/addons/shared_edge.rs +++ b/crates/tools/src/addons/shared_edge.rs @@ -214,6 +214,16 @@ impl Tool for SharedEdgeTool { _ => {} } } + + fn check_option(&self, key: &str, v: &Value) -> Result<(), String> { + use crate::option_check as c; + match key { + "diameter" => c::number(key, v, DIAMETER_RANGE.0, DIAMETER_RANGE.1), + "tolerance" => c::number(key, v, 0.0, MAX_COINCIDENCE), + "together" => c::boolean(key, v), + _ => Err(c::unknown(key)), + } + } } #[cfg(test)] diff --git a/crates/tools/src/addons/smart_pen.rs b/crates/tools/src/addons/smart_pen.rs index cd72f1dd40..40ba482f8b 100644 --- a/crates/tools/src/addons/smart_pen.rs +++ b/crates/tools/src/addons/smart_pen.rs @@ -624,6 +624,10 @@ impl Tool for SmartPenTool { } } } + + fn check_option(&self, key: &str, v: &Value) -> Result<(), String> { + if key == "next" { crate::option_check::one_of(key, v, &["curved", "straight"]) } else { Err(crate::option_check::unknown(key)) } + } } #[cfg(test)] diff --git a/crates/tools/src/builder.rs b/crates/tools/src/builder.rs index 2190d34180..55214e8b7b 100644 --- a/crates/tools/src/builder.rs +++ b/crates/tools/src/builder.rs @@ -775,6 +775,9 @@ impl Tool for ShapeBuilderTool { self.cache.clear(); self.cache.gap = self.gap(); } + fn check_option(&self, key: &str, v: &Value) -> Result<(), String> { + check_builder_options(self.id(), &serde_json::Map::from_iter([(key.to_string(), v.clone())])) + } } /// Why `tool.setOption` cannot give the builder-family tool `tool` the options `values`, checked diff --git a/crates/tools/src/builder/live_paint.rs b/crates/tools/src/builder/live_paint.rs index 6b744e4435..fc27bbde59 100644 --- a/crates/tools/src/builder/live_paint.rs +++ b/crates/tools/src/builder/live_paint.rs @@ -437,6 +437,10 @@ impl Tool for LivePaintBucketTool { self.hover = LpHover::None; } + fn check_option(&self, key: &str, v: &Value) -> Result<(), String> { + check_live_paint_options(self.id(), &serde_json::Map::from_iter([(key.to_string(), v.clone())])) + } + fn waiting(&self) -> bool { self.cache.waiting() } @@ -737,4 +741,8 @@ impl Tool for LivePaintSelectionTool { } self.hover = LpHover::None; } + + fn check_option(&self, key: &str, v: &Value) -> Result<(), String> { + check_live_paint_options(self.id(), &serde_json::Map::from_iter([(key.to_string(), v.clone())])) + } } diff --git a/crates/tools/src/cropimage.rs b/crates/tools/src/cropimage.rs index ff716bf171..e0fa322e3e 100644 --- a/crates/tools/src/cropimage.rs +++ b/crates/tools/src/cropimage.rs @@ -268,6 +268,19 @@ impl Tool for CropImageTool { }; } + /// `rect` is `[x, y, width, height]`, or null to put the box back where it starts. + fn check_option(&self, key: &str, value: &Value) -> Result<(), String> { + if key != "rect" { + return Err(crate::option_check::unknown(key)); + } + let numbers = value.as_array().filter(|a| a.len() == 4).and_then(|a| a.iter().map(Value::as_f64).collect::>>()); + match numbers.as_deref() { + _ if value.is_null() => Ok(()), + Some([x, y, w, h]) if [x, y, w, h].iter().all(|n| n.is_finite()) && *w >= 0.0 && *h >= 0.0 => Ok(()), + _ => Err(format!("`{key}` must be [x, y, width, height]: four finite numbers, width and height not negative")), + } + } + fn deactivate(&mut self, _cx: &ToolContext) -> Vec { self.reset(); vec![] diff --git a/crates/tools/src/cut.rs b/crates/tools/src/cut.rs index 906a632fb3..514e41e4c0 100644 --- a/crates/tools/src/cut.rs +++ b/crates/tools/src/cut.rs @@ -214,6 +214,15 @@ impl Tool for CutTool { _ => {} } } + /// Mirror & Cut's `axis` and `keep`; the other cutting tools have no options. + fn check_option(&self, key: &str, v: &Value) -> Result<(), String> { + use crate::option_check as c; + match (self.id, key) { + ("mirrorCut", "axis") => c::one_of(key, v, &["vertical", "horizontal", "free"]), + ("mirrorCut", "keep") => c::one_of(key, v, &["left", "right", "top", "bottom"]), + _ => Err(c::unknown(key)), + } + } } #[cfg(test)] diff --git a/crates/tools/src/dimension.rs b/crates/tools/src/dimension.rs index 14f7f85881..515ff33039 100644 --- a/crates/tools/src/dimension.rs +++ b/crates/tools/src/dimension.rs @@ -460,6 +460,13 @@ impl Tool for DimensionTool { self.style = o; } } + fn check_option(&self, key: &str, value: &Value) -> Result<(), String> { + match key { + "mode" => crate::option_check::one_of(key, value, &["linear", "angular", "radial", "radius", "diameter"]), + "style" => DimensionOptions::from_params(value.clone()).map(|_| ()), + _ => Err(crate::option_check::unknown(key)), + } + } fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec { self.at = ev.pos; self.shift = ev.mods.shift; diff --git a/crates/tools/src/distort/liquify.rs b/crates/tools/src/distort/liquify.rs index efc68132a1..0606e36a74 100644 --- a/crates/tools/src/distort/liquify.rs +++ b/crates/tools/src/distort/liquify.rs @@ -829,6 +829,25 @@ impl Tool for LiquifyTool { } } } + /// The options of [`LiquifyParams::from_json`] within its ranges, `diameter` for both sizes, + /// `showBrush`, and `tool` naming this tool. A percentage is a fraction up to 1 and a percent + /// above it. + fn check_option(&self, key: &str, value: &Value) -> Result<(), String> { + use crate::option_check as c; + match key { + "tool" if value.as_str() == Some(self.params.kind.id()) => Ok(()), + "tool" => Err(format!("`tool` must be `{}`", self.params.kind.id())), + "diameter" | "width" | "height" => c::number(key, value, 0.5, 10_000.0), + "angle" => c::finite(key, value), + "intensity" | "horizontal" | "vertical" => c::number(key, value, 0.0, 100.0), + "detail" => c::number(key, value, 1.0, 10.0), + "simplify" => c::number(key, value, 0.0, 100.0), + "rate" => c::number(key, value, -180.0, 180.0), + "complexity" => c::number(key, value, 0.0, 15.0), + "showBrush" | "usePressure" | "simplifyOn" | "affectAnchors" | "affectIn" | "affectOut" => c::boolean(key, value), + _ => Err(c::unknown(key)), + } + } /// The tool claims Escape during an Alt-drag that sizes the brush. fn claims_key(&self, _cx: &ToolContext, key: ToolKey) -> bool { key == ToolKey::Escape && self.sizing.is_some() diff --git a/crates/tools/src/distort/puppet.rs b/crates/tools/src/distort/puppet.rs index f141378382..5a1e03cd1b 100644 --- a/crates/tools/src/distort/puppet.rs +++ b/crates/tools/src/distort/puppet.rs @@ -515,6 +515,15 @@ impl Tool for PuppetWarpTool { _ => {} } } + /// `showMesh`, `selectAllPins` and `expand`; `pins` and `selected` are read only. + fn check_option(&self, key: &str, value: &Value) -> Result<(), String> { + use crate::option_check as c; + match key { + "showMesh" | "selectAllPins" => c::boolean(key, value), + "expand" => c::number(key, value, 0.0, 1000.0), + _ => Err(c::unknown(key)), + } + } fn busy(&self) -> bool { self.drag.is_some() } diff --git a/crates/tools/src/draw2/family.rs b/crates/tools/src/draw2/family.rs index 8058101b1c..1dbeb83750 100644 --- a/crates/tools/src/draw2/family.rs +++ b/crates/tools/src/draw2/family.rs @@ -509,6 +509,25 @@ impl Tool for FamilyTool { } } } + /// The options the tool shows ([`Self::options`]): those of the arc, the spiral or the grid. + fn check_option(&self, key: &str, v: &Value) -> Result<(), String> { + use crate::option_check as c; + if self.options().get(key).is_none() { + return Err(c::unknown(key)); + } + let skew = vectorcraft_geom::shapes::GRID_SKEW_MAX; + match key { + "lengthX" | "lengthY" | "width" | "height" => c::positive(key, v, 1e6), + "reference" => c::whole(key, v, 0, 8), + "baseAlong" => c::one_of(key, v, &["x", "y", "X", "Y"]), + "slope" => c::number(key, v, -100.0, 100.0), + "decay" => c::number(key, v, 5.0, 150.0), + "segments" => c::whole(key, v, 2, 1000), + "rows" | "concentric" | "columns" | "radial" => c::whole(key, v, 0, 999), + "rowSkew" | "concentricSkew" | "columnSkew" | "radialSkew" => c::number(key, v, -skew, skew), + _ => c::boolean(key, v), + } + } } /// Arc segment length from a dialog or preference value. diff --git a/crates/tools/src/draw2/gesture.rs b/crates/tools/src/draw2/gesture.rs index 9aed6f545b..9450ed14ca 100644 --- a/crates/tools/src/draw2/gesture.rs +++ b/crates/tools/src/draw2/gesture.rs @@ -1644,6 +1644,26 @@ impl Tool for GestureTool { _ => {} } } + /// The options the tool shows ([`Self::options`]), and the Smooth tool's Fidelity that the + /// Pencil, Paintbrush and Blob Brush smooth with while Alt is held (`smoothFidelity`). + fn check_option(&self, key: &str, v: &Value) -> Result<(), String> { + use crate::option_check as c; + let smooth_store = key == "smoothFidelity" && matches!(self.id, "pencil" | "paintbrush" | "blobBrush"); + if !smooth_store && self.options().get(key).is_none() { + return Err(c::unknown(key)); + } + match key { + "fidelity" => c::number(key, v, super::min_fidelity(self.id), 100.0), + "smoothFidelity" => c::number(key, v, super::min_fidelity("smooth"), 100.0), + "size" => c::number(key, v, 0.1, 1000.0), + "sizeVariation" => c::number(key, v, 0.0, 1000.0), + "angle" => c::number(key, v, -180.0, 180.0), + "roundness" => c::number(key, v, if self.id == "blobBrush" { 0.0 } else { 1.0 }, 100.0), + "editWithin" | "closeWithin" => c::number(key, v, 0.0, 100.0), + "sizeMode" => c::one_of(key, v, &["fixed", "pressure"]), + _ => c::boolean(key, v), + } + } } #[cfg(test)] diff --git a/crates/tools/src/extra.rs b/crates/tools/src/extra.rs index d1a2672402..e5a0a280f4 100644 --- a/crates/tools/src/extra.rs +++ b/crates/tools/src/extra.rs @@ -267,6 +267,18 @@ impl Tool for FlareTool { } } } + /// The switches and [`FLARE_OPTIONS`] within their ranges, the counts whole. + fn check_option(&self, key: &str, v: &Value) -> Result<(), String> { + use crate::option_check as c; + if matches!(key, "raysOn" | "ringsOn") { + return c::boolean(key, v); + } + let Some(&(_, _, lo, hi)) = FLARE_OPTIONS.iter().find(|(k, ..)| *k == key) else { return Err(c::unknown(key)) }; + if is_count(key) && v.as_f64().is_none_or(|n| n.fract() != 0.0) { + return Err(format!("`{key}` must be a whole number from {lo} to {hi}")); + } + c::number(key, v, lo, hi) + } } /// Where a Reshape press landed on a selected path. diff --git a/crates/tools/src/intertwine.rs b/crates/tools/src/intertwine.rs index fb292ea37c..5fed3b07f3 100644 --- a/crates/tools/src/intertwine.rs +++ b/crates/tools/src/intertwine.rs @@ -343,6 +343,10 @@ impl Tool for IntertwineTool { } } + fn check_option(&self, key: &str, value: &Value) -> Result<(), String> { + if key == "prev" { crate::option_check::string_or_null(key, value) } else { Err(crate::option_check::unknown(key)) } + } + fn busy(&self) -> bool { self.dragging } diff --git a/crates/tools/src/lib.rs b/crates/tools/src/lib.rs index d46a7fd972..200ca37625 100644 --- a/crates/tools/src/lib.rs +++ b/crates/tools/src/lib.rs @@ -27,6 +27,7 @@ pub mod meshedit; pub mod mirror; pub mod nineslice; pub mod objects_on_path; +pub mod option_check; pub mod params; pub mod pathtype; pub mod pen; @@ -150,6 +151,18 @@ pub trait Tool: Send { Value::Null } fn set_option(&mut self, _key: &str, _value: &Value) {} + /// Whether [`Self::set_option`] takes `value` for option `key` as it is: an error names an + /// option the tool doesn't have, a value of the wrong type or a number out of range + /// (`tool.setOption` checks every option it is given with this before it sets any). A tool + /// without options takes none. + fn check_option(&self, key: &str, _value: &Value) -> Result<(), String> { + Err(option_check::unknown(key)) + } + /// Whether [`Self::set_option`] takes all of `values`, set together in one call: by default + /// each one checked on its own with [`Self::check_option`]. + fn check_options(&self, values: &serde_json::Map) -> Result<(), String> { + values.iter().try_for_each(|(k, v)| self.check_option(k, v)) + } /// Is an interaction in progress (drag, open pen path)? fn busy(&self) -> bool { false diff --git a/crates/tools/src/objects_on_path.rs b/crates/tools/src/objects_on_path.rs index 8f19259126..a452e9e79d 100644 --- a/crates/tools/src/objects_on_path.rs +++ b/crates/tools/src/objects_on_path.rs @@ -971,6 +971,15 @@ impl Tool for ObjectsOnPathTool { } } + fn check_option(&self, key: &str, value: &Value) -> Result<(), String> { + use crate::option_check as c; + match key { + "pivot" => c::whole(key, value, 0, 8), + "rotate" => c::number(key, value, -360.0, 360.0), + _ => Err(c::unknown(key)), + } + } + fn busy(&self) -> bool { self.press.is_some() || self.rotating.is_some() || self.spacing.is_some() || self.moving.is_some() || self.member.is_some() } diff --git a/crates/tools/src/option_check.rs b/crates/tools/src/option_check.rs new file mode 100644 index 0000000000..9c16deb9cf --- /dev/null +++ b/crates/tools/src/option_check.rs @@ -0,0 +1,154 @@ +//! Checks of tool option values ([`crate::Tool::check_option`]) and of `tool.setOption`'s +//! parameters. Each error names the option and what it takes. + +use serde_json::{Map, Value}; + +use crate::Tool; + +/// The error for an option the tool doesn't have. +pub fn unknown(key: &str) -> String { + format!("unknown option `{key}`") +} + +/// `v` is a finite number from `lo` to `hi`. +pub fn number(key: &str, v: &Value, lo: f64, hi: f64) -> Result<(), String> { + match v.as_f64() { + Some(n) if n.is_finite() && (lo..=hi).contains(&n) => Ok(()), + _ => Err(format!("`{key}` must be a number from {lo} to {hi}")), + } +} + +/// `v` is a finite number. +pub fn finite(key: &str, v: &Value) -> Result<(), String> { + match v.as_f64() { + Some(n) if n.is_finite() => Ok(()), + _ => Err(format!("`{key}` must be a finite number")), + } +} + +/// `v` is a finite number above 0 and at most `hi`. +pub fn positive(key: &str, v: &Value, hi: f64) -> Result<(), String> { + match v.as_f64() { + Some(n) if n > 0.0 && n <= hi => Ok(()), + _ => Err(format!("`{key}` must be a number above 0 and at most {hi}")), + } +} + +/// `v` is a whole number (written without a fraction) from `lo` to `hi`. +pub fn whole(key: &str, v: &Value, lo: u64, hi: u64) -> Result<(), String> { + match v.as_u64() { + Some(n) if (lo..=hi).contains(&n) => Ok(()), + _ => Err(format!("`{key}` must be a whole number from {lo} to {hi}")), + } +} + +/// `v` is true or false. +pub fn boolean(key: &str, v: &Value) -> Result<(), String> { + if v.is_boolean() { Ok(()) } else { Err(format!("`{key}` must be true or false")) } +} + +/// `v` is one of the strings `choices`. +pub fn one_of(key: &str, v: &Value, choices: &[&str]) -> Result<(), String> { + if v.as_str().is_some_and(|s| choices.contains(&s)) { + Ok(()) + } else { + let list: Vec = choices.iter().map(|c| format!("`{c}`")).collect(); + Err(format!("`{key}` must be one of {}", list.join(", "))) + } +} + +/// `v` is a string, or null. +pub fn string_or_null(key: &str, v: &Value) -> Result<(), String> { + if v.is_string() || v.is_null() { Ok(()) } else { Err(format!("`{key}` must be a string or null")) } +} + +/// What `tool.setOption {tool?, key?, value?, values?}` sets: the tool named (none: the active +/// tool) and the options, `key` and `value` among `values`. A parameter of the wrong type, a +/// `value` without a `key` or a `key` without a `value`, and an option given both as `key` and in +/// `values` are errors. With none of `key` and `values`, the options are empty: the command reads +/// them. +pub fn set_option_params(p: &Value) -> Result<(Option<&str>, Map), String> { + let tool = match p.get("tool") { + None => None, + Some(t) => Some(t.as_str().ok_or("`tool` must be a tool id")?), + }; + let mut values = match p.get("values") { + None => Map::new(), + Some(v) => v.as_object().cloned().ok_or("`values` must be an object")?, + }; + match (p.get("key"), p.get("value")) { + (None, None) => {} + (Some(k), v) => { + let k = k.as_str().ok_or("`key` must be a string")?; + let v = v.ok_or_else(|| format!("`value` is missing for `{k}`"))?; + if values.contains_key(k) { + return Err(format!("`{k}` is given both as `key` and in `values`")); + } + values.insert(k.to_string(), v.clone()); + } + (None, Some(_)) => return Err("`value` needs a `key`".into()), + } + Ok((tool, values)) +} + +/// Check every one of `values` as an option of `tool` ([`Tool::check_options`]), before any is +/// set: the first one the tool doesn't take is an error that names the tool. +pub fn check_values(tool: &dyn Tool, values: &Map) -> Result<(), String> { + tool.check_options(values).map_err(|e| format!("tool `{}`: {e}", tool.id())) +} + +#[cfg(test)] +mod tests { + use serde_json::json; + + use super::*; + + #[test] + fn numbers_are_checked_against_their_range() { + assert!(number("fidelity", &json!(0.05), 0.05, 100.0).is_ok()); + assert!(number("fidelity", &json!(100), 0.05, 100.0).is_ok()); + for bad in [json!(-3), json!(1e9), json!("abc"), json!(true), json!(null), json!(0.04)] { + assert_eq!(number("fidelity", &bad, 0.05, 100.0), Err("`fidelity` must be a number from 0.05 to 100".into()), "{bad}"); + } + assert!(whole("sides", &json!(3), 3, 1000).is_ok()); + for bad in [json!(2), json!(3.5), json!(1001), json!(-1), json!("6")] { + assert!(whole("sides", &bad, 3, 1000).is_err(), "{bad}"); + } + assert!(positive("width", &json!(0), 1e6).is_err()); + assert!(positive("width", &json!(1e6), 1e6).is_ok()); + assert!(finite("angle", &json!(720)).is_ok()); + assert!(finite("angle", &json!("720")).is_err()); + } + + #[test] + fn other_values_are_checked_by_kind() { + assert!(boolean("fill", &json!(false)).is_ok()); + assert_eq!(boolean("fill", &json!(0)), Err("`fill` must be true or false".into())); + assert!(one_of("axis", &json!("free"), &["vertical", "free"]).is_ok()); + assert_eq!(one_of("axis", &json!("diagonal"), &["vertical", "free"]), Err("`axis` must be one of `vertical`, `free`".into())); + assert!(string_or_null("prev", &json!(null)).is_ok()); + assert!(string_or_null("prev", &json!(3)).is_err()); + } + + #[test] + fn set_option_params_reads_the_tool_and_the_options() { + let p = json!({"tool": "smooth", "key": "fidelity", "value": 2, "values": {"x": 1}}); + let (tool, values) = set_option_params(&p).unwrap(); + assert_eq!(tool, Some("smooth")); + assert_eq!(Value::Object(values), json!({"fidelity": 2, "x": 1})); + let empty = json!({}); + let (tool, values) = set_option_params(&empty).unwrap(); + assert!(tool.is_none() && values.is_empty()); + assert_eq!(set_option_params(&json!({"tool": 3})).err(), Some("`tool` must be a tool id".into())); + assert_eq!(set_option_params(&json!({"values": [1]})).err(), Some("`values` must be an object".into())); + assert_eq!(set_option_params(&json!({"key": 3, "value": 1})).err(), Some("`key` must be a string".into())); + assert_eq!(set_option_params(&json!({"key": "fill"})).err(), Some("`value` is missing for `fill`".into())); + assert_eq!(set_option_params(&json!({"value": 1})).err(), Some("`value` needs a `key`".into())); + assert_eq!( + set_option_params(&json!({"key": "fill", "value": true, "values": {"fill": false}})).err(), + Some("`fill` is given both as `key` and in `values`".into()) + ); + // An explicit null is a value: the Type tool's triggers take one. + assert!(set_option_params(&json!({"key": "stopEditing", "value": null})).is_ok()); + } +} diff --git a/crates/tools/src/place.rs b/crates/tools/src/place.rs index af67b38c00..360645f671 100644 --- a/crates/tools/src/place.rs +++ b/crates/tools/src/place.rs @@ -183,6 +183,33 @@ impl Tool for PlaceTool { } } + /// A queue whose every entry has its `params` object and a finite `width` and `height`, and + /// `current` within the queue held. + fn check_option(&self, key: &str, value: &Value) -> Result<(), String> { + match key { + "queue" => check_queue(value).map(drop), + "current" => check_current(value, self.entries.len()), + _ => Err(crate::option_check::unknown(key)), + } + } + + /// As [`Self::check_option`], except that a `current` given with a `queue` is an index into + /// that queue (the queue is set first). + fn check_options(&self, values: &serde_json::Map) -> Result<(), String> { + let mut held = self.entries.len(); + if let Some(queue) = values.get("queue") { + held = check_queue(queue)?; + } + for (k, v) in values { + match k.as_str() { + "queue" => {} + "current" => check_current(v, held)?, + _ => self.check_option(k, v)?, + } + } + Ok(()) + } + /// Switching tools discards what the cursor holds. fn deactivate(&mut self, _cx: &ToolContext) -> Vec { self.entries.clear(); @@ -191,6 +218,35 @@ impl Tool for PlaceTool { } } +/// The number of files `queue` holds, or an error when an entry lacks its `params` object or a +/// finite `width` and `height`. +fn check_queue(queue: &Value) -> Result { + let entry = |e: &Value| { + e.get("params").is_some_and(Value::is_object) + && e.get("name").is_none_or(Value::is_string) + && ["width", "height"].iter().all(|k| e.get(k).and_then(Value::as_f64).is_some_and(f64::is_finite)) + }; + let entries = match queue.get("entries") { + None => Some(0), + Some(e) => e.as_array().filter(|a| a.iter().all(entry)).map(Vec::len), + }; + match entries { + Some(n) if queue.is_object() && queue.get("prev").is_none_or(Value::is_string) => Ok(n), + _ => Err("`queue` must be {entries: [{params, name, width, height}], prev?}: each entry with a params object and a finite \ + width and height" + .into()), + } +} + +/// `current` is the index of one of the `held` files. +fn check_current(current: &Value, held: usize) -> Result<(), String> { + match held { + _ if current.as_u64().is_some_and(|i| i < held as u64) => Ok(()), + 0 => Err("`current` can't be set: no file is queued".into()), + _ => Err(format!("`current` must be the index of a queued file, from 0 to {}", held - 1)), + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/tools/src/shape.rs b/crates/tools/src/shape.rs index 66728b4826..7489e74a32 100644 --- a/crates/tools/src/shape.rs +++ b/crates/tools/src/shape.rs @@ -817,6 +817,20 @@ impl Tool for ShapeTool { } } } + /// The options every shape tool keeps ([`Self::options`]). Any finite angle is taken: it is + /// kept as the same direction from 0 to 360°. + fn check_option(&self, key: &str, v: &Value) -> Result<(), String> { + use crate::option_check as c; + match key { + "sides" | "points" => c::whole(key, v, 3, 1000), + "cornerRadius" => c::number(key, v, 0.0, MAX_CORNER_RADIUS), + "starRatio" => c::number(key, v, 0.01, 1.0), + "length" => c::number(key, v, 0.0, 1e6), + "angle" => c::finite(key, v), + "fillLine" => c::boolean(key, v), + _ => Err(c::unknown(key)), + } + } } #[cfg(test)] diff --git a/crates/tools/src/symbolism.rs b/crates/tools/src/symbolism.rs index 1618d6e7d6..c0e1d97137 100644 --- a/crates/tools/src/symbolism.rs +++ b/crates/tools/src/symbolism.rs @@ -222,6 +222,15 @@ impl Tool for SymbolismTool { _ => {} } } + fn check_option(&self, key: &str, v: &Value) -> Result<(), String> { + use crate::option_check as c; + match key { + "diameter" => c::number(key, v, 2.0, 2000.0), + "intensity" | "density" => c::number(key, v, 1.0, 10.0), + "symbol" | "style" => c::string_or_null(key, v), + _ => Err(c::unknown(key)), + } + } } /// Paintbrush: the freehand gesture, painting with the current brush. @@ -288,6 +297,9 @@ impl Tool for BrushPaintTool { self.inner.set_option(key, v); } } + fn check_option(&self, key: &str, v: &Value) -> Result<(), String> { + if key == "brush" { crate::option_check::string_or_null(key, v) } else { self.inner.check_option(key, v) } + } fn wants_samples(&self) -> bool { self.inner.wants_samples() } diff --git a/crates/tools/src/text/tool.rs b/crates/tools/src/text/tool.rs index dd561bc616..44c6c1b0f6 100644 --- a/crates/tools/src/text/tool.rs +++ b/crates/tools/src/text/tool.rs @@ -608,6 +608,25 @@ impl Tool for TypeTool { _ => {} } } + /// The calls [`Self::set_option`] takes: `commitTyping`, `endTyping`, `selectAll` and + /// `stopEditing` take any value, the others the shapes they read. + fn check_option(&self, key: &str, v: &Value) -> Result<(), String> { + let index = |a: &str, b: &str| v.get(a).or_else(|| v.get(b)).and_then(Value::as_u64).is_some(); + let ok = match key { + "textSelection" => index("editing", "id") && index("anchor", "start") && index("caret", "end"), + "select" => index("start", "start") && index("end", "end"), + "prevTool" | "previousTool" => return crate::option_check::string_or_null(key, v), + "copy" => serde_json::from_value::>(v.clone()).is_ok(), + "commitTyping" | "endTyping" | "selectAll" | "stopEditing" => true, + _ => return Err(crate::option_check::unknown(key)), + }; + let shape = match key { + "textSelection" => "{editing, anchor, caret} with whole numbers", + "select" => "{start, end} with whole numbers", + _ => "a list of text runs", + }; + if ok { Ok(()) } else { Err(format!("`{key}` must be {shape}")) } + } fn overlays(&self, cx: &ToolContext) -> Vec { let mut o = self.snap.guides().to_vec(); if let (Some((_, s)), Some(d)) = (self.press, self.drag) { diff --git a/crates/tools/src/xform/artboard.rs b/crates/tools/src/xform/artboard.rs index 5af642c44b..e8cac59c88 100644 --- a/crates/tools/src/xform/artboard.rs +++ b/crates/tools/src/xform/artboard.rs @@ -726,6 +726,18 @@ impl Tool for ArtboardTool { } } + fn check_option(&self, key: &str, value: &Value) -> Result<(), String> { + use crate::option_check as c; + match key { + "active" if value.as_u64().is_some() => Ok(()), + "active" => Err("`active` must be an artboard index: a whole number from 0".into()), + "selected" if value.as_array().is_some_and(|a| !a.is_empty() && a.iter().all(|i| i.as_u64().is_some())) => Ok(()), + "selected" => Err("`selected` must be a list of artboard indexes, the active one first".into()), + "moveArt" | "scaleArt" | "suppressFitClick" => c::boolean(key, value), + _ => Err(c::unknown(key)), + } + } + /// A drag is moving or resizing artboards (Artboard Options › Update While Dragging reads it). fn transforming(&self) -> bool { matches!(self.drag, Some(Drag::Move { began: true, .. } | Drag::Resize { began: true, .. })) diff --git a/crates/tools/src/xform/eyedropper.rs b/crates/tools/src/xform/eyedropper.rs index c5e05f004b..ce6b722f53 100644 --- a/crates/tools/src/xform/eyedropper.rs +++ b/crates/tools/src/xform/eyedropper.rs @@ -517,6 +517,16 @@ impl Tool for EyedropperTool { } } + fn check_option(&self, key: &str, value: &Value) -> Result<(), String> { + use crate::option_check as c; + match key { + "stop" => c::string_or_null(key, value), + "brushKeyColor" => c::boolean(key, value), + "textSelection" => self.text_selection.check_option(key, value), + _ => Err(c::unknown(key)), + } + } + /// Drop the range when its text is removed or no longer selected. fn after_command(&mut self, cx: &ToolContext) -> Vec { self.text_selection.after_command(cx) diff --git a/crates/tools/src/xform/free.rs b/crates/tools/src/xform/free.rs index 1583584940..a747b38efe 100644 --- a/crates/tools/src/xform/free.rs +++ b/crates/tools/src/xform/free.rs @@ -379,6 +379,15 @@ impl Tool for FreeTransformTool { } } + fn check_option(&self, key: &str, value: &Value) -> Result<(), String> { + use crate::option_check as c; + match key { + "mode" => c::one_of(key, value, &["free", "perspective", "distort", "freeDistort"]), + "constrain" => c::boolean(key, value), + _ => Err(c::unknown(key)), + } + } + fn deactivate(&mut self, _cx: &ToolContext) -> Vec { self.quad = None; self.guides.clear(); diff --git a/crates/tools/src/xform/transform.rs b/crates/tools/src/xform/transform.rs index 263c0ea5e4..b8de339af4 100644 --- a/crates/tools/src/xform/transform.rs +++ b/crates/tools/src/xform/transform.rs @@ -337,6 +337,15 @@ impl Tool for TransformTool { } } + /// `origin` is `[x, y]`, or null to clear it. + fn check_option(&self, key: &str, value: &Value) -> Result<(), String> { + if key != "origin" { + return Err(crate::option_check::unknown(key)); + } + let point = value.as_array().is_some_and(|a| a.len() == 2 && a.iter().all(|n| n.as_f64().is_some_and(f64::is_finite))); + if point || value.is_null() { Ok(()) } else { Err("`origin` must be [x, y] with finite numbers, or null".into()) } + } + fn deactivate(&mut self, _cx: &ToolContext) -> Vec { if self.end_drag().is_some_and(|d| d.began) { vec![Action::Cancel] } else { vec![] } } diff --git a/crates/ui-egui/src/addons/pathtools.rs b/crates/ui-egui/src/addons/pathtools.rs index bfbcf0d5b3..c41a3f41b0 100644 --- a/crates/ui-egui/src/addons/pathtools.rs +++ b/crates/ui-egui/src/addons/pathtools.rs @@ -239,12 +239,15 @@ fn body(_app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> bool { false } -/// OK: set the tool's options. +/// OK: set the tool's options. When the tool refuses one of them, nothing is set and the dialog +/// stays open. fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { let tool = d.str("__tool"); let values: Map = d.fields.iter().filter(|(k, _)| !k.starts_with("__")).map(|(k, v)| (k.clone(), v.clone())).collect(); let r = app.run("tool.setOption", json!({ "tool": tool, "values": values })); - app.ui.dialog = None; + if r.is_ok() { + app.ui.dialog = None; + } r } diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 552fbc0c06..c8d931f412 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -621,6 +621,16 @@ fn run_and_close(app: &mut VectorcraftApp, id: &str, params: Value) -> DialogRes r } +/// Set a tool's options with `tool.setOption` (`params`) and close the dialog; when the tool +/// refuses one of them, nothing is set and the dialog stays open. +fn set_tool_options_and_close(app: &mut VectorcraftApp, params: Value) -> DialogResult { + let r = app.run("tool.setOption", params); + if r.is_ok() { + app.ui.dialog = None; + } + r +} + /// The field of a dialog opened over another (Import Shortcut Set over Keyboard Shortcuts) that /// holds the dialog under it, which Cancel and Escape show again. pub(crate) const PARENT: &str = "__parent"; diff --git a/crates/ui-egui/src/dialogs/flare_options.rs b/crates/ui-egui/src/dialogs/flare_options.rs index b94f6a7c2e..9da15fe4a2 100644 --- a/crates/ui-egui/src/dialogs/flare_options.rs +++ b/crates/ui-egui/src/dialogs/flare_options.rs @@ -16,7 +16,7 @@ use vectorcraft_geom::Point; use vectorcraft_tools::extra::{FLARE_OPTIONS, flare_params}; use super::document_setup::check; -use super::{DialogResult, DialogSpec, form, run_and_close}; +use super::{DialogResult, DialogSpec, form, set_tool_options_and_close}; use crate::state::Dialog; use crate::{VectorcraftApp, widgets}; @@ -154,12 +154,14 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> DialogResult { values.insert(key.into(), json!(d.bool(key))); } if let Some((cmd, params)) = command { + // Options the tool would refuse leave the dialog open, before the flare is accepted. + vectorcraft_tools::option_check::check_values(vectorcraft_tools::create("flare").as_ref(), &values)?; // Accept the preview once; option persistence follows successful artwork creation. let result = form::commit_preview(app, &cmd, params)?; app.run("tool.setOption", json!({ "tool": "flare", "values": values }))?; Ok(result) } else { - run_and_close(app, "tool.setOption", json!({ "tool": "flare", "values": values })) + set_tool_options_and_close(app, json!({ "tool": "flare", "values": values })) } } @@ -311,10 +313,11 @@ mod tests { super::super::confirm(&mut app).unwrap(); let parts = flare_parts(&app); assert_eq!(parts.iter().filter(|p| *p == "Ring").count(), 3, "{parts:?}"); - // Out-of-range values are kept within the option's range. - app.run("tool.setOption", json!({"tool": "flare", "values": {"opacity": 900, "diameter": -4}})).unwrap(); - let o = app.session.tool_options_of("flare"); - assert_eq!((o["opacity"].as_f64(), o["diameter"].as_f64()), (Some(100.0), Some(0.0))); + // An out-of-range value is an error, and no option changes. + let before = app.session.tool_options_of("flare"); + let e = app.run("tool.setOption", json!({"tool": "flare", "values": {"opacity": 50, "diameter": -4}})).unwrap_err(); + assert_eq!(e, "tool `flare`: `diameter` must be a number from 0 to 1000"); + assert_eq!(app.session.tool_options_of("flare"), before); } #[test] diff --git a/crates/ui-egui/src/dialogs/freehand.rs b/crates/ui-egui/src/dialogs/freehand.rs index 48f31731cc..00abac95d4 100644 --- a/crates/ui-egui/src/dialogs/freehand.rs +++ b/crates/ui-egui/src/dialogs/freehand.rs @@ -16,7 +16,7 @@ use serde_json::{Map, Value, json}; use super::document_setup::check; -use super::{DialogSpec, form, run_and_close}; +use super::{DialogSpec, form, set_tool_options_and_close}; use crate::state::Dialog; use crate::theme::Tokens; use crate::{VectorcraftApp, widgets}; @@ -315,7 +315,7 @@ fn blob_tip_short_ratio(roundness: f64) -> f32 { /// OK: set the tool's options. fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { let values: Map = KEYS.iter().filter_map(|k| Some((k.to_string(), d.fields.get(*k)?.clone()))).collect(); - run_and_close(app, "tool.setOption", json!({ "tool": d.str("tool"), "values": values })) + set_tool_options_and_close(app, json!({ "tool": d.str("tool"), "values": values })) } #[cfg(test)] diff --git a/crates/ui-egui/src/dialogs/freehand/tests.rs b/crates/ui-egui/src/dialogs/freehand/tests.rs index 35d216bc77..df5071cf41 100644 --- a/crates/ui-egui/src/dialogs/freehand/tests.rs +++ b/crates/ui-egui/src/dialogs/freehand/tests.rs @@ -28,6 +28,24 @@ fn blob_tip_fields_confirm_and_cancel() { assert_eq!(app.session.tool_options_of("blobBrush")["roundness"], json!(0.0)); } +/// OK with a Fidelity the Smooth tool refuses shows the error and keeps the dialog open, with +/// nothing set; a Fidelity it takes then closes it. +#[test] +fn a_refused_fidelity_keeps_the_dialog_open() { + let mut app = app(); + app.run("tool.options", json!({"tool": "smooth"})).unwrap(); + let before = app.session.tool_options_of("smooth"); + app.ui.dialog.as_mut().unwrap().fields.insert("fidelity".into(), json!(0.01)); + let e = super::super::confirm(&mut app).unwrap_err(); + assert_eq!(e, "tool `smooth`: `fidelity` must be a number from 0.05 to 100"); + assert!(app.ui.dialog.is_some(), "the dialog stays open"); + assert_eq!(app.session.tool_options_of("smooth"), before); + app.ui.dialog.as_mut().unwrap().fields.insert("fidelity".into(), json!(5)); + super::super::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(app.session.tool_options_of("smooth")["fidelity"], json!(5.0)); +} + #[test] fn the_tip_preview_is_as_flat_as_the_tip_the_brush_draws() { for roundness in [-5.0, 0.0, 0.05, 0.1, 1.0, 50.0, 100.0, 120.0] { diff --git a/crates/ui-egui/src/dialogs/liquify.rs b/crates/ui-egui/src/dialogs/liquify.rs index 40aa677f17..18b8e48418 100644 --- a/crates/ui-egui/src/dialogs/liquify.rs +++ b/crates/ui-egui/src/dialogs/liquify.rs @@ -12,7 +12,7 @@ use serde_json::{Map, Value, json}; use vectorcraft_tools::distort::liquify::LiquifyKind; use super::document_setup::check; -use super::{DialogSpec, form, run_and_close}; +use super::{DialogSpec, form, set_tool_options_and_close}; use crate::state::Dialog; use crate::theme::Tokens; use crate::{VectorcraftApp, widgets}; @@ -145,7 +145,7 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { values.insert(key.into(), json!(d.f64(key, 0.0) / 100.0)); } } - run_and_close(app, "tool.setOption", json!({ "tool": kind(d).id(), "values": values })) + set_tool_options_and_close(app, json!({ "tool": kind(d).id(), "values": values })) } #[cfg(test)] diff --git a/crates/ui-egui/src/dialogs/live_paint_bucket.rs b/crates/ui-egui/src/dialogs/live_paint_bucket.rs index c040cdcc31..cdce096e6b 100644 --- a/crates/ui-egui/src/dialogs/live_paint_bucket.rs +++ b/crates/ui-egui/src/dialogs/live_paint_bucket.rs @@ -14,7 +14,7 @@ use vectorcraft_doc::LAYER_COLORS; use vectorcraft_tools::builder::LP_BUCKET_WIDTH_RANGE; use super::tile_edge_color::{checked, resolve}; -use super::{DialogSpec, form, run_and_close}; +use super::{DialogSpec, form, set_tool_options_and_close}; use crate::state::Dialog; use crate::{VectorcraftApp, widgets}; @@ -84,7 +84,7 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { checked(&d.str("color"))?; } let values: Map = KEYS.iter().filter_map(|k| Some((k.to_string(), d.fields.get(*k)?.clone()))).collect(); - run_and_close(app, "tool.setOption", json!({ "tool": TOOL, "values": values })) + set_tool_options_and_close(app, json!({ "tool": TOOL, "values": values })) } #[cfg(test)] diff --git a/crates/ui-egui/src/dialogs/live_paint_selection.rs b/crates/ui-egui/src/dialogs/live_paint_selection.rs index a1a91ad2b7..95584c2f96 100644 --- a/crates/ui-egui/src/dialogs/live_paint_selection.rs +++ b/crates/ui-egui/src/dialogs/live_paint_selection.rs @@ -13,7 +13,7 @@ use vectorcraft_doc::LAYER_COLORS; use vectorcraft_tools::builder::LP_SELECT_WIDTH_RANGE; use super::tile_edge_color::{checked, resolve}; -use super::{DialogSpec, form, run_and_close}; +use super::{DialogSpec, form, set_tool_options_and_close}; use crate::state::Dialog; use crate::{VectorcraftApp, widgets}; @@ -80,7 +80,7 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { checked(&d.str("color"))?; } let values: Map = KEYS.iter().filter_map(|k| Some((k.to_string(), d.fields.get(*k)?.clone()))).collect(); - run_and_close(app, "tool.setOption", json!({ "tool": TOOL, "values": values })) + set_tool_options_and_close(app, json!({ "tool": TOOL, "values": values })) } #[cfg(test)] diff --git a/crates/ui-egui/src/dialogs/objects_on_path_options.rs b/crates/ui-egui/src/dialogs/objects_on_path_options.rs index 8a02cd37cf..7180fd6105 100644 --- a/crates/ui-egui/src/dialogs/objects_on_path_options.rs +++ b/crates/ui-egui/src/dialogs/objects_on_path_options.rs @@ -11,7 +11,7 @@ use serde_json::{Map, Value, json}; use vectorcraft_doc::objects_on_path::CENTER; -use super::{DialogSpec, run_and_close}; +use super::{DialogSpec, set_tool_options_and_close}; use crate::state::Dialog; use crate::{VectorcraftApp, widgets}; @@ -70,7 +70,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { /// Save: set the tool's Pivot and Rotate. fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { let values: Map = ["pivot", "rotate"].iter().filter_map(|k| Some((k.to_string(), d.fields.get(*k)?.clone()))).collect(); - run_and_close(app, "tool.setOption", json!({ "tool": TOOL, "values": values })) + set_tool_options_and_close(app, json!({ "tool": TOOL, "values": values })) } #[cfg(test)] diff --git a/crates/ui-egui/src/dialogs/shape_builder_options.rs b/crates/ui-egui/src/dialogs/shape_builder_options.rs index 9393e0707e..d4edbad1f9 100644 --- a/crates/ui-egui/src/dialogs/shape_builder_options.rs +++ b/crates/ui-egui/src/dialogs/shape_builder_options.rs @@ -14,7 +14,7 @@ use vectorcraft_color::Color; use vectorcraft_doc::LAYER_COLORS; use super::tile_edge_color::{checked, resolve}; -use super::{DialogSpec, form, run_and_close}; +use super::{DialogSpec, form, set_tool_options_and_close}; use crate::state::Dialog; use crate::{VectorcraftApp, widgets}; @@ -124,7 +124,7 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { checked(&d.str("highlightColor"))?; } let values: Map = KEYS.iter().filter_map(|k| Some((k.to_string(), d.fields.get(*k)?.clone()))).collect(); - run_and_close(app, "tool.setOption", json!({ "tool": "shapeBuilder", "values": values })) + set_tool_options_and_close(app, json!({ "tool": "shapeBuilder", "values": values })) } #[cfg(test)] diff --git a/crates/ui-egui/src/dialogs/shapes.rs b/crates/ui-egui/src/dialogs/shapes.rs index 392c043f35..e2342e6dd4 100644 --- a/crates/ui-egui/src/dialogs/shapes.rs +++ b/crates/ui-egui/src/dialogs/shapes.rs @@ -102,8 +102,8 @@ fn line_length_angle(d: &Dialog) -> (f64, f64) { fn arc_options(d: &Dialog) -> Value { json!({ "closed": d.str("arcType").eq_ignore_ascii_case("closed"), - "lengthX": d.f64("lengthX", 100.0), - "lengthY": d.f64("lengthY", 100.0), + "lengthX": d.f64("lengthX", 100.0).abs(), + "lengthY": d.f64("lengthY", 100.0).abs(), "reference": arc_reference(d), "baseAlong": d.str("baseAlong"), "slope": d.f64("slope", 50.0), @@ -371,13 +371,11 @@ fn box_origin(d: &Dialog) -> (f64, f64) { fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { // Tool Options: the options the tool's next drag and click use; nothing is drawn. if d.bool(TOOL_OPTIONS) { - let r = app.run("tool.setOption", json!({"tool": d.kind, "values": tool_options(d)})); - app.ui.dialog = None; - return r; + return super::set_tool_options_and_close(app, json!({"tool": d.kind, "values": tool_options(d)})); } let count = match d.kind.as_str() { "polygon" => Some(("sides", 6.0, 3.0)), - "star" => Some(("points", 5.0, 2.0)), + "star" => Some(("points", 5.0, 3.0)), _ => None, }; let options = count @@ -454,7 +452,13 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result { // On the active plane while the perspective grid shows, sized in plane units from the click; // else along General › Constrain Angle, turned about the point the dialog places at the click // (a grid's reference point, the other shapes' top-left corner or centre). - let options = options.or_else(|| (d.kind == "spiral").then(|| params.clone())); + let options = options.or_else(|| { + (d.kind == "spiral").then(|| json!({"decay": params["decay"], "segments": params["segments"], "clockwise": params["clockwise"]})) + }); + // Options the tool would refuse leave the dialog open, before anything is drawn. + if let Some(Value::Object(o)) = &options { + vectorcraft_tools::option_check::check_values(vectorcraft_tools::create(&d.kind).as_ref(), o)?; + } let result = match vectorcraft_engine::perspective_click(&app.session, id, ¶ms, vectorcraft_geom::Point::new(x, y)) { Some((id, params)) => run_and_close(app, &id, params), None => { diff --git a/crates/ui-egui/src/dialogs/symbolism_options.rs b/crates/ui-egui/src/dialogs/symbolism_options.rs index 33d902b90e..05392bbd4f 100644 --- a/crates/ui-egui/src/dialogs/symbolism_options.rs +++ b/crates/ui-egui/src/dialogs/symbolism_options.rs @@ -6,7 +6,7 @@ use serde_json::{Map, Value, json}; -use super::{DialogResult, DialogSpec, form, run_and_close}; +use super::{DialogResult, DialogSpec, form, set_tool_options_and_close}; use crate::state::Dialog; use crate::{VectorcraftApp, widgets}; @@ -50,7 +50,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { /// OK: set the brush the Symbolism tools share (the tool keeps it within its ranges). fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> DialogResult { let values: Map = KEYS.iter().filter(|k| d.fields.contains_key(**k)).map(|k| (k.to_string(), json!(d.f64(k, 0.0)))).collect(); - run_and_close(app, "tool.setOption", json!({ "tool": d.str("tool"), "values": values })) + set_tool_options_and_close(app, json!({ "tool": d.str("tool"), "values": values })) } #[cfg(test)] diff --git a/crates/ui-egui/src/dialogs/tests_rectangular_grid.rs b/crates/ui-egui/src/dialogs/tests_rectangular_grid.rs index ef5dca5ede..e2db8b6d75 100644 --- a/crates/ui-egui/src/dialogs/tests_rectangular_grid.rs +++ b/crates/ui-egui/src/dialogs/tests_rectangular_grid.rs @@ -339,6 +339,20 @@ fn rectangular_grid_failed_creation_does_not_save_counts() { assert_eq!(app.session.doc().unwrap().history.undo.len(), before.undo); } +/// Tool Options with a width the tool refuses is an error that keeps the dialog open and sets +/// nothing. +#[test] +fn rectangular_grid_tool_options_with_a_refused_width_stay_open() { + let mut app = app(); + let before = app.session.tool_options_of(KIND); + super::shapes::open_options(&mut app, KIND).unwrap(); + set(&mut app, "width", json!(0)); + let e = super::confirm(&mut app).unwrap_err(); + assert!(e.contains("`width`"), "{e}"); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some(KIND)); + assert_eq!(app.session.tool_options_of(KIND), before); +} + /// #1377: the dialog shows the tool's stored skews (sliders under their divider counts) and /// switches; OK draws with them and stores them, and the next drag uses them too. #[test] diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 0b490352e3..582bc77802 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -776,7 +776,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "tool.setOption", "Tool Option", "", - "{key, value} | {values: {key: value…}}, tool?: id (default: the active tool) → the tool's options (`{}` reads them). The options a tool keeps (Liquify brush and tool options, Mirror & Cut, Puppet Warp, drawing tools…) last across tool switches and are saved with the preferences; another tool's are stored for when it is chosen", + "{key, value} | {values: {key: value…}}, tool?: id (default: the active tool) → the tool's options (`{}` reads them). The options a tool keeps (Liquify brush and tool options, Mirror & Cut, Puppet Warp, drawing tools…) last across tool switches and are saved with the preferences; another tool's are stored for when it is chosen. Every option is checked before any is set: an option the tool doesn't have, a value of the wrong type, a number out of the tool's range or an unknown choice is an error naming the tool and the option, and nothing changes. The Live Paint tools' width and the Shape Builder's gapLength are set to the nearest end of their range instead", ), ( crate::touch::TOGGLE_MODE, diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index 29d89ebf6d..3e6625fa93 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -1148,7 +1148,7 @@ fn puppet_warp_options(app: &mut VectorcraftApp, ui: &mut Ui) { ui.label(egui::RichText::new(tl!("Expand:")).size(12.0).color(t.text)); let unit = app.session.general_unit(); if let Some(v) = widgets::num_field(ui, ("cb-tool", "expand"), opts["expand"].as_f64(), unit, 64.0) { - app.run("tool.setOption", json!({ "key": "expand", "value": v })).ok(); + app.run("tool.setOption", json!({ "key": "expand", "value": v.clamp(0.0, 1000.0) })).ok(); } let show = opts["showMesh"].as_bool().unwrap_or(true); if widgets::check(ui, "Show Mesh", show, true) { diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 45f4d0141b..a32c3272df 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -921,7 +921,11 @@ Halftone… (`engine.execute {command: "ui.menuDialog", params: {command: "objec Tool options last: `tool.setOption {key, value}` or `{values: {…}}` (and `tool` to set another tool's) sets them, and the options a tool keeps (Liquify brush and tool options, Mirror & Cut, Puppet Warp, Symbolism, drawing tools) stay when you switch tools or documents and are saved with the preferences. The Liquify tools share their Global Brush -Dimensions (`width`, `height`, `angle`, `intensity`). +Dimensions (`width`, `height`, `angle`, `intensity`). `{}` reads the options and sets nothing. Every option given is +checked before any is set: an option the tool doesn't have, a value of the wrong type, a number outside the tool's +range or an unknown choice is an error that names the tool and the option +(``tool `smooth`: `fidelity` must be a number from 0.05 to 100``), and no option, preference or undo step changes. +The Live Paint tools' `width` and the Shape Builder's `gapLength` are set to the nearest end of their range instead. Perspective grid: View → Perspective Grid → Define Grid… (`ui.perspectiveGridDialog`) opens the `perspectiveGrid` dialog prefilled from the grid. Its fields are those of `perspective.grid.define` (`kind`, `units`, `scale`, diff --git a/docs/mcp.md b/docs/mcp.md index 912ac32562..3901375542 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -9811,10 +9811,22 @@ intensity), and the Symbolism tools one brush. Interaction state (pins, a refere desktop app, while the Artboard tool is in use, a change to its `selected` or `active` makes the artboard it then has active the active artboard (the navigator's and the Artboards panel's). +Every option given is checked before any is set. A key that the tool's `check_option` does not take (it is unknown +to that tool), a value of the wrong type, a number outside the tool's range, an unknown choice, a `key` without a +`value`, a `values` that is not an object or a `tool` that is not a tool id is an error result that names the tool and +the option, and nothing changes: no option, no saved preference and no undo step, also when another option given with +it is good. `{}` reads the options and sets nothing. The ranges are VectorCraft's own (for example the Smooth tool's +`fidelity` takes 0.05 to 100, the Pencil's 0.01 to 100); a refused value in a Tool Options dialog keeps the dialog +open. The Live Paint tools' `width` and the Shape Builder's `gapLength` are set to the nearest end of their range +when a number outside it is given, as their sections above say. + ```json {"name":"run_command","arguments":{"command":"tool.setOption","params":{"tool":"twirl","values":{"width":60,"rate":90}}}} +{"name":"run_command","arguments":{"command":"tool.setOption","params":{"tool":"smooth","key":"fidelity","value":-3}}} ``` +The second call returns the error ``tool `smooth`: `fidelity` must be a number from 0.05 to 100``. + The Pencil's, the Paintbrush's and the Smooth tool's `fidelity` is in screen pixels: the tools send `path.freehand` and `path.smoothRegion` the option divided by the zoom, so a stroke keeps as many points and a Smooth drag smooths as much at any zoom. The Smooth tool's `fidelity` (0.05 to 100 px, 2.5 by default) is also the one an Alt smoothing drag with diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 26681e5b7f..5ed24c7b9d 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -747,6 +747,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Parameter schemas:** a command can carry a machine-readable parameter schema (the new `vectorcraft-apischema` crate): each parameter's type, range, unit, whether it is required, its default, whether null counts as left out, and the API levels it was added and deprecated at. `engine.commands` lists the schema in the shape of a JSON Schema 2020-12 object schema, a test keeps the command's `params` text equal to the text the schema writes, and a new call has the params checked against it before the command runs (batch steps before the first step), with an error naming the parameter and no change to the document (a value nested past the schema's 16 levels is such a parameter error, and only a schema that is wrong in itself is an internal error); saved steps keep a key the schema does not name, and their values are checked. The View commands `view.capsLock`, `view.saved.new`, `view.saved.edit`, `view.saved.list`, `view.transparencyGrid` and `view.snapToGlyph.options` have schemas. The schemas belong to API level 1 (`vectorcraft_engine::schemas::API_VERSION`), and a test fails when a schema changes without a new level. Tests: `crates/apischema/src/tests.rs` (with `conformance.rs`, a separate check of the JSON form against the JSON Schema 2020-12 rules), `schemas::tests` and `cmd::views::tests::each_view_command_refuses_a_bad_value_naming_the_parameter` in `vectorcraft-engine`. - **Input schemas in the command listings:** `engine.commands` and the MCP tools `command_list` and `list_commands` give each command with a parameter schema an `inputSchema` next to `schema`: the same schema with the root `type` `"object"`, the form an MCP tool's input schema takes ([MCP schema reference](https://modelcontextprotocol.io/specification/2026-07-28/schema)). A command without a schema lists neither, and `brief` leaves out both schemas with the `params` text. Tests: `schemas::tests::engine_commands_list_an_input_schema_with_an_object_root` and `schemas::tests::an_input_schema_keeps_deprecation` in `vectorcraft-engine`, and `tests::conventions::command_listings_carry_input_schemas` in `vectorcraft-mcp`, which check every listed input schema against the JSON Schema 2020-12 rules. - **Command API reference:** `engine.apiReference` returns a Markdown reference written from the parameter schemas when it is asked for, and MCP serves the same text as the resource `vectorcraft://commands/reference` (`text/markdown; charset=utf-8`). Each command that has a schema gets a section in registry order with its label, menu path, API levels, what it writes, summary and return, and a table of its parameters (type, range with its ends marked included or not, unit, default, required, levels and description; members of objects as dotted rows). Commands without a schema, plug-in commands included, are left out. Schema text is escaped so it stays plain text in its table cell, the same build always returns the same bytes, and a reference past 1 MiB is an error rather than a cut-short text. The command's own schema raised the API level to 2. This is a VectorCraft documentation feature; no score changes. Tests: `cmd::apiref::tests` and `schemas::tests` in `vectorcraft-engine`, `resources::tests` in `vectorcraft-mcp`. +- **Tool option errors:** `tool.setOption` checks every option it is given before it sets any: an option the tool doesn't have, a value of the wrong type, a number outside the tool's range or an unknown choice is an error naming the tool and the option (``tool `smooth`: `fidelity` must be a number from 0.05 to 100``), and no option, saved preference or undo step changes; `{}` only reads. Most ranges are the ones each tool's setter clamped to; the Arc tool's `lengthX` and `lengthY` take more than 0 up to 1e6 and the Line tool's `length` 0 to 1e6, where a negative length was taken as its absolute value. The Live Paint tools' `width` and the Shape Builder's `gapLength` are still set to the nearest end of their range. A Tool Options dialog with a refused value stays open. This is VectorCraft's own rule; no score changes. Tests: `option_check::tests` in `vectorcraft-tools`, `tests::toolsettings` in `vectorcraft-engine`, `tests::liquify` in `vectorcraft-mcp`, `dialogs::freehand::tests::a_refused_fidelity_keeps_the_dialog_open`. - **Automation:** - Variables: Update Data Set writes what the art holds into the active data set for the variables that data set holds, and keeps the data set's value for a text, image or graph variable whose objects are locked or inside a locked layer or group; `dataset.update {all: true}` also adds the other variables that the art reports a value for. - Variables: `dataset.select`, `dataset.next` and `dataset.prev` rewrite type and apply the other values on hidden objects and in hidden layers and groups, which stay hidden unless a visibility value shows them, so a layer shown later holds the selected data set's text; objects that are locked or in a locked layer or group are skipped, except by a visibility value. From 859d8639f4af5f21c345441d534c3b194392305b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 17:20:09 -0800 Subject: [PATCH 024/176] .ai import and save: Scatter brush art comes in turned over, as Art brush art does A Scatter brush read from a .ai or EPS editing copy kept its art as its section holds it, so every copy the brush placed was upside down. The art is now turned over when it is read, as an Art brush's already is: in each copy the side of the section with y up goes down the page before the copy's rotation. The .ai writer now writes Scatter art unflipped, so a saved brush opens again with the same art. A .ai saved by an earlier development build with a Scatter brush (the writer added on 2026-11-07, in no release) opens with that brush's art turned over. Docs: docs/file-format-parity.md, docs/target-app-parity.md. --- crates/eps/src/ai_editing/tests.rs | 34 ++++++++++++ crates/eps/src/ai_editing/writer/brushes.rs | 7 ++- crates/eps/src/import/ai/brush.rs | 7 ++- crates/eps/src/import/ai/tests.rs | 61 +++++++++++++++++++++ docs/file-format-parity.md | 2 +- docs/target-app-parity.md | 1 + 6 files changed, 107 insertions(+), 5 deletions(-) diff --git a/crates/eps/src/ai_editing/tests.rs b/crates/eps/src/ai_editing/tests.rs index 3af515181c..3f1f6eb9c1 100644 --- a/crates/eps/src/ai_editing/tests.rs +++ b/crates/eps/src/ai_editing/tests.rs @@ -8336,6 +8336,40 @@ fn brush_art_of_a_straight_line_comes_back_as_the_line() { } } +/// A Scatter brush's art is written turned over into its section (y up), so the side that is down the +/// page in the brush's copies is up in the section: a triangle with its point down comes out with +/// its point above its base, and comes back with its point down. +#[test] +fn a_scatter_brushs_art_is_written_turned_over() { + use vectorcraft_brush::{Brush, BrushKind, Scatter}; + use vectorcraft_geom::{Point, SubPath}; + let point_down = PathData { subpaths: vec![SubPath::polyline(&[Point::new(0.0, 0.0), Point::new(40.0, 0.0), Point::new(20.0, 10.0)], true)] }; + let art = Node::path(vectorcraft_doc::NodeId(1), point_down, Appearance::basic(black_fill(), Paint::None, 0.0)); + let lib = vec![Brush { name: "Wedge".into(), kind: BrushKind::Scatter(Scatter { art, ..Scatter::default() }) }]; + let mut doc = Document::new(300.0, 200.0); + vectorcraft_brush::store(&mut doc, &lib); + let text = program(&doc); + let start = text.find("%AI8_BeginBrushPattern").unwrap(); + let end = start + text[start..].find("%AI8_EndBrushPattern").unwrap(); + // The points of the frame and the triangle: the triangle's point is the one between the + // frame's left and right edges. + let points: Vec<(f64, f64)> = text[start..end] + .lines() + .filter_map(|l| l.strip_suffix(" m").or_else(|| l.strip_suffix(" L"))) + .filter_map(|l| { + let mut n = l.split_whitespace().map(|v| v.parse::().ok()); + Some((n.next()??, n.next()??)) + }) + .collect(); + let (left, right) = points.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(l, r), p| (l.min(p.0), r.max(p.0))); + let bottom = points.iter().map(|p| p.1).fold(f64::INFINITY, f64::min); + let tip: Vec = points.iter().filter(|p| p.0 > left + 1e-3 && p.0 < right - 1e-3).map(|p| p.1).collect(); + assert!(!tip.is_empty() && tip.iter().all(|y| (y - bottom - 10.0).abs() < 1e-3), "the point is 10 above the base in the section: {points:?}"); + let back = vectorcraft_brush::library(&read_back(&doc)); + let (BrushKind::Scatter(got), BrushKind::Scatter(want)) = (&back[0].kind, &lib[0].kind) else { panic!("{back:?}") }; + assert!(same_tree(&art_tree(&got.art), &art_tree(&want.art)), "{:#?}", got.art); +} + /// Brush art of a path with several subpaths is written as a compound path, which the reader reads as /// a compound path of one path for each subpath, and is weighed as the reader weighs that against the /// art it copies into one file's brushes: of two Art brushes whose art is a path of 30,000 squares, diff --git a/crates/eps/src/ai_editing/writer/brushes.rs b/crates/eps/src/ai_editing/writer/brushes.rs index 2c281e702d..69cc49a19f 100644 --- a/crates/eps/src/ai_editing/writer/brushes.rs +++ b/crates/eps/src/ai_editing/writer/brushes.rs @@ -326,11 +326,12 @@ impl Writer<'_> { fn brush_out(&mut self, b: &Brush) -> Option { let plugin = crate::import::brush_plugin_name(&b.kind); let section = format!("Brush Art {}", self.brush_set.sections + 1); - // The art as the reader reads it: a section is read with y down, and an Art brush's art is - // turned over after that (its section's y up is the right of the path). + // The art as the reader reads it: a section is read with y down, and a Scatter or Art + // brush's art is turned over after that (its section's y up is down the page in each + // Scatter copy and the right of the path in Art). let (params, art) = match &b.kind { BrushKind::Calligraphic(c) => (calligraphic_params(c), None), - BrushKind::Scatter(s) => (scatter_params(s, §ion)?, Some((s.art.clone(), Affine::FLIP_Y))), + BrushKind::Scatter(s) => (scatter_params(s, §ion)?, Some((s.art.clone(), Affine::IDENTITY))), BrushKind::Art(a) => (art_params(a, §ion)?, Some((a.art.clone(), Affine::IDENTITY))), BrushKind::Pattern(_) | BrushKind::Bristle(_) => return None, }; diff --git a/crates/eps/src/import/ai/brush.rs b/crates/eps/src/import/ai/brush.rs index 5a5db47114..4be0776849 100644 --- a/crates/eps/src/import/ai/brush.rs +++ b/crates/eps/src/import/ai/brush.rs @@ -452,7 +452,12 @@ pub(super) fn finish_brushes_within( let kind = match d.kind { _ if !kept => None, DraftKind::Calligraphic(c) => Some(BrushKind::Calligraphic(c)), - DraftKind::Scatter { brush, art: name } => copy(&name).map(|a| BrushKind::Scatter(Scatter { art: a, ..brush })), + DraftKind::Scatter { brush, art: name } => copy(&name).map(|mut a| { + // Each copy is the section turned over: its side with y up draws down the page + // before the copy's rotation, and a brush draws art's y (down here) down the page. + a.transform(Affine::scale_non_uniform(1.0, -1.0), false); + BrushKind::Scatter(Scatter { art: a, ..brush }) + }), DraftKind::Art { brush, art: name, .. } => copy(&name).map(|mut a| { // The side of the section with y up draws on the right of the path, and a brush // draws art's y (down here) on the left of the path. diff --git a/crates/eps/src/import/ai/tests.rs b/crates/eps/src/import/ai/tests.rs index e2a1943de7..09a3fe97ce 100644 --- a/crates/eps/src/import/ai/tests.rs +++ b/crates/eps/src/import/ai/tests.rs @@ -10546,6 +10546,67 @@ fn type_with_an_art_brush_keeps_its_drawn_look() { assert_eq!(brushed, 0, "{:?}", r.warnings); } +/// Each copy a Scatter brush places is its section's art turned over before the copy's rotation: +/// the side of the section with y up goes down the page with the rotation at 0° to the page, and +/// to the right of the path's direction when the rotation follows the path. A rotation turns the +/// copy counterclockwise on the page, from the page or from the path's direction. +#[test] +fn a_scatter_brushs_copies_are_its_art_turned_over() { + // Size, spacing 100% and scatter 0%, fixed; the rotation 0° or 90°, to the page or following + // the path. + let still = "2 /Lopsided art/ 5 1 0 0 / 0 1 1 0 1 1 0 0 0 0 0 0 0 0 0"; + let turned = "2 /Lopsided art/ 5 1 0 0 / 0 1 1 0 1 1 0 0 0 0 90 90 0 0 0"; + let along = "2 /Lopsided art/ 5 1 0 0 / 0 1 1 0 1 1 0 0 0 0 0 0 0 1 0"; + let def = format!( + "{}{}{}{}", + lopsided_art("Lopsided art"), + plugin_object(SCATTER, "Still", still), + plugin_object(SCATTER, "Turned", turned), + plugin_object(SCATTER, "Along", along) + ); + let r = read_ok(&format!("{def}{}", layer(&(rect_path(0.0, 0.0, 10.0, 10.0) + "f\n")))); + let lib = vectorcraft_brush::library(&r.doc); + let stroke = vectorcraft_doc::StrokeLayer::new(Paint::solid(Color::BLACK), 1.0); + // The art is 40 by 8, so copies are 40 apart along a line 100 long, centered at 20, 60 and 100 + // from its start. + let pieces = |name: &str, from: (f64, f64), to: (f64, f64)| { + let b = lib.iter().find(|b| b.name == name).unwrap(); + let line = kurbo::BezPath::from_vec(vec![kurbo::PathEl::MoveTo(Point::new(from.0, from.1)), kurbo::PathEl::LineTo(Point::new(to.0, to.1))]); + vectorcraft_brush::stroke_pieces(&r.doc, b, &line, &stroke) + }; + let filled = |pieces: &[Node], x: f64, y: f64| { + pieces.iter().any(|n| { + let mut hit = false; + n.walk(&mut |c| hit |= c.path_data().is_some_and(|p| kurbo::Shape::winding(&p.to_bezpath(), Point::new(x, y)) != 0)); + hit + }) + }; + let still = pieces("Still", (0.0, 0.0), (100.0, 0.0)); + assert_eq!(still.len(), 3, "{still:#?}"); + // The copy at 60 spans 40 to 80: the narrow block is its first 10, the wide block all of it. + assert!(filled(&still, 70.0, -2.0) && !filled(&still, 70.0, 2.0), "the wide block is above the line"); + assert!(filled(&still, 45.0, 2.0), "the narrow block is below it"); + // Turned 90° to the page, the copy at 60 stands across the line from 40 above it to 80 below + // it: the wide block on the left, the narrow block on the right at its bottom 10. + let turned = pieces("Turned", (0.0, 0.0), (100.0, 0.0)); + assert_eq!(turned.len(), 3, "{turned:#?}"); + assert!(filled(&turned, 58.0, 0.0) && !filled(&turned, 62.0, 0.0), "the wide block is left of the copy's middle"); + assert!(filled(&turned, 62.0, 15.0) && !filled(&turned, 62.0, -15.0), "the narrow block is at its bottom"); + // Right to left with the rotation following the path, the copy at 40 (20 to 60) is turned half + // way round: its narrow block is its last 10. + let along = pieces("Along", (100.0, 0.0), (0.0, 0.0)); + assert_eq!(along.len(), 3, "{along:#?}"); + assert!(filled(&along, 30.0, 2.0) && !filled(&along, 30.0, -2.0), "the wide block is below the line"); + assert!(filled(&along, 55.0, -2.0), "the narrow block is above it, at the copy's other end"); + // Up the page with the rotation following the path, the copy at y 40 (20 to 60) is turned a + // quarter round: the wide block on the left of the line, the narrow block on its right at its + // bottom 10, where the line starts. + let up = pieces("Along", (0.0, 100.0), (0.0, 0.0)); + assert_eq!(up.len(), 3, "{up:#?}"); + assert!(filled(&up, -2.0, 40.0) && !filled(&up, 2.0, 40.0), "the wide block is left of the line"); + assert!(filled(&up, 2.0, 55.0) && !filled(&up, 2.0, 25.0), "the narrow block is right of it, at the copy's bottom"); +} + use read::{GRAPH_PLAIN, GRAPH_UNENDED}; /// Editing data in the legacy format (version 7 specification, chapter 2): `%AI5_FileFormat 2.0`, diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 490b47464d..90d9b1bee4 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -260,7 +260,7 @@ private editing data. VectorCraft: The app's own editing copy of a file (an EPS after its `%%EOF`, a `.ai`'s `AIPrivateData` streams, a PDF's `AIPDFPrivateData` streams when it was saved with the editing data (#868), Zstandard or zlib, the EPS's in ASCII85) is not documented as a whole. VectorCraft reads its structure: layers and sublayers (names, order, visibility, lock, printing, preview, dimming, colour), groups as they were nested, compound paths (painted by their last path, or the last painted one, with the paths of groups inside them kept as their paths: #1410), clipping groups and layer clipping (several clipping paths in a clipping group, a layer or an opacity mask's art clip to their intersection, and a compound path of clipping paths stays one clip; a filled clipping path keeps its fill, which paints under the art it clips, except the path of a mask that covers several layers, whose fill is read as a path of its own in the layer that holds the mask's path, and a compound clipping path whose subpaths paint differently, whose filled subpaths are read as a compound path of their own under the art it clips; clipping paths that would nest the art past the document's 32 levels stop the editing data from being read: #5789), object names, hidden and locked objects, fills and strokes (grey, CMYK, RGB, named and spot colours, spot colours defined in Lab with their Lab values (#1032), global process colours as global swatches at their tint; a stroke of width 0, `0 w`, on a path, a gradient-filled path, legacy type or in an art style comes in as a 0.25 pt hairline, as from PDF: #1671), linear and radial gradients, pattern fills with their patterns as pattern swatches (#1025), gradient and pattern names in the file up to their first newline (a name that another swatch, or a gradient or pattern defined earlier, already has is numbered "Sky 2"; a name without a newline is kept, and when another swatch has it, the pattern's swatch, or a named color sharing a gradient or pattern swatch's name, is numbered the same way), opacity, blend modes, isolation and knockout, embedded images where their matrix puts them, rotated ones too (#2269), with their alpha channel (CMYK images keep their ink amounts, as they do when a `.ai` opens from its PDF part, and an alpha channel that hides part of a CMYK image becomes a grayscale opacity mask), placed (linked) files as linked images in their place, each showing the low-resolution preview the file keeps of it until its file is found or relinked in the Links panel (#1264), with the folder the file keeps relative to the document's, where the link is looked for when its path is gone, placed PDF and `.ai` pages as placed documents of the [page and Crop to box](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-other-file-types/adobe-pdf-placement-options.html) their dictionary names (`AI11 PlacedPDFPageIndex`, `AI11 PlacedPDFCropTo`; a value VectorCraft doesn't read, or a binding to an image variable, leaves a linked image), guides, and every artboard where it is, with its center mark, cross hairs, video safe areas and video ruler pixel aspect ratio. VectorCraft reads `CropAreaActive`, an `/Int` in the dictionary that holds the artboard array, as the index of the active artboard in that array, and the file opens with that artboard active; without it, or when it names no artboard that opens, the first artboard is active. It also reads the Document Raster Effects Settings (resolution, color model, background, anti-alias, clipping mask, Add Around Object and Preserve Spot Colors), the author from the header's `%%For` (an EPS's own header when the editing data's has none), swatches for the header's `%%CMYKCustomColor` and `%%RGBCustomColor` colors that the document has none of, and `%%TemplateBox` in older files; a setting with a value of another type or out of range keeps its default. Objects on Path groups open live, with their path, their objects in order along it, Pivot and Rotate; one with a dragged spacing or other options opens as a plain group. A gradient with stops in the middle runs its whole ramp across its shape, and a gradient object does not pass its fill to the next path (#1390). An object whose art style is one fill and one stroke at most (solid colours, its own gradient, a variable-width profile on a Stroke Offset stroke or written as each side's widths) with Drop Shadow, Inner Glow, Outer Glow, Feather, Round Corners, Scribble, Offset Path, Outline Object, Outline Stroke, Convert to Shape, Tweak (only when it moves nothing), Pucker & Bloat at 0 or Bas Relief (read from its settings block: [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)) comes in as itself with them and their saved settings. A path, compound path or group (not a clipping group) whose only effect is Transform (not with copies or Random) or a Free Distort whose corners make a parallelogram comes in as itself with it too, when neither it nor anything in it paints with a gradient or pattern and everything in it is a path, compound path or group with no opacity mask and no effects of its own; Transform that scales, rotates or reflects needs nothing in it to be stroked. Twist as the only effect is read the same way when nothing in the object is stroked: up to 180° either way (a limit VectorCraft sets) on a path or compound path whose segments are all straight, and up to 90° either way (a limit VectorCraft sets) on another path, compound path or group with no guide in it. One with more, other effects (Zig Zag, a Pucker & Bloat of another amount, a Free Distort with other corners), an effect setting that is not read (an unknown key, a missing or out-of-range value, a Scribble with a color of its own), a variable-width stroke with one centered width array, dashes aligned to corners, a brush other than a Calligraphic or Art one, a Calligraphic brush with settings of its own or an angle that follows the path, or an Art brush other than the ones described next comes in as its drawn look (a group named after it). Objects in a symbol defined before the file's art styles section, as newer files write it, take the same styles as the layers' objects. A path with a Calligraphic brush otherwise comes in as the path, the brush on its stroke at the stroke's weight, which scales the brush (#372), and so does a path with an Art brush, whose weight scales the art across the path, when all of these hold: the brush stretches its art along the path, unflipped, at 100% in Tints; the path's settings are the brush's own, with no entry that isn't read, no variable width and no effects; its stroke isn't a swatch; and the art is paths, compound paths and groups in solid fills, with no strokes, masks or effects, and has some length along the path. A stroke takes the brush the Brushes panel keeps under its name, and one whose name the panel doesn't keep comes in as its drawn look. Type with an Art brush keeps its drawn look under the type. A Calligraphic brush's Pressure, Tilt, Bearing and Rotation come in as those channels (a 6D Art Pen's brushes vary with the pressure, the bearing and the barrel's rotation); its Stylus Wheel varies at random. The file's Calligraphic, Scatter, Art and Bristle brushes replace the default ones in the Brushes panel, in the file's order, also when the file comes in as its PDF part (a brush library has no layers); pattern brushes and brushes it can't read are left out with a note. When the file opens from its layers, the spot colors in the art of each brush that comes in become swatches, and that art's colors count toward the document's color mode, as a pattern's do. The swatches take at most 20,000 color names in all across the brush art, and each brush-art section keeps at most 20,000 names. Each name keeps its first definition, with the color operators' names before the gradient stops' names. A spot color past those limits makes no swatch, and its color still counts toward the color mode. A spot color that the page's art, a pattern or a symbol also defines keeps the value defined there. Type keeps its art style as a live appearance whatever its stack (an Art brush aside), so it can be retyped: each fill and stroke of the style's stack (solid colours, gradients and pattern fills, placed as the drawn look places them) with its own opacity, blend mode and effects, the effects on the whole object, and where the characters paint among them; the effects read are Warp, Offset Path, Outline Object, Outline Stroke, Transform (with copies, Transform Objects, Transform Patterns and Scale Strokes & Effects; not with Random), Free Distort, Pucker & Bloat, Twist, Zig Zag, Tweak (only when it moves nothing, the file holding none of its random outline), Drop Shadow, Inner Glow, Outer Glow, Feather, Round Corners, Scribble, Gaussian Blur, Bas Relief (its detail, smoothness and light direction from its settings block, or the effect's defaults when the style holds no settings block; a settings block that isn't read keeps the drawn look) and Convert to Shape, and a style with others, or with an effect setting that isn't read, keeps the type's drawn look. Convert to Shape keeps its Rectangle, Rounded Rectangle or Ellipse, its Absolute or Relative size (a relative size in the file is added to each side) and its corner radius; a relative Ellipse, or a setting that isn't read, keeps the drawn look. The page's drawing of such a style isn't held to look like VectorCraft's where its drawn look lay. Gradients take their matrix (`Xm`, radials and skewed ones too), focal point and the order of stops sharing a ramp point; gradient meshes, a clipping path's own fill and its stroke, and the artboards' names are read too. `editingData: "always"` (`convert --editing-data`) opens a `.ai` or an Illustrator EPS from its editing data even where it draws differently from its page, which can be older, with a note. Type is made from the file's text document, whole and editable, shown or not: point type (its frame's matrix, which newer files leave out when it is neither turned nor scaled, read as none), area type (a story in several frames as threaded type) and type on a path, with its characters, fonts, size, leading, tracking, scaling, baseline shift, fill and stroke (grey, RGB or CMYK), alignment, indents and paragraph spacing (a character attribute a run doesn't set comes from its character style, then the style that one is based on, then the document's defaults); area type keeps its frame's Area Type Options rows and columns, the gutter between rows and the gutter between columns, and its first baseline (Fixed, Cap Height, Leading or x Height) with its minimum; type on a path keeps its frame's Type on a Path effect, Align to Path and Flip (a frame whose options set key 6 to true keeps their defaults), and the first frame's Spacing is fitted from the file's layout, not read from the dialog's value; the distance from the path under Align to Path is measured for each character at its size and vertical scale (in vertical type, its horizontal scale), from the top of its font's em box (Ascender), half the height of the top of its font's H (Center) or the bottom of its font's bounding box (Descender); the fit under Gravity does not reproduce the file's layout, and its glyphs can lie up to 7.4 pt from the positions the file keeps; the page's drawing of it (often in pieces) is left out. Vertical type keeps its orientation, its columns from right to left, and a run set to Tate-chu-yoko keeps that setting. When it makes the type of every text object that shows, the page's type is only compared with it, each text object keeps its own group, frame and layer, and a line break inside a paragraph stays one. Where it can't make a text object's type (a frame of another kind), that text object takes the page's type where the text document puts its lines, or else what is left of the page's type in painting order (no group around it); the page's type where made type draws stays that type's, and hidden type is left out with a note. Text wrap is read too: an object whose dictionary has the wrap options (offset and Invert Wrap), or any graphic of a legacy wraparound group (`*w` … `*W`, before or after its type, with no offset), is a wrap object, and area type below it in its layer flows around it when the file opens, threaded type included (#2763). Kerning, underline and the other character and paragraph options aren't read yet. A `.ai` saved without PDF compatibility (a placeholder page) opens from its editing data alone, its point type, area type and type on a path made from the text document. A `.ai` whose PDF part shows only text isn't taken for that placeholder when its page states an art, trim or bleed box: it opens from its editing data alone where that reads, else from its PDF part (#1387). A `.ai` whose PDF part draws nothing at all (an empty page, with or without those boxes) opens from its editing data alone where that reads too: there is no page art to check its layers against, and the empty page would lose all of it. Text objects with an appearance keep their own text and frame, type of hidden layers stays hidden, and type on later artboards lands on its text objects (#1391); area type whose frame is too short for a line of the fallback font shows its first line (the frame is made taller, with a warning in the open result) (#1392). In a PDF saved with some of its artboards, the type on each page after the first goes to an artboard of that page's size after the previous page's artboard, and only to one that leaves an artboard for each later page; the first page's artboard also leaves one for each later page. When several artboards fit a later page, VectorCraft takes the one whose art draws most like the page, and compares at most 16 artboards for all the later pages together. Symbols are read into the Symbols panel, in the file's symbol list order, with their art, their registration point and the instances in their art, and their instances come in live with their matrix, name, hide, lock, opacity, blending mode, isolation, knockout and opacity mask; a symbol whose art isn't read whole (type, placed files, an image it leaves out or anything else it doesn't read) isn't kept. A file that comes in as its page or PDF part because its editing data has no layers (a symbol library), or because its layers can't be read or used (any of the cases below), gets the symbols its editing data defines before its first layer, in the symbol list's order, while its page art stays as the page draws it. Instances of symbols it can't read, instances with appearance changes of their own (a dynamic symbol's), pattern fills whose pattern it can't read, placed files the data keeps no preview of and anything else it doesn't read make the file come in as its page (on a layer that doesn't show, they are left out of that layer), with a warning saying what. An unread object on a shown layer whose box can be found instead comes in as a group of the page's objects inside that box, named after it, with the rest of the layers and groups kept and a warning listing what came in as the page's art; the file still comes in as its page when live art or another unread object shares that page art, 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 its transparency (#4806). The layers' art is also compared with the page (by lightness, so colours written as their CMYK equivalents compare alike, and by whether a pixel is inked at all); the page is used when they differ by more than 5% (away from type, when all the type is made from the text document), where one draws an object the other doesn't (away from type, whose lines may be laid out afresh), and when an EPS whose page is its art's box has art printed outside it (#735). A `.ai` is not compared with its page, and its PDF part is not imported, when its text document makes the type of every text object (at least one shows, and none is drawn by the appearance of the layer or group it is in), no object is unread, no placed file has a second placement, no live envelope keeps its drawn art, it declares no large canvas, and its artboards are its pages' trim boxes one for one, in points or in the first page's `UserUnit`: it opens from its layers, with the bleed of its pages' bleed boxes. When they differ because some objects draw differently (an object in another color, or one that only one of them draws), each top-level object of the layers that holds such a difference comes in as a group of the page's objects inside its box and the layers stay, with a warning that names the layer or sublayer of each such object as the Layers panel shows it (`` for one without a name) and how many came in from it; an export or Save As to the file's own path then needs `acknowledgeLoss: true`, and a wrap object replaced this way keeps its wrap options. The file still comes in as its page when only edges or type differ, when a difference lies outside every top-level object, when more than half of the top-level objects or more than 64 hold one, when such an object is or holds type or holds a wrap object inside a group, when the page's type of a text object that stays lies inside such an object's box, when the page's art can't replace such an object for one of the reasons above for an unread object, when matching the differences to the objects would take too much work, or when the result still differs from the page. `editingData: "always"` keeps the objects as read, and placed files at the other point their data gives are tried as well. An EPS whose page is its art's box keeps that page when it comes in through its layers, not the editing data's artboard, and a text object counts as drawn by the page by its colours, not only its lightness, so a red stroke stacked over a dark red one stays (#1102). `textAs: "outlines"` opens a `.ai` whose type shows from its PDF part, which has the outlines; `editingData: false` opens any of them as its page or PDF part only, for print pipelines (#735). A file whose import left something out (hidden text, art or layers) is never written over by an export or Save As to its own path unless `acknowledgeLoss: true` (`convert --replace-lossy`), so the original keeps what the document lacks. Where a `.ai` can't be read that way (or its layers are turned off in the import options), we read its PDF-compatible part, so Illustrator-only live objects arrive as appearance, and plain groups arrive ungrouped: that part draws each object on its own and marks only layers, clipping groups and groups with opacity, blending or a mask (those come back). Art outside the artboards isn't in that part at all (Illustrator's PDF part leaves it out), so it doesn't open; the import says so in a note (#472). Its pages still go where the editing data puts the artboards (a grid stays a grid), with the art on each, when it has as many artboards as pages, of the same sizes (#1068); the page of the artboard `CropAreaActive` names is then the active artboard. A `.ai` whose editing data has artboards but no layers also opens on that page under the same check, and its pages stay where they are. A `.ai` whose PDF part's pages are cropped to its art (each page the box of all the art, which is the editing data's bounding box) instead of its artboards opens from its layers, with its own artboards, where they draw as that page does. Its pages are laid out so that art one of them draws past its artboard (notes beside a design, which the part doesn't clip) doesn't lie over the page before it in the row, where it was taken for that page's art: the check against the editing data then found art its layers don't have there and opened the file as its PDF part, without the art outside the artboards. That part also has no paragraphs: area type is written line by line, and comes back as area type only where its font is installed and lays the lines out with the same breaks, else as a point type object per line (#508). Art off the page that a PDF does draw opens on the pasteboard. A run of type in the editing data whose baseline direction is 1 opens with Standard Vertical Roman Alignment (https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html) on, which is VectorCraft's own mapping: its half-width characters stand upright in vertical type, and horizontal type keeps the mark with no change to its layout. A run whose baseline direction is 2 or 3 (Tate-chu-yoko), or that names none in the run, its character style or the document's defaults, opens with it off. The scripting reference lists 1, 2 and 3 as the Standard, vertical rotated and Tate-chu-yoko baseline directions (https://web.archive.org/web/20170621180804/https://wwwimages.adobe.com/content/dam/Adobe/en/devnet/illustrator/sdk/CC2015_3/Illustrator%20VBScript%20Reference.pdf, page 256). -A Scatter brush in the editing data whose last 15 numbers start with 1 comes into the Brushes panel in Tints. Each brush art section is read without its frame: an unnamed, unpainted rectangle with no settings of its own at the art's bounds (within 1/1000 pt), closed, or open with its first corner again at the end. A wider frame stays in the art, and an art group with a state or look of its own (hidden, locked, isolated, knockout, an opacity, a blend mode, a name, a mask, a note or an appearance) stays a group. +A Scatter brush in the editing data whose last 15 numbers start with 1 comes into the Brushes panel in Tints. A Scatter brush's art comes in turned over from its section, as an Art brush's does: in each copy the side of the section with y up goes down the page before the copy's rotation, and the writer writes the art back the same way. Each brush art section is read without its frame: an unnamed, unpainted rectangle with no settings of its own at the art's bounds (within 1/1000 pt), closed, or open with its first corner again at the end. A wider frame stays in the art, and an art group with a state or look of its own (hidden, locked, isolated, knockout, an opacity, a blend mode, a name, a mask, a note or an appearance) stays a group. An object in a pattern's art or in a brush's art takes the file's art styles in the same way as an object on a layer: with a style VectorCraft reads, it comes in as itself with its effects live, not as the look it draws. An object in a pattern's art with a style in the file's style list keeps that graphic style's id. An art styles section inside a symbol's, a pattern's or a brush's art is skipped. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f3707717e6..35c1f8f646 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1649,6 +1649,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur In a `.ai` opened from its editing data, an object in a pattern's art or a brush's art with an art style VectorCraft reads opens as itself with its effects live, as an object on a layer does, and an object in a pattern's art keeps the id of a graphic style in the file's list (`crates/eps/src/import/ai/tests.rs`). Blends and envelopes in the definitions of a `.ai`'s symbols, patterns and brushes' art count against the same per-file limits on blend layout and envelope checks as the layers' art, so a file with many definitions does not get those limits again for each one (`crates/eps/src/import/ai/read/directives.rs`). A `.ai` or EPS whose editing data has brushes opens with the file's Calligraphic, Scatter, Art and Bristle brushes in the Brushes panel in place of the default ones, in the file's order: the Calligraphic size, roundness and angle with their variation, the Scatter size, spacing, scatter and rotation, the Bristle settings, and the Scatter and Art brushes' art (Art brushes in the older and newer forms of their objects). A brush library `.ai` (brushes and no layers) opens from its PDF part with its brushes, so Other Library lists them. An Art brush in Tints keeps that colorization. Pattern brushes and brushes that can't be read are left out with a note. Paths with a Calligraphic brush, and paths with an Art brush in the newer form at 100% in Tints that stretches art of solid-filled paths unflipped, open as the path with the brush on its stroke. Paths with an Art brush in the older form, and other brushed paths, still come in as their drawn look (part of #372 and #637; `crates/eps/src/import/ai/tests.rs`, `crates/eps/src/import/tests_native.rs`). + In a `.ai` or EPS opened from its editing data, a Scatter brush's art comes in turned over from its section, as an Art brush's does: each copy draws the side of the section with y up down the page before the copy's rotation. The `.ai` writer writes Scatter art back the same way (`crates/eps/src/import/ai/tests.rs`, `crates/eps/src/ai_editing/tests.rs`). In a `.ai` opened from its editing data, a path or type object with Offset Path, Outline Object or Outline Stroke on the whole object opens as itself with those effects live, in their order and shown or hidden; on a fill or stroke of type they stay on that fill or stroke. Offset Path keeps its Offset, Joins and Miter Limit, and Outline Stroke takes its width from the stroke. An Offset Path with a setting missing, out of range or not read keeps the drawn art, as does a path with a Path effect on one fill or stroke (`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` or EPS opened from its editing data, a Scatter brush whose last 15 numbers start with 1 comes into the Brushes panel in Tints, and each brush art section is read without its frame, an unnamed, unpainted rectangle with no settings of its own at the art's bounds (within 1/1000 pt). A wider frame stays in the art, and an art group with a state or look of its own (hidden, locked, isolated, knockout, an opacity, a blend mode, a name, a mask, a note or an appearance) stays a group (`crates/eps/src/import/ai/tests.rs`). In a `.ai` opened from its editing data, type with Warp on the object or on one of its fills or strokes opens as type with the effect live when the live warp draws as the art saved with it. When it draws differently, or when the file's limit of checks has no check left for it, it opens as that art, and one note says how many did. Type stays live without a comparison when the saved art paints nothing or draws type of its own, in frames of threaded type, when a text variable binds it, and when its text object doesn't come in as one text object (`crates/eps/src/import/ai/envelope.rs`, `crates/eps/src/import/tests_native.rs`). From c77239e25d7e82396143108329b750a9333332fa Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 18:27:28 -0800 Subject: [PATCH 025/176] Symbols: instance fill and stroke effects count in Pathfinder effects and clicks A geometry effect on a symbol instance's active fill or stroke reshapes the art the canvas draws, but Effect > Pathfinder took the instance's art without those effects, and a click only reached the instance inside its bounds. - Pathfinder takes the instance's art with its fill and stroke effects on the art's fills and strokes, as it takes a path with such effects, also for an instance with geometry effects of its own and for instances nested in the art. - A click where the effects paint the art outside the instance's bounds selects the instance: fills except with Selection by Path Only, strokes always, and not in outline mode. The click culling box takes those shapes in, measured with the art's own path and group effects. - A compound shape's area still leaves out its members' fill and stroke effects, for symbol instances as for paths. --- crates/doc/src/hit.rs | 38 ++++++++--- crates/doc/src/node/ops.rs | 17 +++-- crates/effects/src/group.rs | 25 +++++-- crates/effects/src/reshape.rs | 106 +++++++++++++++++++++++------- crates/engine/src/tests/expand.rs | 95 ++++++++++++++++++++++++++ docs/target-app-parity.md | 1 + 6 files changed, 241 insertions(+), 41 deletions(-) diff --git a/crates/doc/src/hit.rs b/crates/doc/src/hit.rs index fd907a26cc..d8de6acab5 100644 --- a/crates/doc/src/hit.rs +++ b/crates/doc/src/hit.rs @@ -82,8 +82,9 @@ impl Default for HitOptions { } } -/// The shapes that an image's own fills and strokes paint, each with its fill rule and the fill or -/// stroke that paints it (none for fills and strokes that paint nothing). Effects are evaluated +/// The shapes that an image's own fills and strokes paint, or the fills and strokes of the art of a +/// symbol instance whose own fill or stroke has a geometry effect, each with its fill rule and the +/// fill or stroke that paints it (none for fills and strokes that paint nothing). Effects are evaluated /// above this crate, so the engine registers one with [`set_image_paint`]. It looks up swatches and /// patterns in the document it is given. pub type ImagePaint = fn(Option<&Document>, &Node) -> Vec<(BezPath, FillRule, AppearanceItem)>; @@ -97,8 +98,8 @@ pub fn set_image_paint(f: ImagePaint) { let _ = IMAGE_PAINT.set(f); } -/// The shapes that the image `n`'s own fills and strokes paint ([`set_image_paint`]), none while -/// nothing is registered. +/// The shapes that the image or symbol instance `n` paints with its geometry effects +/// ([`set_image_paint`]), none while nothing is registered. pub(crate) fn image_paint(doc: Option<&Document>, n: &Node) -> Vec<(BezPath, FillRule, AppearanceItem)> { IMAGE_PAINT.get().map_or_else(Vec::new, |f| f(doc, n)) } @@ -891,12 +892,21 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio if opt.outline { return None; } - image_paint(Some(symbols.document()), n).iter().rev().find_map(|(bp, rule, item)| match item { - AppearanceItem::Stroke(s) => s.hits(bp, *rule, p, opt.tol).then_some(HitKind::Stroke), - AppearanceItem::Fill(_) => (!opt.path_only && fill_contains(bp, *rule, p)).then_some(HitKind::Fill), - }) + hit_painted(n, p, opt, symbols) } - NodeKind::Text(_) | NodeKind::PlacedDocument(_) | NodeKind::SymbolInstance { .. } => { + // A symbol instance is hit within its bounds, and outside them where the geometry effects + // of its active fill or stroke reshape the art it draws ([`image_paint`]) except in outline + // mode. + NodeKind::SymbolInstance { .. } => { + if n.geometric_bounds_with(symbols).is_some_and(|b| b.inflate(opt.tol, opt.tol).contains(p)) { + return Some(HitKind::Bounds); + } + if opt.outline { + return None; + } + hit_painted(n, p, opt, symbols) + } + NodeKind::Text(_) | NodeKind::PlacedDocument(_) => { n.geometric_bounds_with(symbols).filter(|b| b.inflate(opt.tol, opt.tol).contains(p)).map(|_| HitKind::Bounds) } // A blend or an envelope is hit within its bounds, and outside them where its evaluated @@ -924,6 +934,16 @@ fn hit_leaf(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Optio } } +/// What a click at `p` hits among the shapes that the fills and strokes of `n` (an image or a +/// symbol instance) paint with their geometry effects ([`image_paint`]), the frontmost first: a +/// stroke along its shape, a fill inside it except with Selection by Path Only. +fn hit_painted(n: &Node, p: Point, opt: HitOptions, symbols: &SymbolBoxes) -> Option { + image_paint(Some(symbols.document()), n).iter().rev().find_map(|(bp, rule, item)| match item { + AppearanceItem::Stroke(s) => s.hits(bp, *rule, p, opt.tol).then_some(HitKind::Stroke), + AppearanceItem::Fill(_) => (!opt.path_only && fill_contains(bp, *rule, p)).then_some(HitKind::Fill), + }) +} + /// Is `p` within `tol` of the type path of `t` (in `n`), what "Type Object Selection by Path /// Only" picks type by: its baselines ([`crate::TextObject::baselines`]), area type's frame and /// type on a path's path, drawn through `n`'s perspective projection if it has one. diff --git a/crates/doc/src/node/ops.rs b/crates/doc/src/node/ops.rs index 2bb655236a..94a298f3c8 100644 --- a/crates/doc/src/node/ops.rs +++ b/crates/doc/src/node/ops.rs @@ -214,8 +214,10 @@ impl Node { /// ([`Appearance::outset`]) instead of measuring along their shape. An image's box takes in /// the shapes its own fills and strokes paint ([`crate::hit::set_image_paint`]). Groups, layers /// without a clipping mask and Intertwine groups take in their members' boxes, grown by their - /// own strokes. Symbol instances are measured as in [`Node::visual_bounds`]. A blend's box - /// takes in where its spine can put its keys and steps. + /// own strokes. Symbol instances are measured as in [`Node::visual_bounds`], taking in the + /// shapes their art paints with the geometry effects of their own fill or stroke + /// ([`crate::hit::set_image_paint`]). A blend's box takes in where its spine can put its keys + /// and steps. pub fn reach_bounds(&self) -> Option { self.reach(None) } @@ -248,10 +250,13 @@ impl Node { .map(|b| b.inflate(o, o)) } NodeKind::Intertwine { children } => children.iter().fold(None, |acc, c| vectorcraft_geom::union_opt(acc, c.reach(symbols))), - // The frame and each shape the image's own fills and strokes paint, a stroke's grown by - // the farthest it can reach from its shape. - NodeKind::Image(_) => { - crate::hit::image_paint(symbols.map(SymbolBoxes::document), self).iter().fold(self.geometric(symbols), |acc, (bp, _, item)| { + // The frame and each shape the image's own fills and strokes paint, or a symbol + // instance's box and each shape its art paints with the geometry effects of the + // instance's own fill or stroke, a stroke's grown by the farthest it can reach from its + // shape. + NodeKind::Image(_) | NodeKind::SymbolInstance { .. } => { + let start = if matches!(self.kind, NodeKind::Image(_)) { self.geometric(symbols) } else { self.visual(symbols) }; + crate::hit::image_paint(symbols.map(SymbolBoxes::document), self).iter().fold(start, |acc, (bp, _, item)| { let o = if let crate::AppearanceItem::Stroke(s) = item { s.reach() } else { 0.0 }; vectorcraft_geom::union_opt(acc, (!bp.elements().is_empty()).then(|| bp.bounding_box().inflate(o, o))) }) diff --git a/crates/effects/src/group.rs b/crates/effects/src/group.rs index bb2f605a91..9d234b9ee8 100644 --- a/crates/effects/src/group.rs +++ b/crates/effects/src/group.rs @@ -110,13 +110,15 @@ fn leaves(doc: Option<&Document>, n: &Node, hook: Option, nodes: &S // Every path of the outline art, at any depth, is drawn inside the object's opacity // and blend mode. A symbol's art comes with the live objects and the instances of // other symbols inside it given as their art, and the type inside it outlined, so the - // art has nothing left for `hook` to give. + // art has nothing left for `hook` to give. Its fills and strokes carry the geometry + // effects of the instance's active fill and stroke, as the canvas draws them. if let Some(h) = hook && let Some(art) = h(n) { let art = match &n.kind { NodeKind::SymbolInstance { symbol, .. } if nodes.charge(&art) => { - let mut art = crate::reshape::symbol_art_with(&art, h, nodes, symbol); + let mut art = instance_art(doc, &art, h, nodes, symbol); + crate::reshape::add_instance_row_effects(doc, n, &mut art); crate::reshape::outline_nested_text(doc, &mut art, false); transparency_into_members(&mut art); art @@ -134,6 +136,19 @@ fn leaves(doc: Option<&Document>, n: &Node, hook: Option, nodes: &S } } +/// `art`, the art `hook` gave an instance of the symbol named `symbol`, with the live objects and +/// the instances of other symbols inside it given as their art +/// ([`crate::reshape::symbol_art_with`]). The art of each of those instances carries the geometry +/// effects of its own active fill and stroke ([`crate::reshape::add_instance_row_effects`]). +fn instance_art(doc: Option<&Document>, art: &Node, hook: OutlineHook, nodes: &SymbolNodes, symbol: &str) -> Node { + let drawn = |m: &Node| { + let mut a = hook(m)?; + crate::reshape::add_instance_row_effects(doc, m, &mut a); + Some(a) + }; + crate::reshape::symbol_art_with(art, &drawn, nodes, symbol) +} + /// `l`, a path drawn inside `n`: its opacity multiplied by `n`'s, and `n`'s blend mode when it is /// not Normal. fn within(l: &mut Node, n: &Node) { @@ -221,13 +236,15 @@ fn reshaped_art(doc: Option<&Document>, n: &Node, hook: Option, nod } }, // A symbol instance with a warp: its symbol's art placed by the instance, with the type - // inside it outlined, reshaped as one piece, as the renderer draws it. + // inside it outlined, reshaped as one piece, as the renderer draws it. The fills and strokes + // of the art then carry the geometry effects of the instance's active fill and stroke. NodeKind::SymbolInstance { symbol, .. } if !fx.is_empty() => { let h = hook?; let art = h(n).filter(|art| nodes.charge(art))?; - let mut art = crate::reshape::symbol_art_with(&art, h, nodes, symbol); + let mut art = instance_art(doc, &art, h, nodes, symbol); crate::reshape::outline_nested_text(doc, &mut art, false); members_as_drawn(doc, &mut art); + crate::reshape::add_instance_row_effects(doc, n, &mut art); let carry = crate::reshape::reshape_leaves_carrying(&mut art, &fx, &n.appearance.effects, doc); // The art's own fills and strokes follow the effects as its members do. if carry.moves(&art.appearance) { diff --git a/crates/effects/src/reshape.rs b/crates/effects/src/reshape.rs index 8c829d9e0b..3bc031a4d3 100644 --- a/crates/effects/src/reshape.rs +++ b/crates/effects/src/reshape.rs @@ -178,7 +178,7 @@ fn geometry_of(fx: &[Effect]) -> Vec { /// of a symbol whose art (in `doc`) holds an instance of `n`'s symbol, at any depth, keeps its /// appearance, so the effects never pass round a symbol that holds itself. Without `doc`, no /// instance in the art takes them. -fn add_instance_row_effects(doc: Option<&Document>, n: &Node, art: &mut Node) { +pub(crate) fn add_instance_row_effects(doc: Option<&Document>, n: &Node, art: &mut Node) { let NodeKind::SymbolInstance { symbol, .. } = &n.kind else { return }; let fill = active_fill(n).map_or(vec![], |f| geometry_of(&f.effects)); let stroke = active_stroke(n).map_or(vec![], |s| geometry_of(&s.effects)); @@ -404,32 +404,94 @@ fn traced_opaque_area(bytes: &[u8]) -> Traced { /// rule and the fill or stroke that paints it: the paths (or compound paths) that [`reshape`] /// makes along its frame or, for those whose first effect is Outline Object, along the outline of /// its opaque area ([`opaque_area`]), with each fill's or stroke's geometry effects applied as the -/// renderer applies them. Empty for anything but an image with such fills or strokes. The swatches -/// and patterns that live-effect plug-ins painting their pieces name are looked up in `doc`, and -/// the image's pixels in `doc` when the image does not hold them. +/// renderer applies them. For a symbol instance whose active fill or stroke has a visible geometry +/// effect ([`has_item_geometry`]), the shapes that the fills and strokes of the art it draws paint +/// ([`instance_paint`]). Empty for anything else. The swatches and patterns that live-effect +/// plug-ins painting their pieces name are looked up in `doc`, and the image's pixels in `doc` when +/// the image does not hold them. pub fn image_paint(doc: Option<&Document>, n: &Node) -> Vec<(BezPath, FillRule, AppearanceItem)> { - if !matches!(n.kind, NodeKind::Image(_)) || !has_item_geometry(n) { - return vec![]; - } - let Some(art) = reshape(doc, n, None) else { return vec![] }; let mut out = vec![]; - art.walk(&mut |c| { - let (NodeKind::Path { rule, .. } | NodeKind::Compound { rule, .. }) = &c.kind else { return }; - let Some(g) = c.stroke_path() else { return }; - let ctx = GeomContext { doc, ..GeomContext::of(c) }; - for item in c.appearance.items.iter().filter(|i| crate::paints(i)) { - let fx = item.effects(); - let shape = if crate::has_geometry(fx) && !g.elements().is_empty() { - crate::apply_geometry_bez(fx, &g, g.bounding_box(), &ctx.item(item)) - } else { - g.clone() - }; - out.push((shape, *rule, item.clone())); - } - }); + if matches!(n.kind, NodeKind::SymbolInstance { .. }) { + let mut budget = SYMBOL_ART_MAX_NODES; + instance_paint(doc, n, 1, &mut budget, &mut out); + return out; + } + if !matches!(n.kind, NodeKind::Image(_)) || !has_item_geometry(n) { + return out; + } + let Some(art) = reshape(doc, n, None) else { return out }; + art.walk(&mut |c| push_painted(doc, c, &mut out)); out } +/// The shapes that the fills and strokes of path or compound path `c` paint, each with the +/// geometry effects of that fill or stroke applied ([`image_paint`]); nothing for other objects. +fn push_painted(doc: Option<&Document>, c: &Node, out: &mut Vec<(BezPath, FillRule, AppearanceItem)>) { + let (NodeKind::Path { rule, .. } | NodeKind::Compound { rule, .. }) = &c.kind else { return }; + let Some(g) = c.stroke_path() else { return }; + let ctx = GeomContext { doc, ..GeomContext::of(c) }; + for item in c.appearance.items.iter().filter(|i| crate::paints(i)) { + let fx = item.effects(); + let shape = if crate::has_geometry(fx) && !g.elements().is_empty() { + crate::apply_geometry_bez(fx, &g, g.bounding_box(), &ctx.item(item)) + } else { + g.clone() + }; + out.push((shape, *rule, item.clone())); + } +} + +/// The shapes that symbol instance `n`, `depth` instances deep, paints with the geometry effects of +/// its active fill and stroke ([`has_item_geometry`]): the paths of the art [`reshape`] makes of it, +/// each with its own geometry effects and those of each fill and stroke applied +/// ([`crate::bake_type_appearance`], [`push_painted`]), the paths that the own fills and strokes of +/// the groups and layers in the art paint ([`crate::evaluate_container`]), and the instances in that +/// art that took those effects, in turn. Hidden objects, clipping paths, guides and the members of +/// clip groups add nothing, and neither does an instance more than +/// [`vectorcraft_doc::depth::MAX_DEPTH`] deep or whose symbol's art would take the objects measured +/// so far past `budget`. +fn instance_paint(doc: Option<&Document>, n: &Node, depth: usize, budget: &mut u64, out: &mut Vec<(BezPath, FillRule, AppearanceItem)>) { + let NodeKind::SymbolInstance { symbol, .. } = &n.kind else { return }; + if depth >= vectorcraft_doc::depth::MAX_DEPTH || !has_item_geometry(n) { + return; + } + let Some(sym) = doc.and_then(|d| d.symbols.iter().find(|s| s.name == *symbol)) else { return }; + let count = sym.art.count() as u64; + if count > *budget { + return; + } + *budget -= count; + let Some(art) = reshape(doc, n, Some(&vectorcraft_doc::symbol_overrides::dynamic_art(&sym.art, n))) else { return }; + painted_in(doc, &art, depth, budget, out); +} + +/// [`instance_paint`] of the objects in `n`, art of an instance `depth` instances deep. +fn painted_in(doc: Option<&Document>, n: &Node, depth: usize, budget: &mut u64, out: &mut Vec<(BezPath, FillRule, AppearanceItem)>) { + if !n.visible { + return; + } + match &n.kind { + NodeKind::Path { clipping: false, guide: false, .. } | NodeKind::Compound { .. } => match crate::bake_type_appearance(doc, n) { + // One path for each fill and stroke, its effects applied. + Some(pieces) => painted_in(doc, &pieces, depth, budget, out), + None => push_painted(doc, n, out), + }, + NodeKind::Path { .. } => {} + NodeKind::SymbolInstance { .. } => instance_paint(doc, n, depth + 1, budget, out), + _ if n.clips() => {} + _ => { + let evaluated = crate::has_container_appearance(n).then(|| crate::evaluate_container(doc, n)).flatten(); + let g = evaluated.as_ref().unwrap_or(n); + if g.clips() { + return; + } + for c in g.children().into_iter().flatten() { + painted_in(doc, c, depth, budget, out); + } + } + } +} + /// The glyph outlines of type `t` in text space with its underline and strikethrough bars: one /// path per run, and all of them as one. pub(crate) fn glyph_outlines(t: &vectorcraft_doc::TextObject) -> (Vec, kurbo::BezPath) { diff --git a/crates/engine/src/tests/expand.rs b/crates/engine/src/tests/expand.rs index d853b91110..b10367910d 100644 --- a/crates/engine/src/tests/expand.rs +++ b/crates/engine/src/tests/expand.rs @@ -260,6 +260,100 @@ fn a_stroke_effect_reshapes_a_stroke_a_dynamic_instance_adds() { assert!(b.x0 <= 31.0 && b.x1 >= 169.0, "the bounds take in the offset stroke: {b:?}"); let drawn = vectorcraft_render::drawn_bounds(&doc, doc.node(id).unwrap()).expect("the instance is drawn"); assert!(drawn.x0 <= 31.0 && drawn.x1 >= 169.0, "the drawn bounds take in the offset stroke: {drawn:?}"); + assert_eq!(hit_at(&s, 30.5, vectorcraft_doc::hit::HitOptions { tol: 1.0, ..Default::default() }), Some(id), "a click on the added stroke"); +} + +/// What a click at (`x`, 100) with `opt` hits. +fn hit_at(s: &Session, x: f64, opt: vectorcraft_doc::hit::HitOptions) -> Option { + vectorcraft_doc::hit::hit_test(&s.doc().unwrap().doc, vectorcraft_geom::Point::new(x, 100.0), opt).map(|h| h.leaf) +} + +/// [`instance_with_row`] of a symbol whose art is an instance of another symbol made of the square. +fn nested_instance_with_row(s: &mut Session) -> (NodeId, usize) { + square(s); + let inner = NodeId(run(s, "symbol.new", json!({"name": "Inner"}))["id"].as_u64().unwrap()); + run(s, "select.set", json!({"ids": [inner.0]})); + let id = NodeId(run(s, "symbol.new", json!({"name": "Outer"}))["id"].as_u64().unwrap()); + run(s, "appearance.addFill", json!({"ids": [id.0]})); + let row = node(s, id).appearance.items.len() - 1; + run(s, "appearance.setItem", json!({"ids": [id.0], "index": row, "none": true})); + (id, row) +} + +/// Effect › Pathfinder › Add on a group holding a symbol instance combines the art the instance +/// draws: the effects on the instance's fill and stroke reshape the result as they reshape the +/// instance, in a symbol placed inside another symbol too. +#[test] +fn pathfinder_takes_a_symbol_instance_fill_and_stroke_effects() { + for (fill, x, color) in [(true, 44, RED), (false, 40, BLUE)] { + let mut s = session(); + let (id, row) = instance_with_row(&mut s, "Square", fill); + offset_row(&mut s, id, row, 10.0); + let g = NodeId(run(&mut s, "object.group", json!({"ids": [id.0]}))["id"].as_u64().unwrap()); + run(&mut s, "effect.apply", json!({"ids": [g.0], "effect": "pathfinder.add"})); + let r = render(&s); + assert!(near(r.pixel(x, 100), color), "fill {fill}: the result keeps the offset: {:?}", r.pixel(x, 100)); + assert!(near(r.pixel(100, 100), RED), "fill {fill}: the result keeps the art's fill: {:?}", r.pixel(100, 100)); + } + // An effect of the instance's own reshapes the art as well. + let mut s = session(); + let (id, row) = instance_with_row(&mut s, "Square", true); + offset_row(&mut s, id, row, 10.0); + run(&mut s, "effect.apply", json!({"ids": [id.0], "item": null, "effect": "path.offsetPath", "params": {"offset": 5}})); + assert!(near(render(&s).pixel(37, 100), RED), "both offsets grow the art on the canvas: {:?}", render(&s).pixel(37, 100)); + let g = NodeId(run(&mut s, "object.group", json!({"ids": [id.0]}))["id"].as_u64().unwrap()); + run(&mut s, "effect.apply", json!({"ids": [g.0], "effect": "pathfinder.add"})); + assert!(near(render(&s).pixel(37, 100), RED), "both offsets grow the result: {:?}", render(&s).pixel(37, 100)); + + let mut s = session(); + let (id, row) = nested_instance_with_row(&mut s); + offset_row(&mut s, id, row, 10.0); + assert!(near(render(&s).pixel(44, 100), RED), "the nested art grows on the canvas: {:?}", render(&s).pixel(44, 100)); + let g = NodeId(run(&mut s, "object.group", json!({"ids": [id.0]}))["id"].as_u64().unwrap()); + run(&mut s, "effect.apply", json!({"ids": [g.0], "effect": "pathfinder.add"})); + assert!(near(render(&s).pixel(44, 100), RED), "the nested art grows in the result: {:?}", render(&s).pixel(44, 100)); +} + +/// A click where the effect on a symbol instance's fill or stroke paints its art outside the +/// instance's bounds selects the instance; a click past the drawn art, a fill with Selection by +/// Path Only and outline mode do not. +#[test] +fn a_click_where_a_symbol_instance_fill_or_stroke_effect_paints_selects_it() { + use vectorcraft_doc::hit::HitOptions; + let opt = HitOptions { tol: 1.0, ..Default::default() }; + let mut s = session(); + let (id, row) = instance_with_row(&mut s, "Square", true); + assert_eq!(hit_at(&s, 44.0, opt), None); + offset_row(&mut s, id, row, 10.0); + assert_eq!(hit_at(&s, 44.0, opt), Some(id), "a click on the grown fill"); + assert_eq!(hit_at(&s, 100.0, opt), Some(id), "a click inside the instance"); + assert_eq!(hit_at(&s, 36.0, opt), None, "a click past the grown fill"); + assert_eq!(hit_at(&s, 44.0, HitOptions { path_only: true, ..opt }), None, "Selection by Path Only leaves the fill out"); + assert_eq!(hit_at(&s, 44.0, HitOptions { outline: true, ..opt }), None, "outline mode draws the art as it is"); + + let mut s = session(); + let (id, row) = instance_with_row(&mut s, "Square", false); + offset_row(&mut s, id, row, 10.0); + assert_eq!(hit_at(&s, 40.0, opt), Some(id), "a click on the moved stroke"); + assert_eq!(hit_at(&s, 45.0, opt), None, "a click between the moved stroke and the fill"); + assert_eq!(hit_at(&s, 40.0, HitOptions { path_only: true, ..opt }), Some(id), "Selection by Path Only takes the stroke"); + + let mut s = session(); + let (id, row) = nested_instance_with_row(&mut s); + offset_row(&mut s, id, row, 10.0); + assert_eq!(hit_at(&s, 44.0, opt), Some(id), "a click on the grown fill of the nested art"); + + // A path in the art with an Offset Path of its own: both offsets grow what it draws. + let mut s = session(); + let art = square(&mut s); + run(&mut s, "effect.apply", json!({"ids": [art.0], "item": null, "effect": "path.offsetPath", "params": {"offset": 5}})); + let id = NodeId(run(&mut s, "symbol.new", json!({"name": "Offset"}))["id"].as_u64().unwrap()); + run(&mut s, "appearance.addFill", json!({"ids": [id.0]})); + let row = node(&s, id).appearance.items.len() - 1; + run(&mut s, "appearance.setItem", json!({"ids": [id.0], "index": row, "none": true})); + offset_row(&mut s, id, row, 10.0); + assert!(near(render(&s).pixel(37, 100), RED), "both offsets grow the art on the canvas: {:?}", render(&s).pixel(37, 100)); + assert_eq!(hit_at(&s, 37.0, opt), Some(id), "a click where both offsets grow the art"); } /// A group in the symbol's art with a fill of its own: the instance's fill effect reshapes what @@ -284,6 +378,7 @@ fn a_fill_effect_reshapes_the_fill_of_a_group_in_the_art() { assert!(b.x0 <= 31.0 && b.x1 >= 169.0, "the bounds take in the group's grown fill: {b:?}"); let drawn = vectorcraft_render::drawn_bounds(&doc, doc.node(id).unwrap()).expect("the instance is drawn"); assert!(drawn.x0 <= 31.0 && drawn.x1 >= 169.0, "the drawn bounds take in the group's grown fill: {drawn:?}"); + assert_eq!(hit_at(&s, 35.0, vectorcraft_doc::hit::HitOptions { tol: 1.0, ..Default::default() }), Some(id), "a click on the group's grown fill"); let before = render(&s); run(&mut s, "effect.expandAppearance", json!({})); diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f3707717e6..c7bb992482 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1535,6 +1535,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Outline Object on an image's own fill or stroke follows the outline of the image's opaque area, and the image's frame when the image has no transparency. Path effects apply to a fill or stroke added to a bitmap object ([archived reference manual, page 561](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=561)), and with Outline Object such a stroke follows the boundary of the art when the image has transparent areas and the image's frame when it has none ([CreativePro article on strokes for placed images](https://web.archive.org/web/20250815214529/https://creativepro.com/add-strokes-placed-images-illustrator/)). VectorCraft's own rules: the opaque area is the pixels at least 50% opaque, and its outline is traced as Image Trace's Black and White mode traces at threshold 128 and fitted with curves. Evidence: `tests::imageoutline` (vectorcraft-effects), `opaque::tests` (vectorcraft-trace), `tests::containers::an_images_stroke_with_outline_object_follows_its_opaque_area` and `tests::containers::an_images_outline_object_stroke_exports_selects_and_measures_along_its_opaque_area` (vectorcraft-engine), `tests::objectfx::an_images_outline_object_stroke_follows_new_pixels_under_the_same_key` (vectorcraft-render). A geometry effect on one of type's own fills or strokes reshapes the whole outline that the fill or stroke paints, on the canvas and in exports; PDF, SVG, EPS and the other vector exports write such type as paths. On type that holds inline graphics, those effects are drawn and exported only when the type has a geometry effect or perspective of its own. A geometry effect on a symbol instance's fill reshapes the filled shapes of the symbol's art and leaves their strokes as they are; one on the instance's stroke reshapes the stroked shapes and leaves their fills as they are. The shapes keep their colors. Only the instance's topmost fill and topmost stroke count, and only while they are visible with an opacity above 0. The canvas and Object › Expand Appearance use the same art, SVG and PDF export bake the same shapes, and Expand Appearance turns the instance into an editable group in one undo step. A group's own fills and strokes in the art take the effects too. An instance inside the art passes the effects on to its own art, and a dynamic symbol's instance reshapes the fills and strokes it paints on the art. How the effects map onto the symbol's art is VectorCraft's own rule. The help page describes effects on one fill or stroke, and the help page describes Expand Appearance (engine `expand::a_symbol_instance_fill_effect_reshapes_its_filled_art_and_expands`, `a_symbol_instance_stroke_effect_reshapes_its_stroked_art_and_expands`, `a_stroke_effect_reshapes_a_stroke_a_dynamic_instance_adds`, `a_fill_effect_reshapes_the_fill_of_a_group_in_the_art`, `only_the_topmost_visible_instance_fill_reshapes_the_art`, `a_nested_symbol_instance_takes_the_outer_fill_effect`, `export_bakes_a_symbol_instance_fill_effect`, `a_fill_effect_on_an_instance_of_a_symbol_that_holds_itself_ends`). Existing documents with a geometry effect on a symbol instance's fill or stroke draw differently: before, the effect drew nothing. + Effect › Pathfinder takes a symbol instance as the art it draws with the geometry effects of its fill and stroke, as they take a path with such effects: the result painted by the instance's art carries those effects, also when the instance has geometry effects of its own and when the instance sits inside another symbol's art. A click where those effects paint the art outside the instance's bounds selects the instance, a fill only when Selection by Path Only is off, and outline mode still takes the instance's bounds alone. A compound shape's area leaves out its members' fill and stroke effects for symbol instances as for paths, since the compound shape paints the area with its own appearance. These are VectorCraft's own rules (engine `expand::pathfinder_takes_a_symbol_instance_fill_and_stroke_effects`, `a_click_where_a_symbol_instance_fill_or_stroke_effect_paints_selects_it`, `a_stroke_effect_reshapes_a_stroke_a_dynamic_instance_adds`). Before, Pathfinder dropped those effects and clicks took only the instance's bounds. The Appearance panel's inline effect editor labels each parameter as the effect dialogs' generic fields do, without the colon ("Max. Radius", "Channel 1", "Create New Fields by"). Roughen's and Zig Zag's Points, Offset Path's Joins, Inner Glow's Source and the menus of Radial Blur, Smart Blur, Sprayed Strokes, Glass, Mezzotint, Halftone Pattern, Grain, Texturizer and De-Interlace are dropdowns with the dialog's labels that send the dialog's values, and a plug-in's choice is a dropdown of the plug-in's values. Revolve's edge, Extrude & Bevel's bevel, every Warp style's orientation, Rasterize's Color Model, Background and Anti-aliasing and the channel of Levels and Curves are dropdowns too, with the labels their own dialogs show. `effect.apply` and `effect.setParams` refuse a Levels or Curves `channel` other than `rgb`, `red`, `green` or `blue` (or `r`, `g` and `b`, in any letter case). Object › Expand Appearance keeps each stroke of a path a stroke (weight, caps, joins, dashes, arrowheads, alignment and width profile) on a copy of the path with the geometry effects baked in, and Object › Expand… is dimmed, with a tooltip, while the selection has appearance attributes, so a stroked line with Zig Zag becomes a stroked zig-zag line and only Expand then outlines it, the two steps the [Expand objects](https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/expand-objects.html) help page describes (#3089). Brushed strokes still become their brush art; `object.expand` still bakes and outlines in one step for agents. From 58f41ca719f6e565e4b3b4abae5652a9b836707c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 19:07:59 -0800 Subject: [PATCH 026/176] Symbols: clicks reach an image's shape grown by an instance fill effect An image in a symbol's art whose own fill or stroke paints a shape (Convert to Shape, Outline Object) takes the instance's fill and stroke geometry effects on the canvas, but hit testing and the cull box measured only the paths in the art, so a click on the grown shape missed the instance. The painted shapes of an instance's art now include those of its images, as for an image on its own. --- crates/effects/src/reshape.rs | 4 +++- crates/engine/src/tests/expand.rs | 28 ++++++++++++++++++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/crates/effects/src/reshape.rs b/crates/effects/src/reshape.rs index 3bc031a4d3..c7874534ce 100644 --- a/crates/effects/src/reshape.rs +++ b/crates/effects/src/reshape.rs @@ -445,7 +445,8 @@ fn push_painted(doc: Option<&Document>, c: &Node, out: &mut Vec<(BezPath, FillRu /// its active fill and stroke ([`has_item_geometry`]): the paths of the art [`reshape`] makes of it, /// each with its own geometry effects and those of each fill and stroke applied /// ([`crate::bake_type_appearance`], [`push_painted`]), the paths that the own fills and strokes of -/// the groups and layers in the art paint ([`crate::evaluate_container`]), and the instances in that +/// the groups and layers in the art paint ([`crate::evaluate_container`]), the shapes that the own +/// fills and strokes of the images in the art paint ([`image_paint`]), and the instances in that /// art that took those effects, in turn. Hidden objects, clipping paths, guides and the members of /// clip groups add nothing, and neither does an instance more than /// [`vectorcraft_doc::depth::MAX_DEPTH`] deep or whose symbol's art would take the objects measured @@ -477,6 +478,7 @@ fn painted_in(doc: Option<&Document>, n: &Node, depth: usize, budget: &mut u64, None => push_painted(doc, n, out), }, NodeKind::Path { .. } => {} + NodeKind::Image(_) => out.extend(image_paint(doc, n)), NodeKind::SymbolInstance { .. } => instance_paint(doc, n, depth + 1, budget, out), _ if n.clips() => {} _ => { diff --git a/crates/engine/src/tests/expand.rs b/crates/engine/src/tests/expand.rs index b10367910d..8d88d6087b 100644 --- a/crates/engine/src/tests/expand.rs +++ b/crates/engine/src/tests/expand.rs @@ -387,6 +387,34 @@ fn a_fill_effect_reshapes_the_fill_of_a_group_in_the_art() { assert!(differing(&before, &after, 8) < 200, "expanding changed {} pixels", differing(&before, &after, 8)); } +/// An image in the symbol's art whose fill Convert to Shape gives a shape: the instance's fill +/// effect grows what that fill paints, and a click there selects the instance. +#[test] +fn a_click_on_the_grown_fill_of_an_image_in_the_art_selects_the_instance() { + let mut s = session(); + let mut png = vec![]; + image::RgbaImage::from_pixel(30, 30, image::Rgba([255, 0, 0, 255])) + .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) + .unwrap(); + // The frame runs from 85 to 115; the fill's shape is 9 pt larger on each side. + let r = run(&mut s, "file.place", json!({"name": "red.png", "dataBase64": vectorcraft_format::base64_encode(&png), "at": [100, 100]})); + let im = NodeId(r["ids"][0].as_u64().unwrap()); + run(&mut s, "select.set", json!({"ids": [im.0]})); + run(&mut s, "appearance.addFill", json!({})); + run(&mut s, "paint.setFill", json!({"color": "#0000ff", "item": 0})); + run(&mut s, "effect.apply", json!({"effect": "convertToShape.rectangle", "item": 0})); + let id = NodeId(run(&mut s, "symbol.new", json!({"name": "Image"}))["id"].as_u64().unwrap()); + run(&mut s, "appearance.addFill", json!({"ids": [id.0]})); + let row = node(&s, id).appearance.items.len() - 1; + run(&mut s, "appearance.setItem", json!({"ids": [id.0], "index": row, "none": true})); + let opt = vectorcraft_doc::hit::HitOptions { tol: 1.0, ..Default::default() }; + assert_eq!(hit_at(&s, 70.0, opt), None); + offset_row(&mut s, id, row, 10.0); + assert!(near(render(&s).pixel(70, 100), BLUE), "the image's fill grows by the offset: {:?}", render(&s).pixel(70, 100)); + assert_eq!(hit_at(&s, 70.0, opt), Some(id), "a click on the image's grown fill"); + assert_eq!(hit_at(&s, 60.0, opt), None, "a click past the grown fill"); +} + /// Of several fills, only the topmost one's effects reach the art, and only while it is visible. #[test] fn only_the_topmost_visible_instance_fill_reshapes_the_art() { From b73c9834c816cc90908e73ca77fc4c5270c3369e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 19:08:44 -0800 Subject: [PATCH 027/176] Scripts: grants file changes take turns and use a file of their own Two processes that changed Script Grants.json at once both wrote Script Grants.json.part, so one could overwrite the other's file or fail on it. Each write now goes to a new file named for its process and write, passing over a name an earlier write left behind, and only that file is removed when the write fails. Changes hold a lock on Script Grants.lock beside the grants file and are not made when it cannot be taken; reads take it when they can. --- crates/engine/src/script/files.rs | 57 +++++++++++++++++++++++++--- crates/engine/src/tests/script_io.rs | 37 ++++++++++++++++++ 2 files changed, 88 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index 6340912cb8..ba1bc60827 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -431,6 +431,7 @@ impl Disk { } let (Some((script, hash)), Some(store)) = (&self.script, self.store_path()) else { return }; let (script, code) = (shown(script), self.ran.iter().cloned().collect::>()); + let Ok(_lock) = lock_store(&store) else { return }; let Ok(mut grants) = try_read_store(&store) else { return }; for g in &mut grants { let ours = g["script"] == *script @@ -566,6 +567,7 @@ impl Disk { fn keep(&self, paths: &[std::path::PathBuf], write: bool, folder: bool) -> Result<(), &'static str> { let (Some((script, hash)), Some(store)) = (&self.script, self.store_path()) else { return Err(NO_ALWAYS) }; // A grants file that is there but cannot be read is left as it is. + let _lock = lock_store(&store).map_err(|_| NOT_SAVED)?; let mut grants = try_read_store(&store).map_err(|_| NOT_SAVED)?; let script = shown(script); let code: Vec<&String> = self.ran.iter().collect(); @@ -882,8 +884,10 @@ fn read_head(real: &Path, max: usize) -> std::io::Result> { } /// The grants the grants file at `store` holds; none when it is missing or cannot be read. A grant -/// that is not well formed is left out. +/// that is not well formed is left out. It is read under [`lock_store`]'s lock when that can be +/// taken, so it is read between two changes. fn read_store(store: &Path) -> Vec { + let _lock = lock_store(store).ok(); load_store(store, false).unwrap_or_default() } @@ -928,8 +932,13 @@ fn load_store(store: &Path, strict: bool) -> std::io::Result) -> std::io::Result<()> { let text = serde_json::to_vec_pretty(&serde_json::json!({"version": 1, "grants": grants})).map_err(std::io::Error::other)?; if text.len() > MAX_STORE_BYTES { @@ -938,14 +947,49 @@ fn write_store(store: &Path, grants: Vec) -> std::io::Result< if let Some(dir) = store.parent() { std::fs::create_dir_all(dir)?; } - let part = store.with_extension("json.part"); - std::fs::write(&part, text)?; + // A name an earlier write left behind is passed over, up to 64 times, and only the file made here + // is removed. + let mut tries = 0; + let (part, mut file) = loop { + let n = NEXT_PART.fetch_add(1, Ordering::Relaxed); + let part = store.with_extension(format!("json.{}-{n}.part", std::process::id())); + match std::fs::File::options().write(true).create_new(true).open(&part) { + Ok(file) => break (part, file), + Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists && tries < 63 => tries += 1, + Err(e) => return Err(e), + } + }; + let written = std::io::Write::write_all(&mut file, &text); + drop(file); // `rename` replaces a grants file that is there, on Windows too (`MOVEFILE_REPLACE_EXISTING`). - std::fs::rename(&part, store).inspect_err(|_| { + written.and_then(|()| std::fs::rename(&part, store)).inspect_err(|_| { let _ = std::fs::remove_file(&part); }) } +/// The lock file beside the grants file at `store` (`Script Grants.lock`), locked until it is +/// dropped and waiting while another process holds it, so that processes that read and change the +/// grants file take turns. A change is not made when the lock cannot be taken. +#[cfg(not(target_arch = "wasm32"))] +fn lock_store(store: &Path) -> std::io::Result { + let lock = store.with_extension("lock"); + let opened = store + .parent() + .map_or(Ok(()), std::fs::create_dir_all) + .and_then(|()| std::fs::File::options().create(true).truncate(false).read(true).write(true).open(&lock)); + let file = opened.and_then(|f| f.lock().map(|()| f)); + if let Err(e) = &file { + log::warn!("can't lock {}: {e}", lock.display()); + } + file +} + +/// The browser has no folders to keep anything in. +#[cfg(target_arch = "wasm32")] +fn lock_store(_: &Path) -> std::io::Result { + Err(std::io::Error::new(std::io::ErrorKind::Unsupported, "no file system")) +} + /// The grants the grants file beside the data folder `data_dir` keeps: each script, the SHA-256 of /// its text, the path and whether it may be written (`script.grants`). pub(crate) fn stored_grants(data_dir: &Path) -> Vec { @@ -957,6 +1001,7 @@ pub(crate) fn stored_grants(data_dir: &Path) -> Vec { /// → how many were removed. pub(crate) fn revoke_grants(data_dir: &Path, script: Option<&str>, path: Option<&str>) -> std::io::Result { let store = data_dir.with_file_name(GRANTS_FILE); + let _lock = lock_store(&store)?; let grants = try_read_store(&store)?; let before = grants.len(); let kept: Vec = diff --git a/crates/engine/src/tests/script_io.rs b/crates/engine/src/tests/script_io.rs index 2f2d7fe6f5..9b9cee9439 100644 --- a/crates/engine/src/tests/script_io.rs +++ b/crates/engine/src/tests/script_io.rs @@ -576,6 +576,43 @@ fn a_copy_of_a_link_that_leads_elsewhere_after_it_was_looked_up_copies_nothing() let _ = std::fs::remove_dir_all(base); } +/// The grants file is written through a temporary file of its own, so a temporary file another +/// process left beside it, or one an earlier write left under the name this write takes first, +/// does not stop a change and is left where it is. +#[test] +fn a_grants_change_does_not_use_another_writers_temporary_file() { + let base = folder("grants-part"); + let data = base.join("settings/Script Data"); + let grant = json!({"script": "/s.jsx", "sha256": "0", "code": [], "path": "/p", "write": false, "folder": false}); + write(&base.join("settings/Script Grants.json"), json!({"version": 1, "grants": [grant]}).to_string().as_bytes()); + std::fs::create_dir_all(base.join("settings/Script Grants.json.part/held")).unwrap(); + let next = crate::script::files::NEXT_PART.load(std::sync::atomic::Ordering::Relaxed); + let left_behind: Vec = + (next..next + 8).map(|n| base.join(format!("settings/Script Grants.json.{}-{n}.part", std::process::id()))).collect(); + for p in &left_behind { + write(p, b"earlier"); + } + assert_eq!(crate::script::files::revoke_grants(&data, None, None).unwrap(), 1); + let left: Value = serde_json::from_slice(&std::fs::read(base.join("settings/Script Grants.json")).unwrap()).unwrap(); + assert_eq!(left["grants"], json!([])); + assert!(left_behind.iter().all(|p| std::fs::read(p).is_ok_and(|b| b == b"earlier")), "files this write did not make stay"); + let _ = std::fs::remove_dir_all(base); +} + +/// A change to the grants file is not made when its lock cannot be taken. +#[test] +fn a_grants_change_without_its_lock_changes_nothing() { + let base = folder("grants-lock"); + let data = base.join("settings/Script Data"); + let grant = json!({"script": "/s.jsx", "sha256": "0", "code": [], "path": "/p", "write": false, "folder": false}); + let text = json!({"version": 1, "grants": [grant]}).to_string(); + write(&base.join("settings/Script Grants.json"), text.as_bytes()); + std::fs::create_dir_all(base.join("settings/Script Grants.lock/held")).unwrap(); + assert!(crate::script::files::revoke_grants(&data, None, None).is_err()); + assert_eq!(std::fs::read_to_string(base.join("settings/Script Grants.json")).unwrap(), text); + let _ = std::fs::remove_dir_all(base); +} + /// `rename` of a file an earlier run wrote names both its old and its new path in `written`. #[test] fn a_renamed_file_names_its_old_and_new_paths_in_written() { From 371c4a3644e35132530558cc01334f6fdde0e63a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 19:12:13 -0800 Subject: [PATCH 028/176] Docs: name the click tests for symbol instance fill and stroke effects --- docs/target-app-parity.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 7729c3ff2b..3ad0209f59 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1552,7 +1552,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Outline Object on an image's own fill or stroke follows the outline of the image's opaque area, and the image's frame when the image has no transparency. Path effects apply to a fill or stroke added to a bitmap object ([archived reference manual, page 561](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=561)), and with Outline Object such a stroke follows the boundary of the art when the image has transparent areas and the image's frame when it has none ([CreativePro article on strokes for placed images](https://web.archive.org/web/20250815214529/https://creativepro.com/add-strokes-placed-images-illustrator/)). VectorCraft's own rules: the opaque area is the pixels at least 50% opaque, and its outline is traced as Image Trace's Black and White mode traces at threshold 128 and fitted with curves. Evidence: `tests::imageoutline` (vectorcraft-effects), `opaque::tests` (vectorcraft-trace), `tests::containers::an_images_stroke_with_outline_object_follows_its_opaque_area` and `tests::containers::an_images_outline_object_stroke_exports_selects_and_measures_along_its_opaque_area` (vectorcraft-engine), `tests::objectfx::an_images_outline_object_stroke_follows_new_pixels_under_the_same_key` (vectorcraft-render). A geometry effect on one of type's own fills or strokes reshapes the whole outline that the fill or stroke paints, on the canvas and in exports; PDF, SVG, EPS and the other vector exports write such type as paths. On type that holds inline graphics, those effects are drawn and exported only when the type has a geometry effect or perspective of its own. A geometry effect on a symbol instance's fill reshapes the filled shapes of the symbol's art and leaves their strokes as they are; one on the instance's stroke reshapes the stroked shapes and leaves their fills as they are. The shapes keep their colors. Only the instance's topmost fill and topmost stroke count, and only while they are visible with an opacity above 0. The canvas and Object › Expand Appearance use the same art, SVG and PDF export bake the same shapes, and Expand Appearance turns the instance into an editable group in one undo step. A group's own fills and strokes in the art take the effects too. An instance inside the art passes the effects on to its own art, and a dynamic symbol's instance reshapes the fills and strokes it paints on the art. How the effects map onto the symbol's art is VectorCraft's own rule. The help page describes effects on one fill or stroke, and the help page describes Expand Appearance (engine `expand::a_symbol_instance_fill_effect_reshapes_its_filled_art_and_expands`, `a_symbol_instance_stroke_effect_reshapes_its_stroked_art_and_expands`, `a_stroke_effect_reshapes_a_stroke_a_dynamic_instance_adds`, `a_fill_effect_reshapes_the_fill_of_a_group_in_the_art`, `only_the_topmost_visible_instance_fill_reshapes_the_art`, `a_nested_symbol_instance_takes_the_outer_fill_effect`, `export_bakes_a_symbol_instance_fill_effect`, `a_fill_effect_on_an_instance_of_a_symbol_that_holds_itself_ends`). Existing documents with a geometry effect on a symbol instance's fill or stroke draw differently: before, the effect drew nothing. - Effect › Pathfinder takes a symbol instance as the art it draws with the geometry effects of its fill and stroke, as they take a path with such effects: the result painted by the instance's art carries those effects, also when the instance has geometry effects of its own and when the instance sits inside another symbol's art. A click where those effects paint the art outside the instance's bounds selects the instance, a fill only when Selection by Path Only is off, and outline mode still takes the instance's bounds alone. A compound shape's area leaves out its members' fill and stroke effects for symbol instances as for paths, since the compound shape paints the area with its own appearance. These are VectorCraft's own rules (engine `expand::pathfinder_takes_a_symbol_instance_fill_and_stroke_effects`, `a_click_where_a_symbol_instance_fill_or_stroke_effect_paints_selects_it`, `a_stroke_effect_reshapes_a_stroke_a_dynamic_instance_adds`). Before, Pathfinder dropped those effects and clicks took only the instance's bounds. + Effect › Pathfinder takes a symbol instance as the art it draws with the geometry effects of its fill and stroke, as they take a path with such effects: the result painted by the instance's art carries those effects, also when the instance has geometry effects of its own and when the instance sits inside another symbol's art. A click where those effects paint the art outside the instance's bounds selects the instance, a fill only when Selection by Path Only is off, and outline mode still takes the instance's bounds alone. A compound shape's area leaves out its members' fill and stroke effects for symbol instances as for paths, since the compound shape paints the area with its own appearance. These are VectorCraft's own rules (engine `expand::pathfinder_takes_a_symbol_instance_fill_and_stroke_effects`, `a_click_where_a_symbol_instance_fill_or_stroke_effect_paints_selects_it`, `a_stroke_effect_reshapes_a_stroke_a_dynamic_instance_adds`, `a_fill_effect_reshapes_the_fill_of_a_group_in_the_art`, `a_click_on_the_grown_fill_of_an_image_in_the_art_selects_the_instance`). Before, Pathfinder dropped those effects and clicks took only the instance's bounds. The Appearance panel's inline effect editor labels each parameter as the effect dialogs' generic fields do, without the colon ("Max. Radius", "Channel 1", "Create New Fields by"). Roughen's and Zig Zag's Points, Offset Path's Joins, Inner Glow's Source and the menus of Radial Blur, Smart Blur, Sprayed Strokes, Glass, Mezzotint, Halftone Pattern, Grain, Texturizer and De-Interlace are dropdowns with the dialog's labels that send the dialog's values, and a plug-in's choice is a dropdown of the plug-in's values. Revolve's edge, Extrude & Bevel's bevel, every Warp style's orientation, Rasterize's Color Model, Background and Anti-aliasing and the channel of Levels and Curves are dropdowns too, with the labels their own dialogs show. `effect.apply` and `effect.setParams` refuse a Levels or Curves `channel` other than `rgb`, `red`, `green` or `blue` (or `r`, `g` and `b`, in any letter case). Object › Expand Appearance keeps each stroke of a path a stroke (weight, caps, joins, dashes, arrowheads, alignment and width profile) on a copy of the path with the geometry effects baked in, and Object › Expand… is dimmed, with a tooltip, while the selection has appearance attributes, so a stroked line with Zig Zag becomes a stroked zig-zag line and only Expand then outlines it, the two steps the [Expand objects](https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/expand-objects.html) help page describes (#3089). Brushed strokes still become their brush art; `object.expand` still bakes and outlines in one step for agents. From ff1a86114a74f83093a7ad461a1a7311571e0f12 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 20:07:39 -0800 Subject: [PATCH 029/176] Hit testing: keep the shapes a symbol instance's fill and stroke effects paint Every click and hover measured the shapes that each symbol instance with a geometry effect on its fill or stroke paints, once for the cull box and again for the hit, so hovering over a document with many such instances of a complex symbol reshaped every one of them on each move. Those shapes are now kept on the thread, as live objects' art already is, and measured again only when the instance, the symbols, patterns, swatches, fonts or plug-ins change. They are not kept while the symbols hold an image, whose pixels can change when its file is read again. Kept evaluations of live objects and of instances are also measured again when a symbol's 9-slice guides or natural size change; before, a click on a live object holding an instance could follow the old placement. --- crates/doc/src/hit.rs | 160 +++++++++++++++++++++++++----------- crates/doc/src/hit/tests.rs | 71 +++++++++++++++- 2 files changed, 183 insertions(+), 48 deletions(-) diff --git a/crates/doc/src/hit.rs b/crates/doc/src/hit.rs index d8de6acab5..54a201037e 100644 --- a/crates/doc/src/hit.rs +++ b/crates/doc/src/hit.rs @@ -98,10 +98,58 @@ pub fn set_image_paint(f: ImagePaint) { let _ = IMAGE_PAINT.set(f); } +/// The shapes that [`ImagePaint`] gives for one object. +type Painted = Vec<(BezPath, FillRule, AppearanceItem)>; + /// The shapes that the image or symbol instance `n` paints with its geometry effects -/// ([`set_image_paint`]), none while nothing is registered. -pub(crate) fn image_paint(doc: Option<&Document>, n: &Node) -> Vec<(BezPath, FillRule, AppearanceItem)> { - IMAGE_PAINT.get().map_or_else(Vec::new, |f| f(doc, n)) +/// ([`set_image_paint`]), none while nothing is registered. The shapes of a symbol instance of +/// `doc` with an effect on a fill or stroke are kept on this thread ([`PAINT_KEPT`]) and measured +/// again when `n`, a symbol of `doc` or its 9-slice guides or natural size, a pattern of `doc`, +/// its swatches or color groups, or the +/// [`LiveInputs`] have changed since, and on every call while `n` or the document's symbols or +/// patterns hold a placed document or the symbols hold an image ([`symbols_hold_images`]). +pub(crate) fn image_paint(doc: Option<&Document>, n: &Node) -> Rc { + let Some(f) = IMAGE_PAINT.get() else { return Rc::default() }; + let row_effects = || n.appearance.items.iter().any(|i| !i.effects().is_empty()); + let Some(d) = doc.filter(|_| matches!(n.kind, NodeKind::SymbolInstance { .. }) && row_effects()) else { + return Rc::new(f(doc, n)); + }; + let inputs = live_inputs(); + if let Some(painted) = kept(&PAINTED, d, n, inputs) { + return painted; + } + #[cfg(test)] + PAINT_EVALUATED.with(|c| c.set(c.get() + 1)); + let painted = Rc::new(f(doc, n)); + if !symbols_hold_images(d) { + let size = painted.iter().fold(0usize, |s, (bp, _, _)| s.saturating_add(1 + bp.elements().len())); + keep(&PAINTED, d, n, inputs, &painted, size, PAINT_KEPT); + } + painted +} + +/// Does the art of a symbol of `doc` hold an image? The shapes its fills and strokes paint can +/// follow its pixels, which change when its file is read again, so [`image_paint`] does not keep +/// the shapes of an instance then. +fn symbols_hold_images(doc: &Document) -> bool { + let mut image = false; + doc.symbols.iter().for_each(|s| s.art.walk(&mut |c| image |= matches!(c.kind, NodeKind::Image(_)))); + image +} + +/// How many symbol instances' shapes [`image_paint`] keeps on each thread: every click and every +/// hover measures each instance whose fill or stroke has a geometry effect. +const PAINT_KEPT: usize = 64; + +thread_local! { + /// The shapes [`image_paint`] keeps, the latest first. + static PAINTED: RefCell>> = const { RefCell::new(Vec::new()) }; +} + +#[cfg(test)] +thread_local! { + /// How many symbol instances [`image_paint`] measured on this thread. + static PAINT_EVALUATED: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// One level of evaluation of a live object in a document, as the canvas draws it: type in an @@ -128,21 +176,68 @@ fn live_inputs() -> u64 { LIVE_ART.get().map_or(0, |(_, inputs)| inputs()) } -/// A live object evaluated by [`live_art`] on this thread: the object, its document's symbols (by -/// name and art), patterns, swatches and color groups and the [`LiveInputs`] as they were, the art -/// and its [`art_size`]. -struct EvaluatedLive { +/// An object evaluated by [`live_art`] or [`image_paint`] on this thread: the object, its +/// document's symbols (by name and art), patterns, swatches and color groups, the document data +/// that symbols' 9-slice guides and natural sizes are kept in, and the [`LiveInputs`] as they +/// were, the result and its size. +struct Evaluated { node: Node, symbols: Vec<(String, Arc)>, patterns: Vec, swatches: crate::Shared>, swatch_groups: crate::Shared>, + unknown: crate::Shared>, inputs: u64, - art: Rc>, + art: Rc, size: usize, } -impl EvaluatedLive { +/// The evaluations kept on this thread in one store, the latest first. +type Store = std::thread::LocalKey>>>; + +/// The evaluation of `n` in `doc` with inputs `inputs` that `store` keeps, moved to the front. +fn kept(store: &'static Store, doc: &Document, n: &Node, inputs: u64) -> Option> { + store.with_borrow_mut(|kept| { + let i = kept.iter().position(|e| e.is_of(doc, n, inputs))?; + let e = kept.remove(i); + let art = e.art.clone(); + kept.insert(0, e); + Some(art) + }) +} + +/// Keep `art`, of size `size`, the evaluation of `n` in `doc` with inputs `inputs`, at the front +/// of `store`, which keeps `most` evaluations whose sizes add up to [`LIVE_KEPT_SIZE`] at most. +/// Nothing is kept when `art` alone is larger, or when `n` or the document's symbols or patterns +/// hold a placed document ([`holds_placed`]). +fn keep(store: &'static Store, doc: &Document, n: &Node, inputs: u64, art: &Rc, size: usize, most: usize) { + if size > LIVE_KEPT_SIZE || holds_placed(doc, n) { + return; + } + let symbols = doc.symbols.iter().map(|s| (s.name.clone(), s.art.clone())).collect(); + let e = Evaluated { + node: n.clone(), + symbols, + patterns: doc.patterns.clone(), + swatches: doc.swatches.clone(), + swatch_groups: doc.swatch_groups.clone(), + unknown: doc.unknown.clone(), + inputs, + art: art.clone(), + size, + }; + store.with_borrow_mut(|kept| { + kept.insert(0, e); + kept.truncate(most); + let mut total = 0usize; + kept.retain(|e| { + total = total.saturating_add(e.size); + total <= LIVE_KEPT_SIZE + }); + }); +} + +impl Evaluated { /// Is this the evaluation of `n` in `doc`, with inputs `inputs`, as they are now? fn is_of(&self, doc: &Document, n: &Node, inputs: u64) -> bool { self.inputs == inputs @@ -152,6 +247,7 @@ impl EvaluatedLive { && self.patterns == doc.patterns && self.swatches == doc.swatches && self.swatch_groups == doc.swatch_groups + && self.unknown == doc.unknown } } @@ -159,8 +255,9 @@ impl EvaluatedLive { /// envelope's stroke band hits it again and again, and an envelope can hold a blend. const LIVE_KEPT: usize = 4; -/// Most [`art_size`] the evaluations [`live_art`] keeps on one thread add up to. Art larger than -/// this is not kept. +/// Most size the evaluations [`live_art`] keeps on one thread add up to ([`art_size`]), and the +/// shapes [`image_paint`] keeps (each shape and its path elements). Art larger than this is not +/// kept. const LIVE_KEPT_SIZE: usize = 250_000; /// The size of `art` for [`LIVE_KEPT_SIZE`]: its objects and the anchors of their paths. @@ -185,52 +282,23 @@ fn holds_placed(doc: &Document, n: &Node) -> bool { thread_local! { /// The evaluations [`live_art`] keeps, the latest first. - static EVALUATED: RefCell> = const { RefCell::new(Vec::new()) }; + static EVALUATED: RefCell>>> = const { RefCell::new(Vec::new()) }; } /// The art live object `n` of `doc` draws ([`set_live_art`]); [`crate::live::expand_live`] while -/// nothing is registered. The art is evaluated again when `n`, a symbol of `doc`, a pattern of -/// `doc`, its swatches or color groups, or the [`LiveInputs`] have changed since, and on every +/// nothing is registered. The art is evaluated again when `n`, a symbol of `doc` or its 9-slice +/// guides or natural size, a pattern of `doc`, its swatches or color groups, or the +/// [`LiveInputs`] have changed since, and on every /// click while it or the document's symbols or patterns hold a placed document ([`holds_placed`]). fn live_art(doc: &Document, n: &Node) -> Rc> { let inputs = live_inputs(); - let kept = EVALUATED.with_borrow_mut(|kept| { - let i = kept.iter().position(|e| e.is_of(doc, n, inputs))?; - let e = kept.remove(i); - let art = e.art.clone(); - kept.insert(0, e); - Some(art) - }); - if let Some(art) = kept { + if let Some(art) = kept(&EVALUATED, doc, n, inputs) { return art; } #[cfg(test)] LIVE_EVALUATED.with(|c| c.set(c.get() + 1)); let art = Rc::new(LIVE_ART.get().map_or_else(|| crate::live::expand_live(n), |(f, _)| f(Some(doc), n))); - let size = art_size(&art); - if size > LIVE_KEPT_SIZE || holds_placed(doc, n) { - return art; - } - let symbols = doc.symbols.iter().map(|s| (s.name.clone(), s.art.clone())).collect(); - let e = EvaluatedLive { - node: n.clone(), - symbols, - patterns: doc.patterns.clone(), - swatches: doc.swatches.clone(), - swatch_groups: doc.swatch_groups.clone(), - inputs, - art: art.clone(), - size, - }; - EVALUATED.with_borrow_mut(|kept| { - kept.insert(0, e); - kept.truncate(LIVE_KEPT); - let mut total = 0usize; - kept.retain(|e| { - total = total.saturating_add(e.size); - total <= LIVE_KEPT_SIZE - }); - }); + keep(&EVALUATED, doc, n, inputs, &art, art_size(&art), LIVE_KEPT); art } diff --git a/crates/doc/src/hit/tests.rs b/crates/doc/src/hit/tests.rs index 3eac4202b6..4cb7b7b402 100644 --- a/crates/doc/src/hit/tests.rs +++ b/crates/doc/src/hit/tests.rs @@ -599,6 +599,60 @@ fn evaluated_art_is_not_kept_while_a_placed_document_may_show_in_it() { assert_eq!(evaluated(), before + 2); } +/// For instances of the symbol "Painted", a fill that paints the square from (300, 0) to +/// (320, 20); nothing for anything else. +fn painted_far_away(_: Option<&Document>, n: &Node) -> Vec<(BezPath, FillRule, AppearanceItem)> { + match &n.kind { + NodeKind::SymbolInstance { symbol, .. } if symbol == "Painted" => { + let square = shapes::rectangle(Rect::new(300.0, 0.0, 320.0, 20.0)).to_bezpath(); + vec![(square, FillRule::NonZero, AppearanceItem::Fill(crate::FillLayer::new(Paint::solid(Color::rgb(1.0, 0.0, 0.0)))))] + } + _ => vec![], + } +} + +/// Clicks and hovers measure the shapes a symbol instance's fill and stroke effects paint once, +/// and again only after the instance or the symbols change. +#[test] +fn clicks_measure_a_symbol_instances_painted_shapes_once_until_it_changes() { + set_image_paint(painted_far_away); + let mut d = Document::new(1000.0, 1000.0); + let l = d.layers[0].id; + let art = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 20.0, 20.0)), Appearance::default_art()); + d.symbols.push(crate::Symbol { dynamic: false, name: "Painted".into(), art: Arc::new(art) }); + let inst = d.alloc_id(); + let mut n = Node::new(inst, NodeKind::SymbolInstance { symbol: "Painted".into(), xf: vectorcraft_geom::Affine::IDENTITY }); + n.appearance = Appearance::default_art().into(); + let offset = crate::Effect { id: "path.offsetPath".into(), params: serde_json::json!({"offset": 10}), visible: true }; + n.appearance.items[0].effects_mut().push(offset); + d.insert(Some(l), 0, n).unwrap(); + let measured = || PAINT_EVALUATED.with(std::cell::Cell::get); + let before = measured(); + let at = |d: &Document, x: f64| hit_test(d, Point::new(x, 10.0), HitOptions::default()).map(|h| h.leaf); + assert_eq!(at(&d, 310.0), Some(inst), "a click where the instance's fill paints"); + assert_eq!(at(&d, 500.0), None); + assert_eq!(at(&d, 10.0), Some(inst)); + assert_eq!(measured(), before + 1); + d.node_mut(inst).unwrap().appearance.items[0].effects_mut()[0].params = serde_json::json!({"offset": 12}); + assert_eq!(at(&d, 310.0), Some(inst)); + assert_eq!(measured(), before + 2, "a changed instance is measured again"); + let other = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 5.0, 5.0)), Appearance::default_art()); + d.symbols.push(crate::Symbol { dynamic: false, name: "Other".into(), art: Arc::new(other) }); + assert_eq!(at(&d, 310.0), Some(inst)); + assert_eq!(measured(), before + 3, "changed symbols measure it again"); + assert_eq!(at(&d, 310.0), Some(inst)); + assert_eq!(measured(), before + 3); + // An image's pixels change when its file is read again, so with one in a symbol's art every + // click measures the instance. + let xf = vectorcraft_geom::Affine::IDENTITY; + let im = crate::ImageObject { key: "k".into(), width: 10, height: 10, xf, link: None, placement: Default::default(), pixels: None }; + let image = Node::new(d.alloc_id(), NodeKind::Image(Box::new(im))); + d.symbols.push(crate::Symbol { dynamic: false, name: "Photo".into(), art: Arc::new(image) }); + assert_eq!(at(&d, 310.0), Some(inst)); + assert_eq!(at(&d, 310.0), Some(inst)); + assert!(measured() >= before + 5, "each click measures it: {}", measured() - before); +} + /// A kept evaluation is the evaluation of the object only while the fonts and plug-ins /// ([`LiveInputs`]) are as they were. #[test] @@ -611,19 +665,32 @@ fn a_kept_evaluation_is_stale_after_the_live_inputs_change() { } /// An evaluation of `n` in `d`, with inputs 7, holding no symbols, patterns or art. -fn kept_evaluation(d: &Document, n: &Node) -> EvaluatedLive { - EvaluatedLive { +fn kept_evaluation(d: &Document, n: &Node) -> Evaluated> { + Evaluated { node: n.clone(), symbols: vec![], patterns: vec![], swatches: d.swatches.clone(), swatch_groups: d.swatch_groups.clone(), + unknown: d.unknown.clone(), inputs: 7, art: std::rc::Rc::new(vec![]), size: 0, } } +/// A kept evaluation is stale once a symbol's 9-slice guides or natural size change: they place +/// the symbol's art, and the document keeps them apart from the symbols. +#[test] +fn a_kept_evaluation_is_stale_after_a_symbols_placement_changes() { + let mut d = Document::new(100.0, 100.0); + let n = Node::path(NodeId(3), shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)), Appearance::default_art()); + let e = kept_evaluation(&d, &n); + assert!(e.is_of(&d, &n, 7)); + d.unknown.insert(crate::SYMBOL_SIZES.into(), serde_json::json!({"Logo": [40.0, 20.0]})); + assert!(!e.is_of(&d, &n, 7)); +} + /// A kept evaluation is stale once a swatch changes, in a color group too: a painted live effect's /// pieces name swatches. #[test] From 64662b435b545bd6d6f47553f92032bba38a9055 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 20:32:04 -0800 Subject: [PATCH 030/176] Scripts: a file opened under a withdrawn grant is not read When a run evaluated code that withdrew a kept grant, a File opened under that grant still gave the bytes it held to read, readln and readch, and seek to the end showed its length. Those calls now give Script file access denied and set error, and eof is true. docs/mcp.md says so. --- crates/engine/src/script/files.rs | 37 +++++++++++++++++++++++----- crates/engine/src/tests/script_io.rs | 24 ++++++++++++++++++ crates/js/src/file_classes.rs | 7 +++++- docs/mcp.md | 3 ++- 4 files changed, 63 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index ba1bc60827..be813e3a74 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -420,6 +420,12 @@ impl Disk { } } } + // Objects that hold a file the run may no longer read give none of it. + for o in self.open.values_mut() { + if o.read_from.as_deref().is_some_and(|p| !self.scope.allows(p)) { + o.unreadable = true; + } + } } /// Writes the evaluated code this run ran into the grants it kept with Always, so a later run @@ -1391,6 +1397,9 @@ struct Open { /// The grant the file was opened under was withdrawn while its changes could not be written: /// they are written again when the run ends, and the object takes no more writes. withdrawn: bool, + /// The run may no longer read the file the object holds: `read`, `readln`, `readch` and `seek` + /// give [`ACCESS_DENIED`], and `eof` is true. + unreadable: bool, } impl Open { @@ -1410,7 +1419,17 @@ impl Open { } else { (Encoding::Cp1252, 0) }; - Some(Self { bytes, pos, encoding, name: encoding.name().to_string(), target: None, read_from: None, dirty: false, withdrawn: false }) + Some(Self { + bytes, + pos, + encoding, + name: encoding.name().to_string(), + target: None, + read_from: None, + dirty: false, + withdrawn: false, + unreadable: false, + }) } /// Writes `text` at the position, over what is there and past the end, when it takes at most @@ -1593,6 +1612,12 @@ fn with_open(host: &Host, a: &[Data], f: impl FnOnce(&mut Open) -> Data) -> Data } } +/// [`with_open`] for a call that reads what the file holds: `{error}` [`ACCESS_DENIED`] when the +/// run may no longer read it. +fn with_readable(host: &Host, a: &[Data], f: impl FnOnce(&mut Open) -> Data) -> Data { + with_open(host, a, |file| if file.unreadable { error(ACCESS_DENIED) } else { f(file) }) +} + /// The first two arguments as path text, refused with a `RangeError` when either is too long. fn two_paths(a: &[Data]) -> Result<(String, String), HostError> { let (path, base) = (arg_text(a, 0), arg_text(a, 1)); @@ -2031,20 +2056,20 @@ pub(crate) fn dialog_filters(filter: &str) -> Vec<(String, Vec)> { fn read(host: &Host, a: &[Data]) -> Result { let max = arg_number(a, 1).filter(|n| *n >= 0.0).map(|n| n as usize); - Ok(with_open(host, a, |f| text_result(f.read(max)))) + Ok(with_readable(host, a, |f| text_result(f.read(max)))) } fn readln(host: &Host, a: &[Data]) -> Result { - Ok(with_open(host, a, |f| text_result(f.read_line()))) + Ok(with_readable(host, a, |f| text_result(f.read_line()))) } fn readch(host: &Host, a: &[Data]) -> Result { - Ok(with_open(host, a, |f| text_result(f.read_char()))) + Ok(with_readable(host, a, |f| text_result(f.read_char()))) } fn seek(host: &Host, a: &[Data]) -> Result { let (Some(pos), Some(mode)) = (arg_number(a, 1), arg_number(a, 2)) else { return Err(HostError::Type(BAD_SEEK.into())) }; - Ok(with_open(host, a, |f| { + Ok(with_readable(host, a, |f| { let base = match mode as u8 { 1 => f.pos as f64, 2 => f.bytes.len() as f64, @@ -2066,7 +2091,7 @@ fn tell(host: &Host, a: &[Data]) -> Result { } fn eof(host: &Host, a: &[Data]) -> Result { - Ok(Data::Bool(host.disk.borrow().open.get(&handle(a)).is_none_or(|f| f.pos >= f.bytes.len()))) + Ok(Data::Bool(host.disk.borrow().open.get(&handle(a)).is_none_or(|f| f.unreadable || f.pos >= f.bytes.len()))) } fn encoding(host: &Host, a: &[Data]) -> Result { diff --git a/crates/engine/src/tests/script_io.rs b/crates/engine/src/tests/script_io.rs index 9b9cee9439..ae782692f3 100644 --- a/crates/engine/src/tests/script_io.rs +++ b/crates/engine/src/tests/script_io.rs @@ -1854,6 +1854,30 @@ fn script_files_open_under_a_withdrawn_grant_keep_their_unwritten_changes() { let _ = std::fs::remove_dir_all(base); } +/// A file opened for reading under a kept grant that new code withdraws gives no more of what it +/// holds. +#[test] +fn script_files_open_under_a_withdrawn_grant_are_not_read() { + let base = folder("grantwithdrawnread"); + let dir = base.join("picked"); + write(&dir.join("in.txt"), b"secret"); + let text = format!( + "var f = new File({:?});\n\ + if (!f.open('r')) vc.log(['asked', !!Folder.selectDialog('p')]);\n\ + else {{ var a = f.readch(); eval('1'); var r = f.read(), e = f.error; f.error = ''; vc.log([a, r, e, f.eof, f.seek(0, 2), f.error, f.tell()]); }}", + dir.join("in.txt").to_string_lossy() + ); + let mut s = with_data(&base); + start_framed(&mut s, &base, &text); + assert!(pump_to_picker(&mut s).is_none()); + assert!(s.script_pick(crate::script::files::PickAnswer::Allow { paths: vec![dir.to_string_lossy().into_owned()], always: true })); + assert_eq!(pump_to_picker(&mut s).unwrap().unwrap()["log"], json!([["asked", true]])); + start_framed(&mut s, &base, &text); + let r = pump_to_picker(&mut s).unwrap().unwrap(); + assert_eq!(r["log"], json!([["s", "", DENIED, true, false, DENIED, 1]])); + let _ = std::fs::remove_dir_all(base); +} + /// The folder that holds the settings is kept out of every grant: a pick there gives `null` with the /// error, a grant written into the grants file for it is not taken, and the script cannot write the /// grants file through its data folder. diff --git a/crates/js/src/file_classes.rs b/crates/js/src/file_classes.rs index f1bba51291..c962bf9679 100644 --- a/crates/js/src/file_classes.rs +++ b/crates/js/src/file_classes.rs @@ -887,7 +887,12 @@ fn seek(i: &mut Interp, this: Value, args: &[Value], _: bool) -> JsResult return Err(i.throw(ErrorType::Range, "File.seek: the mode must be 0, 1 or 2")); } let Some(h) = opened(i, o)? else { return Ok(Value::Bool(false)) }; - host(i, "seek", &[h, Value::Number(pos.floor()), Value::Number(mode)]) + let r = host(i, "seek", &[h, Value::Number(pos.floor()), Value::Number(mode)])?; + // A seek the host refuses sets `error` and gives `false`. + if !outcome(i, o, &r)? { + return Ok(Value::Bool(false)); + } + Ok(r) } fn tell(i: &mut Interp, this: Value, _: &[Value], _: bool) -> JsResult { diff --git a/docs/mcp.md b/docs/mcp.md index 1c49dde6c9..4562889e7e 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2458,7 +2458,8 @@ VectorCraft writes files by these rules of its own: asks again. It is offered only for a script run from a file. The grant also keeps the SHA-256 of each source the run evaluated up to its end (a file `$.evalFile` ran, a string given to `eval` or `Function`, at most 256). A later run loses the grant before it evaluates a source the grant does not list, and from the start when its - `#targetengine` engine holds code the grant does not list, such as another script's. A kept grant stays on the + `#targetengine` engine holds code the grant does not list, such as another script's. A file opened under a + grant the run loses gives `Script file access denied` when it is read or `seek` is called after that. A kept grant stays on the real path that was allowed: when that path now leads elsewhere, through a link put in its place or in a folder above it, the grant is not used. - A command a script runs with `vc.run` reads and writes files only where the script's `File` and `Folder` objects From 1bf936defa9465d3f60d82ad2d2b8edbe17f00b7 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 13 Nov 2026 21:05:20 -0800 Subject: [PATCH 031/176] Tests: the Enter-denies test removes its temporary folder --- crates/ui-egui/src/tests/script_run.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/tests/script_run.rs b/crates/ui-egui/src/tests/script_run.rs index 202ac35c6f..882799385e 100644 --- a/crates/ui-egui/src/tests/script_run.rs +++ b/crates/ui-egui/src/tests/script_run.rs @@ -540,7 +540,8 @@ fn enter_in_a_scripts_file_dialog_denies() { let source = "vc.log(Folder.selectDialog('Pick'));"; menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": source })).unwrap().unwrap(); script_runs::poll(&mut app); - app.script_picked = vec![folder("enterdeny").to_string_lossy().into_owned()]; + let dir = folder("enterdeny"); + app.script_picked = vec![dir.to_string_lossy().into_owned()]; let ctx = egui::Context::default(); crate::theme::install_fonts(&ctx); let enter = egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }; @@ -551,6 +552,7 @@ fn enter_in_a_scripts_file_dialog_denies() { assert!(app.ui.dialog.as_ref().is_none_or(|d| d.kind != dialogs::script_run::PICKER_KIND), "the dialog closes"); finish(&mut app); assert_eq!(app.session.script_report().unwrap()["log"], json!([null])); + let _ = std::fs::remove_dir_all(&dir); } /// Enter on the file dialog's focused Choose… button goes to that button, which opens the folder From 6864086cda15fa4fad3f3c920550bf7b39cb3f80 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 02:50:41 -0800 Subject: [PATCH 032/176] i18n: keep bracketed field names untranslated in fr rows --- crates/ui-egui/src/i18n/fr.tsv | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 6fc56e60cb..83effda4cc 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -7593,7 +7593,7 @@ breakText Glyphs Glyphes @msg `alignOn` must be a string `alignOn` doit être une chaîne @msg `align` is start, center or end `align` vaut start, center ou end @msg `align` must be a string `align` doit être une chaîne -@msg `anchors` must be an array of [subpath, anchor] pairs `anchors` doit être une liste de paires [sous-tracé, point d’ancrage] +@msg `anchors` must be an array of [subpath, anchor] pairs `anchors` doit être une liste de paires [subpath, anchor] @msg `anchors` must list anchor indices (0, 1, 2…), not {k} `anchors` doit lister des indices de points d’ancrage (0, 1, 2…), pas {k} @msg `anchors` must list anchor indices (0, 1, 2…), not {v} `anchors` doit lister des indices de points d’ancrage (0, 1, 2…), pas {v} @msg `answer` for this {kind} dialog must be one of: {_1} `answer` pour cette boîte de dialogue {kind} doit valoir l’une de ces valeurs : {_1} @@ -7657,7 +7657,7 @@ breakText Glyphs Glyphes @msg `fidelity` must be from {lo} to {hi} pt `fidelity` doit être compris entre {lo} et {hi} pt @msg `files` must be 1 to 1000 paths of font files the last text.findFontFiles search found `files` doit contenir de 1 à 1000 chemins de fichiers de police trouvés par la dernière recherche text.findFontFiles @msg `focal` and `radius` cannot be used together `focal` et `radius` ne peuvent pas être utilisés ensemble -@msg `focal` must be an array of [subpath, anchor] pairs `focal` doit être une liste de paires [sous-tracé, point d’ancrage] +@msg `focal` must be an array of [subpath, anchor] pairs `focal` doit être une liste de paires [subpath, anchor] @msg `focal` names [{si}, {ai}], which is not an anchor of the path `focal` désigne [{si}, {ai}], qui n’est pas un point d’ancrage du tracé @msg `folder` must be an absolute folder path `folder` doit être le chemin absolu d’un dossier @msg `fontAxes` must be an object of axis tags and values, such as {"wght"} `fontAxes` doit être un objet de balises d’axe et de valeurs, comme {"wght"} From 72082aee46c4902a8c39483f16dc8ad832b257b7 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 12:27:34 -0800 Subject: [PATCH 033/176] Tools: tool.setOption refuses non-object parameters and keeps its target tool Parameters that are not an object (true, 7, [], "x") are an error instead of an empty read; no parameters (null) still read the options. The tool an option is checked against is named before the edit in progress is finished, so a held Cmd press made by finishing it no longer sends the value to the selection tool it lends. --- crates/engine/src/tests/build.rs | 20 ++++++++++++++++++++ crates/engine/src/tooling.rs | 20 ++++++++++++-------- crates/tools/src/option_check.rs | 13 +++++++++++-- docs/control-protocol.md | 3 ++- docs/mcp.md | 3 ++- 5 files changed, 47 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/tests/build.rs b/crates/engine/src/tests/build.rs index cb61ac1b9e..545551f13f 100644 --- a/crates/engine/src/tests/build.rs +++ b/crates/engine/src/tests/build.rs @@ -1049,6 +1049,26 @@ fn shape_builder_drops_a_press_held_during_a_merge() { } } +/// `tool.setOption` without a tool, while a Cmd press is held during a merge, sets the Shape +/// Builder's option: finishing the merge makes the press, which lends the selection tool, and the +/// value still goes to the Shape Builder it was checked against. +#[test] +fn shape_builder_option_set_while_a_cmd_press_is_held_goes_to_the_shape_builder() { + let v = ViewInfo::default(); + let mut s = session(); + s.select_tool("shapeBuilder", v).unwrap(); + s.set_tool_option_cmd(&json!({"key": "pickColorFrom", "value": "swatches"})).unwrap(); + square_row(&mut s); + click_row(&mut s, v); + s.pointer(&PointerEvent::new(PointerKind::Down, 305.0, 10.0).with_mods(Mods { cmd: true, ..Default::default() }), v).unwrap(); + assert!(s.tool_editing(), "the press is held"); + let out = s.set_tool_option_cmd(&json!({"key": "pickColorFrom", "value": "artwork"})).unwrap(); + assert_eq!(s.tool_id(), "selection", "the held press lent the selection tool"); + assert_eq!(s.lender.as_ref().map(|t| t.id()), Some("shapeBuilder")); + assert_eq!(out["pickColorFrom"], json!("artwork")); + assert_eq!(s.lender.as_ref().map(|t| t.options()["pickColorFrom"].clone()), Some(json!("artwork"))); +} + /// A new revision of the document made outside a command while a merge is computed on another /// thread keeps the merge when the selected art is as it was (the next poll applies it, as the /// command computes it), and drops it when the art changed. diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index df7ef4b1d8..fcbaf664d0 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -1319,12 +1319,15 @@ impl Session { { return Err(format!("unknown tool `{t}`")); } - let active = tool.is_none_or(|t| t == self.tool.id()); + // The tool is named before the edit in progress is finished: finishing it can make a held + // Cmd press, which lends a selection tool and makes that the active tool. + let id = tool.unwrap_or(self.tool.id()); + let active = id == self.tool.id(); if values.is_empty() { - return Ok(self.tool_options_of(tool.unwrap_or(self.tool.id()))); + return Ok(self.tool_options_of(id)); } // Every value is checked before any is set, so an invalid one changes nothing. - vectorcraft_tools::builder::check_builder_options(tool.unwrap_or(self.tool.id()), &values)?; + vectorcraft_tools::builder::check_builder_options(id, &values)?; // The Place queue is read later, by a click outside any automation scope: its files must // be readable now, under the roots of whoever sets it. if let Some(entries) = values.get("queue").and_then(|q| q.get("entries")).and_then(Value::as_array) { @@ -1332,7 +1335,7 @@ impl Session { crate::file_access::check_read(path)?; } } - if tool.unwrap_or(self.tool_id()) == "dimension" { + if id == "dimension" { if let Some(style) = values.get("style") { vectorcraft_doc::dimension::DimensionOptions::from_params(style.clone())?; } @@ -1342,15 +1345,16 @@ impl Session { return Err("Unknown dimension mode".into()); } } - match tool.filter(|_| !active) { - Some(id) => vectorcraft_tools::option_check::check_values(self.make_tool(id).as_ref(), &values)?, - None => vectorcraft_tools::option_check::check_values(self.tool.as_ref(), &values)?, + if active { + vectorcraft_tools::option_check::check_values(self.tool.as_ref(), &values)?; + } else { + vectorcraft_tools::option_check::check_values(self.make_tool(id).as_ref(), &values)?; } // The active tool's merge being computed is applied with the options it was started with. if active { self.finish_tool_edit_later().map_err(|e| e.to_string())?; } - Ok(self.set_tool_options(tool, &values)) + Ok(self.set_tool_options(Some(id), &values)) } /// Let the active tool finish work a command from outside it ended ([`vectorcraft_tools::Tool::after_command`]): diff --git a/crates/tools/src/option_check.rs b/crates/tools/src/option_check.rs index 9c16deb9cf..9a45caeb13 100644 --- a/crates/tools/src/option_check.rs +++ b/crates/tools/src/option_check.rs @@ -65,9 +65,12 @@ pub fn string_or_null(key: &str, v: &Value) -> Result<(), String> { /// What `tool.setOption {tool?, key?, value?, values?}` sets: the tool named (none: the active /// tool) and the options, `key` and `value` among `values`. A parameter of the wrong type, a /// `value` without a `key` or a `key` without a `value`, and an option given both as `key` and in -/// `values` are errors. With none of `key` and `values`, the options are empty: the command reads -/// them. +/// `values` are errors, and so are parameters that are not an object. With none of `key` and +/// `values`, or with no parameters (null), the options are empty: the command reads them. pub fn set_option_params(p: &Value) -> Result<(Option<&str>, Map), String> { + if !p.is_object() && !p.is_null() { + return Err("the parameters must be an object".into()); + } let tool = match p.get("tool") { None => None, Some(t) => Some(t.as_str().ok_or("`tool` must be a tool id")?), @@ -139,6 +142,12 @@ mod tests { let empty = json!({}); let (tool, values) = set_option_params(&empty).unwrap(); assert!(tool.is_none() && values.is_empty()); + // Omitted parameters arrive as null: a read, like `{}`. + let (tool, values) = set_option_params(&Value::Null).unwrap(); + assert!(tool.is_none() && values.is_empty()); + for bad in [json!(true), json!(7), json!([]), json!("x")] { + assert_eq!(set_option_params(&bad).err(), Some("the parameters must be an object".into()), "{bad}"); + } assert_eq!(set_option_params(&json!({"tool": 3})).err(), Some("`tool` must be a tool id".into())); assert_eq!(set_option_params(&json!({"values": [1]})).err(), Some("`values` must be an object".into())); assert_eq!(set_option_params(&json!({"key": 3, "value": 1})).err(), Some("`key` must be a string".into())); diff --git a/docs/control-protocol.md b/docs/control-protocol.md index a32c3272df..edd0d8f96f 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -921,7 +921,8 @@ Halftone… (`engine.execute {command: "ui.menuDialog", params: {command: "objec Tool options last: `tool.setOption {key, value}` or `{values: {…}}` (and `tool` to set another tool's) sets them, and the options a tool keeps (Liquify brush and tool options, Mirror & Cut, Puppet Warp, Symbolism, drawing tools) stay when you switch tools or documents and are saved with the preferences. The Liquify tools share their Global Brush -Dimensions (`width`, `height`, `angle`, `intensity`). `{}` reads the options and sets nothing. Every option given is +Dimensions (`width`, `height`, `angle`, `intensity`). `{}` reads the options and sets nothing; parameters that are +not an object are an error. Every option given is checked before any is set: an option the tool doesn't have, a value of the wrong type, a number outside the tool's range or an unknown choice is an error that names the tool and the option (``tool `smooth`: `fidelity` must be a number from 0.05 to 100``), and no option, preference or undo step changes. diff --git a/docs/mcp.md b/docs/mcp.md index 3901375542..0c46157847 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -9815,7 +9815,8 @@ Every option given is checked before any is set. A key that the tool's `check_op to that tool), a value of the wrong type, a number outside the tool's range, an unknown choice, a `key` without a `value`, a `values` that is not an object or a `tool` that is not a tool id is an error result that names the tool and the option, and nothing changes: no option, no saved preference and no undo step, also when another option given with -it is good. `{}` reads the options and sets nothing. The ranges are VectorCraft's own (for example the Smooth tool's +it is good. Parameters that are not an object are an error too. `{}`, or no parameters, reads the options and sets +nothing. The ranges are VectorCraft's own (for example the Smooth tool's `fidelity` takes 0.05 to 100, the Pencil's 0.01 to 100); a refused value in a Tool Options dialog keeps the dialog open. The Live Paint tools' `width` and the Shape Builder's `gapLength` are set to the nearest end of their range when a number outside it is given, as their sections above say. From cefaeefca942b8978110dc79193ae10730c8991d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 12:38:25 -0800 Subject: [PATCH 034/176] Scripts: grants kept earlier in a run keep the code evaluated before a later one Keeping a second grant with Always marked all the code the run had evaluated as recorded, so the run's end skipped the grants kept before it, and they kept the code list from when they were kept. The next run that evaluated that code withdrew them. Keeping a grant now writes the current code list into the grants the run kept before it as well. --- crates/engine/src/script/files.rs | 12 +++++++++- crates/engine/src/tests/script_io.rs | 35 ++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index be813e3a74..216e27f677 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -569,7 +569,7 @@ impl Disk { /// Adds grants of `paths` (with `write`, folders when `folder`) for this script to the grants /// file, with the code the run has evaluated so far, written whole to a file beside it that then - /// takes its place. + /// takes its place. The grants the run kept before are given the same code. fn keep(&self, paths: &[std::path::PathBuf], write: bool, folder: bool) -> Result<(), &'static str> { let (Some((script, hash)), Some(store)) = (&self.script, self.store_path()) else { return Err(NO_ALWAYS) }; // A grants file that is there but cannot be read is left as it is. @@ -577,6 +577,16 @@ impl Disk { let mut grants = try_read_store(&store).map_err(|_| NOT_SAVED)?; let script = shown(script); let code: Vec<&String> = self.ran.iter().collect(); + // The grants this run kept before take the code evaluated since, as the run's end would + // have given them. + for g in &mut grants { + if g["script"] == *script + && g["sha256"] == *hash + && self.kept.iter().any(|(p, w, f)| g["path"] == *shown(p) && g["write"] == *w && g["folder"] == *f) + { + g["code"] = serde_json::json!(code); + } + } for p in paths { let path = shown(p); grants diff --git a/crates/engine/src/tests/script_io.rs b/crates/engine/src/tests/script_io.rs index ae782692f3..4463c19e97 100644 --- a/crates/engine/src/tests/script_io.rs +++ b/crates/engine/src/tests/script_io.rs @@ -1766,6 +1766,41 @@ fn script_file_grants_keep_the_code_evaluated_after_the_dialog() { let _ = std::fs::remove_dir_all(base); } +/// A grant kept with Always before a second one is kept in the same run also keeps the code the +/// run evaluated between the two, so the next run that evaluates it keeps both grants. +#[test] +fn script_file_grants_kept_earlier_in_a_run_keep_the_code_evaluated_before_a_later_grant() { + let base = folder("grantbetween"); + let first = base.join("picked/a.txt"); + let second = base.join("picked/b.txt"); + write(&first, b"a"); + write(&second, b"b"); + let text = format!( + "var a = new File({:?}); var ka = a.open('r');\n\ + if (!ka) File.openDialog('a');\n\ + var between = eval('new File(a.fsName).open(\"r\")');\n\ + var b = new File({:?}); var kb = b.open('r');\n\ + if (!kb) File.openDialog('b');\n\ + vc.log([ka, between, kb, new File(a.fsName).open('r')]);", + first.to_string_lossy(), + second.to_string_lossy() + ); + let mut s = with_data(&base); + start_framed(&mut s, &base, &text); + assert!(pump_to_picker(&mut s).is_none()); + assert!(s.script_pick(crate::script::files::PickAnswer::Allow { paths: vec![first.to_string_lossy().into_owned()], always: true })); + assert!(pump_to_picker(&mut s).is_none()); + assert!(s.script_pick(crate::script::files::PickAnswer::Allow { paths: vec![second.to_string_lossy().into_owned()], always: true })); + assert_eq!(pump_to_picker(&mut s).unwrap().unwrap()["log"], json!([[false, true, false, true]])); + start_framed(&mut s, &base, &text); + assert_eq!( + pump_to_picker(&mut s).unwrap().unwrap()["log"], + json!([[true, true, true, true]]), + "the first grant keeps the code evaluated before the second" + ); + let _ = std::fs::remove_dir_all(base); +} + /// Code another script left in a named engine withdraws a script's kept grants in that engine. #[test] fn script_file_grants_are_withdrawn_by_code_another_script_left_in_the_engine() { From d435ae1a27abf9b9efdd01ab771663d9ef22e3a8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 12:32:26 -0800 Subject: [PATCH 035/176] Scripts: an open file that is renamed is read under its new path's rules `rename` moved the write path of open File objects but left the path they were read from at the old name. When new code then withdrew the kept grant for the folder, a grant the run still held for the old path let the object go on giving the file's bytes. The read path now moves with the write path. --- crates/engine/src/script/files.rs | 13 +++++++++---- crates/engine/src/tests/script_io.rs | 29 ++++++++++++++++++++++++++++ 2 files changed, 38 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index 216e27f677..19c1a37409 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -1844,11 +1844,16 @@ fn rename(host: &Host, a: &[Data]) -> Result { if std::fs::rename(&from, &to).is_err() { return Ok(error(WRITE_FAILED)); } - // Open objects of the file, or of files in the folder, write to the new path. - for file in disk.open.values_mut() { - if let Some(rest) = file.target.as_deref().and_then(|t| t.strip_prefix(&from).ok()) { - file.target = Some(if rest.as_os_str().is_empty() { to.clone() } else { to.join(rest) }); + // Open objects of the file, or of files in the folder, write to the new path, and the rules for + // reading apply to them there. + let moved = |p: &mut Option| { + if let Some(rest) = p.as_deref().and_then(|t| t.strip_prefix(&from).ok()) { + *p = Some(if rest.as_os_str().is_empty() { to.clone() } else { to.join(rest) }); } + }; + for file in disk.open.values_mut() { + moved(&mut file.target); + moved(&mut file.read_from); } // The old path no longer holds the file, so the report names it as well as the new one. disk.wrote(&from); diff --git a/crates/engine/src/tests/script_io.rs b/crates/engine/src/tests/script_io.rs index 4463c19e97..1943a11bab 100644 --- a/crates/engine/src/tests/script_io.rs +++ b/crates/engine/src/tests/script_io.rs @@ -1913,6 +1913,35 @@ fn script_files_open_under_a_withdrawn_grant_are_not_read() { let _ = std::fs::remove_dir_all(base); } +/// A file opened for reading and then renamed is read under the rules for its new path: when new code +/// withdraws the kept grant for its folder, a grant the run still holds for its old path does not let +/// the object give more of it. +#[test] +fn script_files_renamed_while_open_are_read_under_their_new_path() { + let base = folder("grantwithdrawnrenamed"); + let dir = base.join("picked"); + let file = dir.join("in.txt"); + write(&file, b"secret"); + let text = format!( + "var f = new File({:?});\n\ + if (!f.open('r')) vc.log(['asked', !!Folder.selectDialog('p')]);\n\ + else {{ var a = f.readch(); File.openDialog('p'); var n = new File(f.fsName).rename('r.txt'); eval('1');\n\ + var r = f.read(), e = f.error; vc.log([a, n, r, e]); }}", + file.to_string_lossy() + ); + let mut s = with_data(&base); + start_framed(&mut s, &base, &text); + assert!(pump_to_picker(&mut s).is_none()); + assert!(s.script_pick(crate::script::files::PickAnswer::Allow { paths: vec![dir.to_string_lossy().into_owned()], always: true })); + assert_eq!(pump_to_picker(&mut s).unwrap().unwrap()["log"], json!([["asked", true]])); + start_framed(&mut s, &base, &text); + assert!(pump_to_picker(&mut s).is_none()); + assert!(s.script_pick(crate::script::files::PickAnswer::Allow { paths: vec![file.to_string_lossy().into_owned()], always: false })); + let r = pump_to_picker(&mut s).unwrap().unwrap(); + assert_eq!(r["log"], json!([["s", true, "", DENIED]])); + let _ = std::fs::remove_dir_all(base); +} + /// The folder that holds the settings is kept out of every grant: a pick there gives `null` with the /// error, a grant written into the grants file for it is not taken, and the script cannot write the /// grants file through its data folder. From 1ae70095ccc33735bf52c198abe68d3340c56f47 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 12:47:48 -0800 Subject: [PATCH 036/176] Scripts: the grants-file lock waits a bounded time Taking the lock on Script Grants.lock blocked until the holder let go, so another process that stalled while holding it stopped listing, loading, keeping and revoking grants for good. The lock is now tried 20 times, 50 ms apart, and then fails with TimedOut: a change is not made and a read gives no grants rather than reading without the lock. --- crates/engine/src/script/files.rs | 50 ++++++++++++++++++++++++---- crates/engine/src/tests/script_io.rs | 36 ++++++++++++++++++++ 2 files changed, 80 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index 19c1a37409..0e863fa03d 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -900,10 +900,10 @@ fn read_head(real: &Path, max: usize) -> std::io::Result> { } /// The grants the grants file at `store` holds; none when it is missing or cannot be read. A grant -/// that is not well formed is left out. It is read under [`lock_store`]'s lock when that can be -/// taken, so it is read between two changes. +/// that is not well formed is left out. It is read under [`lock_store`]'s lock, so it is read +/// between two changes, and none are read when the lock cannot be taken. fn read_store(store: &Path) -> Vec { - let _lock = lock_store(store).ok(); + let Ok(_lock) = lock_store(store) else { return Vec::new() }; load_store(store, false).unwrap_or_default() } @@ -983,9 +983,20 @@ fn write_store(store: &Path, grants: Vec) -> std::io::Result< }) } +/// How many times [`lock_store`] tries to take the grants file's lock, [`LOCK_PAUSE`] apart, before +/// it gives up. +#[cfg(not(target_arch = "wasm32"))] +pub(crate) const LOCK_TRIES: u32 = 20; + +/// The wait between two tries of [`lock_store`]. +#[cfg(not(target_arch = "wasm32"))] +const LOCK_PAUSE: std::time::Duration = std::time::Duration::from_millis(50); + /// The lock file beside the grants file at `store` (`Script Grants.lock`), locked until it is -/// dropped and waiting while another process holds it, so that processes that read and change the -/// grants file take turns. A change is not made when the lock cannot be taken. +/// dropped, so that processes that read and change the grants file take turns. While another +/// process or handle holds it, the lock is tried [`LOCK_TRIES`] times, [`LOCK_PAUSE`] apart, and +/// then the result is `Err` with [`std::io::ErrorKind::TimedOut`]. A change is not made when the +/// lock cannot be taken. #[cfg(not(target_arch = "wasm32"))] fn lock_store(store: &Path) -> std::io::Result { let lock = store.with_extension("lock"); @@ -993,13 +1004,40 @@ fn lock_store(store: &Path) -> std::io::Result { .parent() .map_or(Ok(()), std::fs::create_dir_all) .and_then(|()| std::fs::File::options().create(true).truncate(false).read(true).write(true).open(&lock)); - let file = opened.and_then(|f| f.lock().map(|()| f)); + let file = opened.and_then(take_lock); if let Err(e) = &file { log::warn!("can't lock {}: {e}", lock.display()); } file } +/// `file`, locked within [`lock_store`]'s tries. +#[cfg(not(target_arch = "wasm32"))] +fn take_lock(file: std::fs::File) -> std::io::Result { + let mut tries = 1; + loop { + match file.try_lock() { + Ok(()) => return Ok(file), + Err(std::fs::TryLockError::Error(e)) => return Err(e), + Err(std::fs::TryLockError::WouldBlock) if tries >= LOCK_TRIES => { + return Err(std::io::Error::new(std::io::ErrorKind::TimedOut, "another process holds the lock")); + } + Err(std::fs::TryLockError::WouldBlock) => tries += 1, + } + #[cfg(test)] + if WHILE_GRANTS_LOCKED.with_borrow_mut(|w| w.as_mut().map(|waiting| waiting()).is_some()) { + continue; + } + std::thread::sleep(LOCK_PAUSE); + } +} + +#[cfg(test)] +thread_local! { + /// Tests: runs on this thread in place of each wait of [`lock_store`] for a lock that is held. + pub(crate) static WHILE_GRANTS_LOCKED: std::cell::RefCell>> = const { std::cell::RefCell::new(None) }; +} + /// The browser has no folders to keep anything in. #[cfg(target_arch = "wasm32")] fn lock_store(_: &Path) -> std::io::Result { diff --git a/crates/engine/src/tests/script_io.rs b/crates/engine/src/tests/script_io.rs index 1943a11bab..7b5db047ef 100644 --- a/crates/engine/src/tests/script_io.rs +++ b/crates/engine/src/tests/script_io.rs @@ -613,6 +613,42 @@ fn a_grants_change_without_its_lock_changes_nothing() { let _ = std::fs::remove_dir_all(base); } +/// Reading and changing the grants file wait for a lock another handle holds only for a bounded +/// number of tries: then a read gives no grants and a change fails with the file unchanged. A lock +/// released while it waits is taken. +#[test] +fn a_grants_change_waits_for_a_held_lock_a_bounded_number_of_tries() { + use crate::script::files::{LOCK_TRIES, WHILE_GRANTS_LOCKED, revoke_grants, stored_grants}; + let base = folder("grants-lock-held"); + let data = base.join("settings/Script Data"); + let grant = json!({"script": "/s.jsx", "sha256": "0", "code": [], "path": "/p", "write": false, "folder": false}); + let text = json!({"version": 1, "grants": [grant]}).to_string(); + write(&base.join("settings/Script Grants.json"), text.as_bytes()); + let held = std::fs::File::options().create(true).truncate(false).read(true).write(true).open(base.join("settings/Script Grants.lock")).unwrap(); + held.lock().unwrap(); + let waits = std::rc::Rc::new(std::cell::Cell::new(0)); + let counted = waits.clone(); + WHILE_GRANTS_LOCKED.set(Some(Box::new(move || counted.set(counted.get() + 1)))); + assert_eq!(stored_grants(&data), Vec::::new(), "grants are not read without the lock"); + assert_eq!(waits.get(), LOCK_TRIES - 1); + waits.set(0); + let refused = revoke_grants(&data, None, None); + assert_eq!(refused.map_err(|e| e.kind()), Err(std::io::ErrorKind::TimedOut)); + assert_eq!(waits.get(), LOCK_TRIES - 1, "it waits between tries and gives up after the last"); + assert_eq!(std::fs::read_to_string(base.join("settings/Script Grants.json")).unwrap(), text); + let mut released = Some(held); + let counted = waits.clone(); + waits.set(0); + WHILE_GRANTS_LOCKED.set(Some(Box::new(move || { + counted.set(counted.get() + 1); + drop(released.take()); + }))); + assert_eq!(revoke_grants(&data, None, None).unwrap(), 1, "a lock released while it waits is taken"); + assert_eq!(waits.get(), 1); + WHILE_GRANTS_LOCKED.set(None); + let _ = std::fs::remove_dir_all(base); +} + /// `rename` of a file an earlier run wrote names both its old and its new path in `written`. #[test] fn a_renamed_file_names_its_old_and_new_paths_in_written() { From 82620a1b27aaed84b3f01fcb9c341274eb995034 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 12:58:51 -0800 Subject: [PATCH 037/176] Scripts: copy and length reach files open for reading A file opened with open('r') kept its old bytes after copy wrote over it or length changed it, while an object open for writing took the new bytes. Both now update every object that holds the file. An object that holds a renamed file is found at the new path, and an object whose file was removed is not taken for a file made later at its path. --- crates/engine/src/script/files.rs | 34 +++++++++++++++++++--------- crates/engine/src/tests/script_io.rs | 29 ++++++++++++++++++++++++ 2 files changed, 52 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index 0e863fa03d..559b660d08 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -1448,6 +1448,9 @@ struct Open { /// The run may no longer read the file the object holds: `read`, `readln`, `readch` and `seek` /// give [`ACCESS_DENIED`], and `eof` is true. unreadable: bool, + /// The file the object holds was removed, so a file made later at its path is not the one it + /// holds. + removed: bool, } impl Open { @@ -1477,9 +1480,19 @@ impl Open { dirty: false, withdrawn: false, unreadable: false, + removed: false, }) } + /// Does the object hold the bytes of the file at the real path `real`: the file it writes to, or, + /// when it writes to none, the file it was opened on while that file was not removed? + fn holds(&self, real: &Path) -> bool { + match self.target.as_deref() { + Some(t) => t == real, + None => !self.removed && self.read_from.as_deref() == Some(real), + } + } + /// Writes `text` at the position, over what is there and past the end, when it takes at most /// `left` bytes; → the bytes written. fn write(&mut self, text: &str, left: usize) -> Result { @@ -1797,7 +1810,7 @@ fn copy(host: &Host, a: &[Data]) -> Result { }; // The target's open objects each take a copy of the bytes, which count as written too, as does // the copy itself when it is written. - let holders = disk.open.values().filter(|o| o.target.as_deref() == Some(target.as_path())).count(); + let holders = disk.open.values().filter(|o| o.holds(&target)).count(); disk.charge_write(copied.len().saturating_mul(holders.saturating_add(usize::from(!itself))))?; // The copy takes the source's permissions, as `std::fs::copy` gives them. let permissions = std::fs::metadata(&source).map(|m| m.permissions()); @@ -1806,9 +1819,10 @@ fn copy(host: &Host, a: &[Data]) -> Result { if !itself && (r.is_ok() || target.exists()) { disk.wrote(&target); } - // Open objects of the target hold the copy, so closing them does not write their older bytes. + // Open objects of the target hold the copy, so those opened for reading read it and closing the + // others does not write their older bytes. if r.is_ok() { - for file in disk.open.values_mut().filter(|o| o.target.as_deref() == Some(target.as_path())) { + for file in disk.open.values_mut().filter(|o| o.holds(&target)) { file.bytes.clone_from(&copied); file.pos = file.pos.min(copied.len()); file.dirty = false; @@ -1843,10 +1857,12 @@ fn remove(host: &Host, a: &[Data]) -> Result { }; if r.is_ok() { // Other open objects of the file drop their changes and take no more writes, so neither - // their close nor the run's end makes the file again. - for file in disk.open.values_mut().filter(|o| o.target.as_deref() == Some(target.as_path())) { + // their close nor the run's end makes the file again, and no object holds a file made later + // at its path. + for file in disk.open.values_mut().filter(|o| o.holds(&target)) { file.dirty = false; file.target = None; + file.removed = true; } disk.wrote(&target); } @@ -1952,11 +1968,7 @@ fn set_length(host: &Host, a: &[Data]) -> Result { Ok(m) => { // Each open object of the file holds its own bytes, so what each one grows by counts too. let len = usize::try_from(n).unwrap_or(usize::MAX); - let held = disk - .open - .values() - .filter(|o| o.target.as_deref() == Some(target.as_path())) - .fold(0usize, |sum, o| sum.saturating_add(len.saturating_sub(o.bytes.len()))); + let held = disk.open.values().filter(|o| o.holds(&target)).fold(0usize, |sum, o| sum.saturating_add(len.saturating_sub(o.bytes.len()))); disk.charge_write(usize::try_from(n.saturating_sub(m.len())).unwrap_or(usize::MAX).saturating_add(held))?; // The file's open objects write what they hold first, and then hold the new length. let ids: Vec = disk.open.iter().filter(|(_, o)| o.target.as_deref() == Some(target.as_path())).map(|(id, _)| *id).collect(); @@ -1967,7 +1979,7 @@ fn set_length(host: &Host, a: &[Data]) -> Result { }; if r.is_ok() { let len = usize::try_from(n).unwrap_or(usize::MAX); - for file in disk.open.values_mut().filter(|o| o.target.as_deref() == Some(target.as_path())) { + for file in disk.open.values_mut().filter(|o| o.holds(&target)) { file.bytes.resize(len, 0); file.pos = file.pos.min(len); } diff --git a/crates/engine/src/tests/script_io.rs b/crates/engine/src/tests/script_io.rs index 7b5db047ef..62f031528b 100644 --- a/crates/engine/src/tests/script_io.rs +++ b/crates/engine/src/tests/script_io.rs @@ -889,6 +889,35 @@ fn script_file_copy_of_an_open_file_has_its_changes() { let _ = std::fs::remove_dir_all(base); } +/// An object that has a file open for reading holds what `copy` writes over the file and the length +/// `length` sets, as an object open for writing does, also after the file is renamed, and not after +/// it is removed. +#[test] +fn script_file_open_for_reading_holds_a_copy_and_a_new_length() { + let base = folder("copyreader"); + let r = run( + &base, + "var d = Folder.temp.fsName, s = new File(d + '/s.txt'); s.open('w'); s.write('copied'); s.close();\n\ + var t = new File(d + '/t.txt'); t.open('w'); t.write('old'); t.close(); t.open('r');\n\ + var out = [s.copy(t.fsName), t.read()]; t.close();\n\ + var u = new File(d + '/u.txt'); u.open('w'); u.write('abcdef'); u.close(); u.open('r');\n\ + new File(u.fsName).length = 2; out.push(u.read()); u.close(); vc.log(out);", + ); + assert_eq!(r["log"], json!([[true, "copied", "ab"]])); + // A renamed file is held at its new path; a removed one is not held by a file made at its path. + let r = run( + &base, + "var d = Folder.temp.fsName, s = new File(d + '/s.txt'); s.open('w'); s.write('copied'); s.close();\n\ + var v = new File(d + '/v.txt'); v.open('w'); v.write('old'); v.close(); v.open('r');\n\ + var w = new File(d + '/v.txt'); var out = [w.rename('w.txt'), s.copy(d + '/v.txt'), v.read()];\n\ + v.seek(0); out.push(s.copy(w.fsName), v.read()); v.close();\n\ + var x = new File(d + '/x.txt'); x.open('w'); x.write('kept'); x.close(); x.open('r');\n\ + out.push(new File(x.fsName).remove(), s.copy(d + '/x.txt'), x.read()); x.close(); vc.log(out);", + ); + assert_eq!(r["log"], json!([[true, true, "old", true, "copied", true, true, "kept"]])); + let _ = std::fs::remove_dir_all(base); +} + /// A file whose `close` could not write it stays open, so a later `close` writes it. #[test] fn script_file_close_that_fails_can_be_tried_again() { From df95a67ea7879bab3dacf0347883d8976e80c556 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 14:10:16 -0800 Subject: [PATCH 038/176] Tools: tool.setOption reads and sets the tool that lent the Selection tool When a held Cmd press lends the Selection tool, `tool.setOption` that names the waiting tool (the Shape Builder) reads its options from that tool instead of making it again from the saved preferences, and a value set on it counts as set since the tool last started afresh. Params that are not an object now give the error the other commands give, "the params must be an object, not {got}", which the message catalogs already translate. The params text of tool.setOption in the MCP catalog, the desktop commands and the headless host says so. --- crates/engine/src/tests/build.rs | 16 ++++++++--- crates/engine/src/tests/toolsettings.rs | 5 ++++ crates/engine/src/tooling.rs | 28 ++++++++++++++----- crates/mcp/src/headless.rs | 2 +- crates/mcp/src/tests/liquify.rs | 15 +++++++++++ crates/mcp/src/ui_catalog.rs | 2 +- crates/tools/src/option_check.rs | 36 ++++++++++++++++++++++--- crates/ui-egui/src/menus/ui_commands.rs | 2 +- docs/control-protocol.md | 5 ++-- docs/mcp.md | 8 +++--- 10 files changed, 96 insertions(+), 23 deletions(-) diff --git a/crates/engine/src/tests/build.rs b/crates/engine/src/tests/build.rs index 545551f13f..cca6de810f 100644 --- a/crates/engine/src/tests/build.rs +++ b/crates/engine/src/tests/build.rs @@ -1049,9 +1049,9 @@ fn shape_builder_drops_a_press_held_during_a_merge() { } } -/// `tool.setOption` without a tool, while a Cmd press is held during a merge, sets the Shape -/// Builder's option: finishing the merge makes the press, which lends the selection tool, and the -/// value still goes to the Shape Builder it was checked against. +/// When `tool.setOption` names no tool, the option is set on the tool that was active when the +/// call arrived (the Shape Builder), even when finishing its merge replays a held Cmd press that +/// switches to the Selection tool. #[test] fn shape_builder_option_set_while_a_cmd_press_is_held_goes_to_the_shape_builder() { let v = ViewInfo::default(); @@ -1067,6 +1067,16 @@ fn shape_builder_option_set_while_a_cmd_press_is_held_goes_to_the_shape_builder( assert_eq!(s.lender.as_ref().map(|t| t.id()), Some("shapeBuilder")); assert_eq!(out["pickColorFrom"], json!("artwork")); assert_eq!(s.lender.as_ref().map(|t| t.options()["pickColorFrom"].clone()), Some(json!("artwork"))); + // Named while it waits, the Shape Builder is read where it waits, not made afresh from the + // preferences. + s.lender.as_mut().unwrap().set_option("pickColorFrom", &json!("swatches")); + let read = s.set_tool_option_cmd(&json!({"tool": "shapeBuilder"})).unwrap(); + assert_eq!(read["pickColorFrom"], json!("swatches"), "read from the waiting tool"); + // A value set on it counts as set on the tool chosen. + s.tool_set_since_reset = false; + s.set_tool_option_cmd(&json!({"tool": "shapeBuilder", "key": "highlightFill", "value": false})).unwrap(); + assert!(s.tool_set_since_reset(), "the tool chosen was set"); + assert_eq!(s.lender.as_ref().map(|t| t.options()["highlightFill"].clone()), Some(json!(false))); } /// A new revision of the document made outside a command while a merge is computed on another diff --git a/crates/engine/src/tests/toolsettings.rs b/crates/engine/src/tests/toolsettings.rs index eae2a16aa4..a893244021 100644 --- a/crates/engine/src/tests/toolsettings.rs +++ b/crates/engine/src/tests/toolsettings.rs @@ -370,6 +370,11 @@ fn an_empty_set_option_reads_and_saves_nothing() { let saved = s.prefs.tool_settings.clone(); assert_eq!(s.set_tool_option_cmd(&json!({})).unwrap(), s.tool_options()); assert_eq!(s.set_tool_option_cmd(&json!({"tool": "flare"})).unwrap(), s.tool_options_of("flare")); + // No params (null) read too; params that are not an object are an error. + assert_eq!(s.set_tool_option_cmd(&serde_json::Value::Null).unwrap(), s.tool_options()); + for (bad, got) in [(json!(true), "true"), (json!([]), "[]")] { + assert_eq!(s.set_tool_option_cmd(&bad).unwrap_err(), format!("the params must be an object, not {got}")); + } assert_eq!(s.prefs.tool_settings, saved); } diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index fcbaf664d0..eeb1383c3c 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -1260,7 +1260,14 @@ impl Session { /// The options of tool `id`: the active tool's, or those it would have if chosen now. pub fn tool_options_of(&self, id: &str) -> Value { - if id == self.tool.id() { self.tool.options() } else { self.make_tool(id).options() } + if id == self.tool.id() { + self.tool.options() + } else if let Some(lender) = self.lender.as_deref().filter(|l| l.id() == id) { + // The tool that lent a selection tool for a Cmd-drag holds its options while it waits. + lender.options() + } else { + self.make_tool(id).options() + } } /// Set options of tool `id` (default: the active tool). Another tool's persistent options are @@ -1272,7 +1279,10 @@ impl Session { self.note_place_queue_roots(); } let active = id.is_none_or(|id| id == self.tool.id()); - self.tool_set_since_reset |= active; + // The tool that lent a selection tool for a Cmd-drag is the tool chosen, and active again + // when the drag ends. + let lender = id.is_some_and(|id| self.lender.as_deref().is_some_and(|l| l.id() == id)); + self.tool_set_since_reset |= active || lender; // The Place queue and a parametric shape's kind are set first: setting the queue starts // again at its first file, and a `current` given with it is an index into it; setting the // kind puts the shape's other numbers back to that kind's, and those given with it are its. @@ -1284,7 +1294,7 @@ impl Session { t.set_option(k, v); } Self::store_tool_settings(&mut self.prefs, t); - let out = t.options(); + let mut out = t.options(); if let Some(other) = other { // The tool that lent a selection tool for a Cmd-drag is kept aside, not made again when // it is back: when it is the tool set, it takes the writes too (the Rounded Rectangle's @@ -1297,6 +1307,9 @@ impl Session { } } Self::restore_tool_settings(&self.prefs, lender); + if lender.id() == other.id() { + out = lender.options(); + } } // Only the stores it shares with the tool set: the active tool's own options stay as they // are, also in the middle of a drag that Escape can cancel. @@ -1308,10 +1321,11 @@ impl Session { /// `tool.setOption {tool?, key?, value?, values?}` (a command of the desktop app and of the /// headless host): set one option (`key`, `value`) or several (`values`) of `tool` (default: - /// the active tool) → its options. With no option given, the options are read and nothing is - /// set. Every option given is checked first ([`vectorcraft_tools::Tool::check_option`]): an - /// unknown option, a value of the wrong type or a number out of range is an error that sets - /// none of them. + /// the tool active when the call arrives, named before the edit in progress is finished) → its + /// options. With no option given, the options are read and nothing is set. Parameters that are + /// not an object are an error; none (null) read the options. Every option given is checked + /// first ([`vectorcraft_tools::Tool::check_option`]): an unknown option, a value of the wrong + /// type or a number out of range is an error that sets none of them. pub fn set_tool_option_cmd(&mut self, p: &Value) -> std::result::Result { let (tool, values) = vectorcraft_tools::option_check::set_option_params(p)?; if let Some(t) = tool diff --git a/crates/mcp/src/headless.rs b/crates/mcp/src/headless.rs index 69c7b5ba0e..cd08ece378 100644 --- a/crates/mcp/src/headless.rs +++ b/crates/mcp/src/headless.rs @@ -48,7 +48,7 @@ const HOST_COMMANDS: &[(&str, &str, &str)] = &[ ( "tool.setOption", "Tool Option", - "{key?, value? | values?: {key: value…}, tool?: id (default: the active tool)} → the tool's options (`{}` reads them); kept options last across tool switches", + "{key?, value? | values?: {key: value…}, tool?: id (default: the active tool)} → the tool's options (`{}` or no params reads them; params that are not an object are an error); kept options last across tool switches", ), ]; diff --git a/crates/mcp/src/tests/liquify.rs b/crates/mcp/src/tests/liquify.rs index c6d3862384..793f16efee 100644 --- a/crates/mcp/src/tests/liquify.rs +++ b/crates/mcp/src/tests/liquify.rs @@ -43,6 +43,21 @@ fn a_refused_option_value_is_an_error_result() { assert_eq!(command(&mut h, "tool.setOption", json!({})), before); } +/// `tool.setOption` with params that are not an object is an error result that sets nothing; +/// without params it reads the options, as `{}` does. +#[test] +fn set_option_params_that_are_not_an_object_are_an_error_result() { + let mut h = Headless::with_document(); + command(&mut h, "tool.select", json!({"tool": "warp"})); + let before = command(&mut h, "tool.setOption", json!({})); + for params in [json!(true), json!(7), json!([]), json!("x")] { + let r = call_tool(&mut h, "run_command", &json!({"command": "tool.setOption", "params": params})); + assert!(r.is_error, "{params}: {r:?}"); + } + assert_eq!(ok(&mut h, "run_command", json!({"command": "tool.setOption"})), before); + assert_eq!(command(&mut h, "tool.setOption", json!({})), before); +} + #[test] fn pointer_gestures_carry_pen_pressure() { let bloat = |pressure: f64| { diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 7783f72f1f..7f54d48a82 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -775,7 +775,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "tool.setOption", "Tool Option", "", - "{key, value} | {values: {key: value…}}, tool?: id (default: the active tool) → the tool's options (`{}` reads them). The options a tool keeps (Liquify brush and tool options, Mirror & Cut, Puppet Warp, drawing tools…) last across tool switches and are saved with the preferences; another tool's are stored for when it is chosen. Every option is checked before any is set: an option the tool doesn't have, a value of the wrong type, a number out of the tool's range or an unknown choice is an error naming the tool and the option, and nothing changes. The Live Paint tools' width and the Shape Builder's gapLength are set to the nearest end of their range instead", + "{key, value} | {values: {key: value…}}, tool?: id (default: the active tool) → the tool's options (`{}` or no params reads them; params that are not an object are an error). The options a tool keeps (Liquify brush and tool options, Mirror & Cut, Puppet Warp, drawing tools…) last across tool switches and are saved with the preferences; another tool's are stored for when it is chosen. Every option is checked before any is set: an option the tool doesn't have, a value of the wrong type, a number out of the tool's range or an unknown choice is an error naming the tool and the option, and nothing changes. The Live Paint tools' width and the Shape Builder's gapLength are set to the nearest end of their range instead", ), ( "tool.toggleTouchMode", diff --git a/crates/tools/src/option_check.rs b/crates/tools/src/option_check.rs index 9a45caeb13..8507a82184 100644 --- a/crates/tools/src/option_check.rs +++ b/crates/tools/src/option_check.rs @@ -69,7 +69,7 @@ pub fn string_or_null(key: &str, v: &Value) -> Result<(), String> { /// `values`, or with no parameters (null), the options are empty: the command reads them. pub fn set_option_params(p: &Value) -> Result<(Option<&str>, Map), String> { if !p.is_object() && !p.is_null() { - return Err("the parameters must be an object".into()); + return Err(format!("the params must be an object, not {}", shown(p))); } let tool = match p.get("tool") { None => None, @@ -94,6 +94,32 @@ pub fn set_option_params(p: &Value) -> Result<(Option<&str>, Map) Ok((tool, values)) } +/// The JSON text of `v` as a parameter error shows it: cut to 40 characters, with `…` when it was +/// longer. The text is written only up to the cut. +fn shown(v: &Value) -> String { + struct Cut { + text: String, + left: usize, + } + impl std::fmt::Write for Cut { + fn write_str(&mut self, s: &str) -> std::fmt::Result { + for c in s.chars() { + if self.left == 0 { + return Err(std::fmt::Error); + } + self.left -= 1; + self.text.push(c); + } + Ok(()) + } + } + let mut out = Cut { text: String::new(), left: 40 }; + if std::fmt::Write::write_fmt(&mut out, format_args!("{v}")).is_err() { + out.text.push('…'); + } + out.text +} + /// Check every one of `values` as an option of `tool` ([`Tool::check_options`]), before any is /// set: the first one the tool doesn't take is an error that names the tool. pub fn check_values(tool: &dyn Tool, values: &Map) -> Result<(), String> { @@ -145,9 +171,13 @@ mod tests { // Omitted parameters arrive as null: a read, like `{}`. let (tool, values) = set_option_params(&Value::Null).unwrap(); assert!(tool.is_none() && values.is_empty()); - for bad in [json!(true), json!(7), json!([]), json!("x")] { - assert_eq!(set_option_params(&bad).err(), Some("the parameters must be an object".into()), "{bad}"); + for (bad, got) in [(json!(true), "true"), (json!(7), "7"), (json!([]), "[]"), (json!("x"), "\"x\"")] { + assert_eq!(set_option_params(&bad).err(), Some(format!("the params must be an object, not {got}")), "{bad}"); } + // A long value is shown cut, as the other parameter errors show it. + let long = json!("a".repeat(100)); + let shown = format!("\"{}…", "a".repeat(39)); + assert_eq!(set_option_params(&long).err(), Some(format!("the params must be an object, not {shown}"))); assert_eq!(set_option_params(&json!({"tool": 3})).err(), Some("`tool` must be a tool id".into())); assert_eq!(set_option_params(&json!({"values": [1]})).err(), Some("`values` must be an object".into())); assert_eq!(set_option_params(&json!({"key": 3, "value": 1})).err(), Some("`key` must be a string".into())); diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 582bc77802..c419237a13 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -776,7 +776,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "tool.setOption", "Tool Option", "", - "{key, value} | {values: {key: value…}}, tool?: id (default: the active tool) → the tool's options (`{}` reads them). The options a tool keeps (Liquify brush and tool options, Mirror & Cut, Puppet Warp, drawing tools…) last across tool switches and are saved with the preferences; another tool's are stored for when it is chosen. Every option is checked before any is set: an option the tool doesn't have, a value of the wrong type, a number out of the tool's range or an unknown choice is an error naming the tool and the option, and nothing changes. The Live Paint tools' width and the Shape Builder's gapLength are set to the nearest end of their range instead", + "{key, value} | {values: {key: value…}}, tool?: id (default: the active tool) → the tool's options (`{}` or no params reads them; params that are not an object are an error). The options a tool keeps (Liquify brush and tool options, Mirror & Cut, Puppet Warp, drawing tools…) last across tool switches and are saved with the preferences; another tool's are stored for when it is chosen. Every option is checked before any is set: an option the tool doesn't have, a value of the wrong type, a number out of the tool's range or an unknown choice is an error naming the tool and the option, and nothing changes. The Live Paint tools' width and the Shape Builder's gapLength are set to the nearest end of their range instead", ), ( crate::touch::TOGGLE_MODE, diff --git a/docs/control-protocol.md b/docs/control-protocol.md index edd0d8f96f..0d78baca0a 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -922,9 +922,8 @@ Tool options last: `tool.setOption {key, value}` or `{values: {…}}` (and `tool the options a tool keeps (Liquify brush and tool options, Mirror & Cut, Puppet Warp, Symbolism, drawing tools) stay when you switch tools or documents and are saved with the preferences. The Liquify tools share their Global Brush Dimensions (`width`, `height`, `angle`, `intensity`). `{}` reads the options and sets nothing; parameters that are -not an object are an error. Every option given is -checked before any is set: an option the tool doesn't have, a value of the wrong type, a number outside the tool's -range or an unknown choice is an error that names the tool and the option +not an object are an error. Every option given is checked before any is set: an option the tool doesn't have, a value +of the wrong type, a number outside the tool's range or an unknown choice is an error that names the tool and the option (``tool `smooth`: `fidelity` must be a number from 0.05 to 100``), and no option, preference or undo step changes. The Live Paint tools' `width` and the Shape Builder's `gapLength` are set to the nearest end of their range instead. diff --git a/docs/mcp.md b/docs/mcp.md index 0c46157847..7ec64a52de 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -9816,10 +9816,10 @@ to that tool), a value of the wrong type, a number outside the tool's range, an `value`, a `values` that is not an object or a `tool` that is not a tool id is an error result that names the tool and the option, and nothing changes: no option, no saved preference and no undo step, also when another option given with it is good. Parameters that are not an object are an error too. `{}`, or no parameters, reads the options and sets -nothing. The ranges are VectorCraft's own (for example the Smooth tool's -`fidelity` takes 0.05 to 100, the Pencil's 0.01 to 100); a refused value in a Tool Options dialog keeps the dialog -open. The Live Paint tools' `width` and the Shape Builder's `gapLength` are set to the nearest end of their range -when a number outside it is given, as their sections above say. +nothing. The ranges are VectorCraft's own (for example the Smooth tool's `fidelity` takes 0.05 to 100, the Pencil's +0.01 to 100); a refused value in a Tool Options dialog keeps the dialog open. The Live Paint tools' `width` and the +Shape Builder's `gapLength` are set to the nearest end of their range when a number outside it is given, as their +sections above say. ```json {"name":"run_command","arguments":{"command":"tool.setOption","params":{"tool":"twirl","values":{"width":60,"rate":90}}}} From 9971b39c6dc37fa2e7122502420ee15cbe6b6ede Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 14:50:47 -0800 Subject: [PATCH 039/176] i18n: Danish rows for script file messages Adds Danish rows for the script File and Folder messages, now that Danish is a complete-message language, and removes the two Danish rows for messages the scripts no longer give. --- crates/ui-egui/src/i18n/da.tsv | 23 +++++++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 80fb5d9ab8..b3c1a1a86e 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -75,14 +75,33 @@ @msg Script file could not be read Scriptfilen kunne ikke læses @msg Script folder has more than 2,048 entries Scriptmappen har mere end 2.048 elementer @msg Script file open mode must be r, w, e or a Scriptfilens åbningstilstand skal være r, w, e eller a -@msg Script file writing is not available Skrivning af scriptfiler er ikke tilgængelig -@msg Script file dialogs are not available Scriptfildialoger er ikke tilgængelige @msg Script files cannot be opened in another application Scriptfiler kan ikke åbnes i et andet program @msg Script file access is unavailable on the web Scriptets filadgang er ikke tilgængelig på nettet @msg Script has 256 files open Scriptet har 256 filer åbne @msg Script file path exceeds 32,767 characters Scriptfilens sti er længere end 32.767 tegn @msg Script folder mask takes too many steps to match Scriptmappens maske kræver for mange trin at matche @msg the script opened more file data than one run may open (32 MiB) scriptet åbnede flere fildata, end én kørsel må åbne (32 MiB) +@msg Script file access denied: {path} Scriptets filadgang blev nægtet: {path} +@msg Script file access to the app's own folders is not allowed Scripts må ikke få adgang til programmets egne mapper +@msg Script file cannot encode the text Scriptfilen kan ikke kode teksten +@msg Script file could not be written Scriptfilen kunne ikke skrives +@msg Script file dialogs need a person to answer them Scriptets fildialoger skal besvares af en person +@msg Script file is not open for writing Scriptfilen er ikke åben for skrivning +@msg Script file name is already in use Scriptfilens navn er allerede i brug +@msg Script file name must be a name without a folder Scriptfilens navn skal være et navn uden en mappe +@msg Script file permission can be kept only for a script run from a file Filtilladelsen kan kun beholdes for et script, der køres fra en fil +@msg Script file permission could not be saved Scriptets filtilladelse kunne ikke gemmes +@msg Script folder is not empty Scriptmappen er ikke tom +@msg Script files cannot make aliases Scriptfiler kan ikke oprette aliasser +@msg Script file hidden setting cannot be changed Scriptfilens indstilling for skjult kan ikke ændres +@msg {name}: a file dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name}: en fildialog kan ikke åbnes i et callback fra en indbygget funktion, en getter, en konvertering eller en fil, som $.evalFile kører; kald den fra scriptets egen kode +@msg the script wrote more file data than one run may write (32 MiB) scriptet skrev flere fildata, end én kørsel må skrive (32 MiB) +@msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` for et scripts fildialog skal være en af: once, always, deny, stop +@msg choose a file or folder first, or deny vælg først en fil eller mappe, eller afvis +@msg the script file permissions could not be saved: {e} scriptets filtilladelser kunne ikke gemmes: {e} +@msg this script's file access can be allowed only once dette scripts filadgang kan kun tillades én gang +@msg Only the person at the keyboard can allow a script's file access Kun personen ved tastaturet kan tillade et scripts filadgang +@msg A script is given at most 2,048 files: the files picked after them were left out Et script får højst 2.048 filer: de filer, der blev valgt derefter, blev udeladt @msg File.seek: takes a position and a mode File.seek: tager en position og en tilstand @msg vc.run: give a command id, as a string vc.run: angiv et kommando-id som en streng @msg vc.run: takes a command id and an object of parameters vc.run: tager et kommando-id og et objekt med parametre From b173bd7b4048679a3fed38a0ecf103754342f29f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 13:45:16 -0800 Subject: [PATCH 040/176] Scripts: a folder renamed under another case of its name moves its open files `rename` matched open File objects by the path as given, while the objects hold the names the file system keeps. Where case does not matter, a folder named in another case was renamed but its open files kept the old path, so their changes could not be written and they stayed under the old path's rules for reading. The objects are now matched by the kept name, and a rename whose kept name cannot be learned is refused. --- crates/engine/src/script/files.rs | 14 +++++++++++++- crates/engine/src/tests/script_io.rs | 22 ++++++++++++++++++++++ 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index 559b660d08..7f4052dfb8 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -1895,13 +1895,25 @@ fn rename(host: &Host, a: &[Data]) -> Result { { return Ok(error(NAME_TAKEN)); } + // Open objects hold real paths with the names the file system keeps, and `from` keeps the last + // name as given, which where case does not matter can differ in case: they are matched by the + // kept name. A link is renamed itself, and no object holds a path through it. When the kept + // name cannot be learned, nothing is renamed, so no object goes on under the old path's rules. + let kept = if was.file_type().is_symlink() { + from.clone() + } else { + match std::fs::canonicalize(&from) { + Ok(kept) => kept, + Err(_) => return Ok(error(WRITE_FAILED)), + } + }; if std::fs::rename(&from, &to).is_err() { return Ok(error(WRITE_FAILED)); } // Open objects of the file, or of files in the folder, write to the new path, and the rules for // reading apply to them there. let moved = |p: &mut Option| { - if let Some(rest) = p.as_deref().and_then(|t| t.strip_prefix(&from).ok()) { + if let Some(rest) = p.as_deref().and_then(|t| t.strip_prefix(&kept).ok()) { *p = Some(if rest.as_os_str().is_empty() { to.clone() } else { to.join(rest) }); } }; diff --git a/crates/engine/src/tests/script_io.rs b/crates/engine/src/tests/script_io.rs index 62f031528b..9fc69e080f 100644 --- a/crates/engine/src/tests/script_io.rs +++ b/crates/engine/src/tests/script_io.rs @@ -1192,6 +1192,28 @@ fn script_file_rename_does_not_move_the_settings_folder_named_in_another_case() let _ = std::fs::remove_dir_all(base); } +/// Where case does not matter, a folder renamed under its name in another case still moves the open +/// objects of the files in it: changes are written under the new name, not lost at the old one. +#[cfg(any(windows, target_os = "macos"))] +#[test] +fn script_file_rename_of_a_folder_named_in_another_case_moves_its_open_files() { + let base = folder("renamecase"); + let mut s = with_data(&base); + let r = run_in( + &mut s, + &base, + "var d = Folder.userData.fsName; new Folder(d + '/sub').create();\n\ + var f = new File(d + '/sub/f.txt'); f.open('w'); f.write('kept');\n\ + var out = [new Folder(d + '/SUB').rename('moved'), f.close(), f.error]; vc.log(out); vc.log(d);", + ) + .unwrap(); + let d = PathBuf::from(r["log"][1].as_str().unwrap()); + assert_eq!(r["log"][0], json!([true, true, ""])); + assert_eq!(std::fs::read(d.join("moved/f.txt")).unwrap(), b"kept"); + assert!(!d.join("sub").exists()); + let _ = std::fs::remove_dir_all(base); +} + /// Where case matters, a rename to a name that differs in case alone does not replace the other file. #[cfg(target_os = "linux")] #[test] From fd2baa04225c214e911dc26f2e3e0c76615a1da9 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 14:51:22 -0800 Subject: [PATCH 041/176] Tests: the data folder write test expects Windows line ends and paths on Windows `writeln` uses CRLF by default on Windows, and the script reports paths without the `\?\` prefix that canonicalize adds there. The test expected LF and compared with the prefixed path, so it failed on Windows. It now expects the platform's default line end and compares plain paths. --- crates/engine/src/tests/script_io.rs | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/tests/script_io.rs b/crates/engine/src/tests/script_io.rs index 9fc69e080f..6637d3fe8d 100644 --- a/crates/engine/src/tests/script_io.rs +++ b/crates/engine/src/tests/script_io.rs @@ -500,16 +500,18 @@ fn script_files_write_in_the_temporary_and_data_folders() { vc.log(out); vc.log(u.fsName); vc.log(Folder.temp.fsName);", ) .unwrap(); - assert_eq!(r["log"][0], json!([true, true, true, true, true, true, true, "a1trueb\nc\r\n", true, true, true, 4, true, true])); + // The first `writeln` uses the default line end, which is the platform's. + let text = if cfg!(windows) { "a1trueb\r\nc\r\n" } else { "a1trueb\nc\r\n" }; + assert_eq!(r["log"][0], json!([true, true, true, true, true, true, true, text, true, true, true, 4, true, true])); let notes = PathBuf::from(r["log"][1].as_str().unwrap()); let temp = PathBuf::from(r["log"][2].as_str().unwrap()); - assert_eq!(std::fs::read(¬es).unwrap(), b"a1trueb\nc\r\n"); - assert!(notes.starts_with(std::fs::canonicalize(base.join("settings/Script Data")).unwrap()), "{notes:?}"); + assert_eq!(std::fs::read(¬es).unwrap(), text.as_bytes()); + assert!(notes.starts_with(crate::cmd::findfiles::plain(std::fs::canonicalize(base.join("settings/Script Data")).unwrap())), "{notes:?}"); assert!(!temp.exists(), "the run's temporary folder is deleted when it ends"); let written: Vec<&str> = r["written"].as_array().unwrap().iter().filter_map(Value::as_str).collect(); assert!(written.contains(¬es.to_string_lossy().as_ref()), "{written:?}"); let again = run_in(&mut s, &base, "var u = new File(Folder.userData.fsName + '/notes.txt'); u.open('r'); vc.log(u.read());").unwrap(); - assert_eq!(again["log"], json!(["a1trueb\nc\r\n"]), "a script's data folder is kept between runs"); + assert_eq!(again["log"], json!([text]), "a script's data folder is kept between runs"); let _ = std::fs::remove_dir_all(base); } From 8620f0611cfb02ea1e5ef7a7522c4dcf939ce8fb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 15:37:25 -0800 Subject: [PATCH 042/176] Scripts: a file whose write fails after it was emptied is named as written Writing an open file's bytes empties the file first. When the write then failed, for example on a full disk, the file had lost its old bytes but was left out of the files the run names as written. It is now named as soon as it has been opened for the write. --- crates/engine/src/script/files.rs | 16 ++++++++++++---- crates/engine/src/tests/script_io.rs | 17 +++++++++++++++++ 2 files changed, 29 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index 7f4052dfb8..05f148e714 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -762,11 +762,17 @@ impl Disk { if moved || std::fs::symlink_metadata(&real).is_ok_and(|m| m.file_type().is_symlink()) { return Err(ACCESS_DENIED); } - // The file stays changed until its bytes are written, so the run's end tries it again. - std::fs::write(&real, &file.bytes).map_err(|_| WRITE_FAILED)?; - file.dirty = false; + // The file stays changed until its bytes are written, so the run's end tries it again. Once + // it is opened its old bytes are gone, so a write that then fails names it in the report too. + let mut out = std::fs::File::create(&real).map_err(|_| WRITE_FAILED)?; + let written = std::io::Write::write_all(&mut out, &file.bytes).is_ok(); + #[cfg(test)] + let written = written && !FLUSH_WRITE_FAILS.with(std::cell::Cell::get); + if written { + file.dirty = false; + } self.wrote(&real); - Ok(()) + if written { Ok(()) } else { Err(WRITE_FAILED) } } /// Writes every open file that has changed: at the end of the run. → the files that could not @@ -2357,6 +2363,8 @@ pub(crate) type CopyHook = Box; #[cfg(test)] thread_local! { pub(crate) static BEFORE_COPY_READ: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; + /// Tests: while set, the bytes `flush` writes fail after the file was opened for them. + pub(crate) static FLUSH_WRITE_FAILS: std::cell::Cell = const { std::cell::Cell::new(false) }; } #[cfg(test)] diff --git a/crates/engine/src/tests/script_io.rs b/crates/engine/src/tests/script_io.rs index 6637d3fe8d..eca6dd5638 100644 --- a/crates/engine/src/tests/script_io.rs +++ b/crates/engine/src/tests/script_io.rs @@ -515,6 +515,23 @@ fn script_files_write_in_the_temporary_and_data_folders() { let _ = std::fs::remove_dir_all(base); } +/// A file whose bytes fail to be written after it was opened for them has lost its old bytes, so the +/// failed run names it among the files that stay written. +#[test] +fn script_file_whose_write_fails_partway_is_named_as_written() { + let base = folder("flushfails"); + let mut s = with_data(&base); + let r = run_in(&mut s, &base, "var f = new File(Folder.userData.fsName + '/f.txt'); f.open('w'); f.write('old'); f.close(); vc.log(f.fsName);") + .unwrap(); + let path = r["log"][0].as_str().unwrap().to_string(); + crate::script::files::FLUSH_WRITE_FAILS.with(|f| f.set(true)); + let r = run_in(&mut s, &base, "var f = new File(Folder.userData.fsName + '/f.txt'); f.open('e'); f.write('new'); f.close();"); + crate::script::files::FLUSH_WRITE_FAILS.with(|f| f.set(false)); + let e = format!("{}", r.unwrap_err()); + assert!(e.split("these files stay written:").nth(1).is_some_and(|w| w.contains(&path)), "{e}"); + let _ = std::fs::remove_dir_all(base); +} + /// `copy` reads its source under the rules for reading: a source that a link to a file outside the /// script's places replaced after it was looked up is refused, and nothing is copied. #[cfg(unix)] From b7d85212961739db08326e6dd69a94ddf660aaf4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 15:32:49 -0800 Subject: [PATCH 043/176] Window: Arrange Documents tiles the documents side by side, stacked or 2-Up to 6-Up Tile laid the open documents out in one grid only, and the application bar had no Arrange Documents button. Window > Arrange now also has Tile All Vertically (side by side in one row), Tile All Horizontally (stacked in one column) and 2-Up, 3-Up, 4-Up and 6-Up layouts, which show that many documents and leave the others under their tabs. Those layouts show the first documents in tab order, and the current document takes the last pane when it is not among them. An Arrange Documents button on the application bar, beside the workspace switcher, lists Consolidate All Windows and the Tile layouts. The item for the layout the panes show is checked. window.arrange.tile takes `layout` (grid, vertical, horizontal, 2up, 3up, 4up or 6up; grid when omitted), refuses any other value, and returns it with {tiled, panes}. ui.inspect reports tileLayout. --- crates/mcp/src/ui_catalog.rs | 2 +- crates/ui-egui/src/canvas.rs | 2 +- crates/ui-egui/src/canvas/panes.rs | 149 ++++++++++-- crates/ui-egui/src/canvas/panes/tests.rs | 282 ++++++++++++++++++++++- crates/ui-egui/src/chrome.rs | 47 +++- crates/ui-egui/src/control.rs | 7 +- crates/ui-egui/src/doc_windows/tests.rs | 4 +- crates/ui-egui/src/i18n/bg.tsv | 7 + crates/ui-egui/src/i18n/bs.tsv | 7 + crates/ui-egui/src/i18n/ca.tsv | 7 + crates/ui-egui/src/i18n/cs.tsv | 7 + crates/ui-egui/src/i18n/da.tsv | 7 + crates/ui-egui/src/i18n/de.tsv | 7 + crates/ui-egui/src/i18n/el.tsv | 7 + crates/ui-egui/src/i18n/es.tsv | 7 + crates/ui-egui/src/i18n/fi.tsv | 7 + crates/ui-egui/src/i18n/fr.tsv | 7 + crates/ui-egui/src/i18n/gu.tsv | 7 + crates/ui-egui/src/i18n/hi.tsv | 7 + crates/ui-egui/src/i18n/hu.tsv | 7 + crates/ui-egui/src/i18n/id.tsv | 7 + crates/ui-egui/src/i18n/it.tsv | 7 + crates/ui-egui/src/i18n/ja.tsv | 7 + crates/ui-egui/src/i18n/ka.tsv | 7 + crates/ui-egui/src/i18n/ko.tsv | 7 + crates/ui-egui/src/i18n/nl.tsv | 7 + crates/ui-egui/src/i18n/pl.tsv | 7 + crates/ui-egui/src/i18n/pt-br.tsv | 7 + crates/ui-egui/src/i18n/ru.tsv | 7 + crates/ui-egui/src/i18n/sv.tsv | 7 + crates/ui-egui/src/i18n/tests.rs | 11 + crates/ui-egui/src/i18n/tr.tsv | 7 + crates/ui-egui/src/i18n/uk.tsv | 7 + crates/ui-egui/src/i18n/vi.tsv | 7 + crates/ui-egui/src/i18n/zh-hans.tsv | 7 + crates/ui-egui/src/i18n/zh-hant.tsv | 7 + crates/ui-egui/src/menus.rs | 1 + crates/ui-egui/src/menus/run.rs | 2 +- crates/ui-egui/src/menus/state.rs | 2 + crates/ui-egui/src/menus/tree.rs | 35 ++- crates/ui-egui/src/menus/ui_commands.rs | 2 +- crates/ui-egui/src/state.rs | 5 + docs/mcp.md | 22 +- docs/target-app-parity.md | 1 + 44 files changed, 716 insertions(+), 54 deletions(-) diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 1bc2d14442..0429a7af31 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -768,7 +768,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "window.arrange.tile", "Tile", "", - "{} show every open document and each further view of one (window.newWindow) at once, edge to edge in the document area, one pane each in a grid (columns: the square root of the number of panes, rounded up), each fitted to its pane; the current window's pane takes the tools, a click in another pane makes its window the current one; the tabs stay; windows floating come back under the tabs first; with fewer than two windows open the view stays as it is; returns {tiled, panes}", + "{layout?: grid|vertical|horizontal|2up|3up|4up|6up} show the open documents and each further view of one (window.newWindow) at once, edge to edge in the document area, one pane each, each fitted to its pane: `grid` (the default) in a grid (columns: the square root of the number of panes, rounded up), `vertical` side by side in one row (Tile All Vertically), `horizontal` stacked in one column (Tile All Horizontally), `2up`, `3up`, `4up` and `6up` at most that many panes (2up and 3up side by side, 4up two by two, 6up three by two) with the other windows under their tabs: the first windows in tab order, the current window in the last pane when it is not among them; the current window's pane takes the tools, a click in another pane makes its window the current one; the tabs stay; windows floating come back under the tabs first; with fewer than two windows open the view and the layout stay as they are; any other `layout` is an error; returns {tiled, panes, layout}", ), ( "window.arrange.floatInWindow", diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 5c30f96246..1cc1abd5ca 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -63,7 +63,7 @@ use outline::{OVERLAY_MAX_ANCHORS, c32, node_outline, walk_drawn}; #[cfg(test)] use overlays::selected_anchor; use overlays::{HandleLook, blend_widgets_overlay, draw_inside_overlay, draw_overlays, hover_highlight, ime_geometry, selection_overlay}; -pub use panes::Panes; +pub use panes::{Layout as TileLayout, Panes}; pub(crate) use panes::{consolidate, pane, tile, tiled_area}; use raster::{changed_pixels, pixel_region, upload}; pub(crate) use raster::{color_image, color_image_owned, render_job}; diff --git a/crates/ui-egui/src/canvas/panes.rs b/crates/ui-egui/src/canvas/panes.rs index 0a26f26843..6b8eea9440 100644 --- a/crates/ui-egui/src/canvas/panes.rs +++ b/crates/ui-egui/src/canvas/panes.rs @@ -1,5 +1,6 @@ //! Window › Arrange › Tile: every open document in a pane of its own, edge to edge in the document -//! area. The current document's pane is the canvas ([`super::show`]). Each other pane draws its +//! area, in a grid, side by side or stacked; the 2-up to 6-up layouts show that many and leave the +//! rest under their tabs ([`Layout`]). The current document's pane is the canvas ([`super::show`]). Each other pane draws its //! document from a render of its own, with its artboards, guides and selected objects, and a press //! in it makes its document the current one. Each view Window › New Window opened has a pane of //! its own ([`crate::doc_windows`]). @@ -38,6 +39,9 @@ pub struct Panes { pending: HashMap, /// The panes the last frame drew, as (window, pane rect). pub(crate) last: Vec<(Win, egui::Rect)>, + /// The slots of `last`'s windows, in the same order: which windows they were, as document + /// indices shift when a document closes. + last_slots: Vec>, /// By slot: the size of the view's area its view was last fitted to in a pane, and the zoom and /// center the fit gave. fits: HashMap, @@ -49,6 +53,7 @@ impl Panes { self.shown.clear(); self.pending.clear(); self.last.clear(); + self.last_slots.clear(); self.fits.clear(); } @@ -158,37 +163,123 @@ fn render_pane( img } -/// The grid of `n` panes in `area`, filled row by row: as many columns as the square root of `n` -/// rounded up, and as many rows as those columns need. The panes meet edge to edge and cover -/// `area`; the spare cells of the last row stay empty. -pub(crate) fn cells(n: usize, area: egui::Rect) -> Vec { - if n == 0 { - return vec![]; +/// How Tile lays out the panes (`window.arrange.tile`'s `layout`). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum Layout { + /// A grid: as many columns as the square root of the number of panes rounded up. + #[default] + Grid, + /// Side by side in one row, each pane as tall as the document area. + Vertical, + /// Stacked in one column, each pane as wide as the document area. + Horizontal, + /// At most this many panes (2, 3, 4 or 6); the other windows stay under their tabs. + Up(usize), +} + +impl Layout { + /// Each layout with its name in `layout`, in the order the menus list them. + pub(crate) const ALL: [(&'static str, Layout); 7] = [ + ("grid", Layout::Grid), + ("vertical", Layout::Vertical), + ("horizontal", Layout::Horizontal), + ("2up", Layout::Up(2)), + ("3up", Layout::Up(3)), + ("4up", Layout::Up(4)), + ("6up", Layout::Up(6)), + ]; + + /// The layout's name in `layout`. + pub(crate) fn name(self) -> &'static str { + Self::ALL.iter().find(|(_, l)| *l == self).map_or("grid", |(n, _)| n) } + + /// The layout `p`'s `layout` names, the grid without one. Any other value is an error. + pub(crate) fn from_params(p: &serde_json::Value) -> Result { + let key = "layout"; + match p.get(key) { + None => Ok(Layout::Grid), + Some(v) => v + .as_str() + .and_then(|s| Self::ALL.iter().find(|(n, _)| *n == s)) + .map(|(_, l)| *l) + .ok_or_else(|| format!("`{key}` must be one of {}", Self::ALL.map(|(n, _)| n).join(", "))), + } + } + + /// How many of `n` windows the layout gives a pane. + fn panes(self, n: usize) -> usize { + match self { + Layout::Up(k) => n.min(k), + _ => n, + } + } + + /// How many columns the layout puts `n` panes in. + fn columns(self, n: usize) -> usize { + match self { + Layout::Grid => grid_columns(n), + Layout::Vertical => n, + Layout::Horizontal => 1, + Layout::Up(k) if k <= 3 => n, + Layout::Up(k) => grid_columns(k).min(n), + } + } +} + +/// The square root of `n` rounded up. +fn grid_columns(n: usize) -> usize { let mut cols = 1; while cols * cols < n { cols += 1; } + cols +} + +/// The `n` panes `layout` places in `area`, filled row by row, in as many rows as its columns +/// need (the grid: as many columns as the square root of `n` rounded up). The panes meet edge to +/// edge and cover `area`; the spare cells of the last row stay empty. +pub(crate) fn layout_cells(layout: Layout, n: usize, area: egui::Rect) -> Vec { + if n == 0 { + return vec![]; + } + let cols = layout.columns(n).clamp(1, n); let rows = n.div_ceil(cols); let x = |c: usize| if c == cols { area.right() } else { area.left() + area.width() * c as f32 / cols as f32 }; let y = |r: usize| if r == rows { area.bottom() } else { area.top() + area.height() * r as f32 / rows as f32 }; (0..n).map(|i| egui::Rect::from_min_max(pos2(x(i % cols), y(i / cols)), pos2(x(i % cols + 1), y(i / cols + 1)))).collect() } -/// `window.arrange.tile`: every open document, and each further view of one, in a pane of its own, -/// each fitted to its pane. With fewer than two windows open (when the menu item is grayed out) it -/// leaves the view and `tiled` as they are. The windows floating come back under the tabs for it. -pub(crate) fn tile(app: &mut VectorcraftApp) -> Result { +/// The windows of `docked` (in tab order) that `layout` gives a pane: all of them, or as many of +/// the first ones as it shows, with the current window `active` in the last pane when it is not +/// among them. +pub(crate) fn shown_windows(layout: Layout, docked: &[Win], active: Option) -> Vec { + let k = layout.panes(docked.len()); + let mut shown = docked[..k].to_vec(); + if let (Some(a), Some(last)) = (active.filter(|a| !shown.contains(a) && docked.contains(a)), shown.last_mut()) { + *last = a; + } + shown +} + +/// `window.arrange.tile`: every open document, and each further view of one, in a pane of its own +/// as `layout` places them (the grid without one), each fitted to its pane. With fewer than two +/// windows open (when the menu item is grayed out) it leaves the view, `tiled` and the layout as +/// they are. The windows floating come back under the tabs for it. A `layout` that is not one of +/// [`Layout::ALL`]'s names is an error. +pub(crate) fn tile(app: &mut VectorcraftApp, p: &serde_json::Value) -> Result { + let layout = Layout::from_params(p)?; app.sync_views(); let n = crate::doc_windows::windows(app).len(); if n < 2 { - return Ok(json!({"tiled": app.ui.tiled, "panes": n})); + return Ok(json!({"tiled": app.ui.tiled, "panes": n, "layout": app.ui.tile_layout.name()})); } crate::doc_windows::dock_all(app); app.ui.tiled = true; + app.ui.tile_layout = layout; app.ui.home = None; crate::doc_windows::unfit_all(app); - Ok(json!({"tiled": app.ui.tiled, "panes": n})) + Ok(json!({"tiled": app.ui.tiled, "panes": layout.panes(n), "layout": layout.name()})) } /// `window.arrange.consolidateAllWindows`: one document at a time again, under its tab, the @@ -216,27 +307,41 @@ pub(crate) fn tiled_area(app: &mut VectorcraftApp, ui: &mut Ui) -> bool { app.canvas.panes.clear(); } app.canvas.panes.last.clear(); + app.canvas.panes.last_slots.clear(); return false; } // The current window's pane is the canvas, unless it is a floating one. let active = crate::doc_windows::current(app).filter(|a| docked.contains(a)); + // The 2-up to 6-up layouts leave the windows past their panes under the tabs. + let layout = app.ui.tile_layout; + let shown = shown_windows(layout, &docked, active); app.sync_views(); - let live: Vec = crate::doc_windows::windows(app).into_iter().filter_map(|w| slot(app, w)).collect(); + // The renders of the panes and the floating windows stay; a window under its tab has none. + let live: Vec = + crate::doc_windows::windows(app).into_iter().filter(|w| shown.contains(w) || !docked.contains(w)).filter_map(|w| slot(app, w)).collect(); app.canvas.panes.shown.retain(|s, _| live.contains(s)); app.canvas.panes.pending.retain(|s, _| live.contains(s)); app.canvas.panes.fits.retain(|s, _| live.contains(s)); - // A window opened, closed, floated or docked changes the grid, and so does coming back to the - // panes from one window: each window fits its new pane. - if app.canvas.panes.last.iter().map(|(w, _)| *w).ne(docked.iter().copied()) { - for w in &docked { - if let Some(v) = crate::doc_windows::view_mut(app, *w) { - v.fitted = false; - } + // A window opened, closed, floated or docked changes the panes, and so does coming back to the + // panes from one window: each window fits its new pane. With as many panes as before, only a + // window that moved to another pane fits it, as when a tab brings its window into the last pane + // of a 2-up to 6-up layout: the others keep their zoom and scroll. Windows are compared by + // their slots, since a closed document shifts the indices of the documents after it. + let before = std::mem::take(&mut app.canvas.panes.last_slots); + let now: Vec> = shown.iter().map(|w| slot(app, *w)).collect(); + let same_panes = before.len() == now.len(); + for (i, (w, s)) in shown.iter().zip(&now).enumerate() { + if same_panes && s.is_some() && before.get(i) == Some(s) { + continue; + } + if let Some(v) = crate::doc_windows::view_mut(app, *w) { + v.fitted = false; } } + app.canvas.panes.last_slots = now; let t = Tokens::get(ui.ctx()); let ppp = ui.ctx().pixels_per_point(); - let cells: Vec<(Win, egui::Rect)> = docked.iter().copied().zip(cells(n, ui.available_rect_before_wrap())).collect(); + let cells: Vec<(Win, egui::Rect)> = shown.iter().copied().zip(layout_cells(layout, shown.len(), ui.available_rect_before_wrap())).collect(); let areas: Vec<(Win, egui::Rect)> = cells.iter().map(|(w, cell)| (*w, view_rects(app, *cell, ppp).1)).collect(); let unfitted = refit_resized(app, &areas); let mut activate = None; diff --git a/crates/ui-egui/src/canvas/panes/tests.rs b/crates/ui-egui/src/canvas/panes/tests.rs index 005b930d01..2ad0af3dc1 100644 --- a/crates/ui-egui/src/canvas/panes/tests.rs +++ b/crates/ui-egui/src/canvas/panes/tests.rs @@ -43,6 +43,11 @@ fn button(pos: Pos2, pressed: bool) -> egui::Event { egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() } } +/// Tile's grid of `n` panes in `area`. +fn cells(n: usize, area: egui::Rect) -> Vec { + layout_cells(Layout::Grid, n, area) +} + /// The documents' indices in the panes the last frame drew, and the panes. fn panes(app: &VectorcraftApp) -> (Vec, Vec) { app.canvas.panes.last.iter().map(|(w, r)| (w.0, *r)).unzip() @@ -84,6 +89,279 @@ fn cells_tile_the_area_edge_to_edge() { } } +/// The distinct left and top edges of `c`: how many columns and rows its panes take. +fn columns_and_rows(c: &[egui::Rect]) -> (usize, usize) { + let lefts: BTreeSet = c.iter().map(|r| r.left().to_bits()).collect(); + let tops: BTreeSet = c.iter().map(|r| r.top().to_bits()).collect(); + (lefts.len(), tops.len()) +} + +#[test] +fn each_tile_layout_places_its_panes_edge_to_edge() { + let area = egui::Rect::from_min_size(pos2(10.0, 35.0), vec2(1001.0, 703.0)); + let cases = [ + (Layout::Vertical, 3, (3, 1)), + (Layout::Vertical, 7, (7, 1)), + (Layout::Horizontal, 3, (1, 3)), + (Layout::Up(2), 2, (2, 1)), + (Layout::Up(3), 3, (3, 1)), + (Layout::Up(3), 2, (2, 1)), + (Layout::Up(4), 4, (2, 2)), + (Layout::Up(4), 3, (2, 2)), + (Layout::Up(6), 6, (3, 2)), + (Layout::Up(6), 4, (3, 2)), + (Layout::Up(6), 2, (2, 1)), + ]; + for (layout, n, shape) in cases { + let c = layout_cells(layout, n, area); + assert_eq!(c.len(), n); + assert_eq!(columns_and_rows(&c), shape, "{layout:?} with {n} panes: columns and rows"); + assert_eq!(c[0].min, area.min, "{layout:?}: the first pane starts at the corner"); + let right = c.iter().map(|r| r.right()).fold(f32::MIN, f32::max); + let bottom = c.iter().map(|r| r.bottom()).fold(f32::MIN, f32::max); + assert_eq!((right, bottom), (area.right(), area.bottom()), "{layout:?} with {n} panes reaches the far edges"); + for (i, r) in c.iter().enumerate() { + assert!(r.width() > 0.0 && r.height() > 0.0 && area.contains_rect(*r), "{layout:?}: {r:?}"); + for o in &c[i + 1..] { + assert!(r.intersect(*o).area() <= 0.0, "{layout:?} panes overlap: {r:?} {o:?}"); + } + } + } + assert!(layout_cells(Layout::Up(2), 0, area).is_empty()); +} + +#[test] +fn tile_layouts_line_the_documents_up_side_by_side_or_stacked() { + let mut app = app_with(3); + let ctx = egui::Context::default(); + let reply = app.run("window.arrange.tile", json!({"layout": "vertical"})).unwrap(); + assert_eq!(reply, json!({"tiled": true, "panes": 3, "layout": "vertical"})); + frame(&mut app, &ctx, vec![]); + let (docs, rects) = panes(&app); + assert_eq!(docs, [0, 1, 2]); + assert!(rects.windows(2).all(|p| p[0].top() == p[1].top() && p[0].height() == p[1].height() && p[0].right() == p[1].left()), "{rects:?}"); + let reply = app.run("window.arrange.tile", json!({"layout": "horizontal"})).unwrap(); + assert_eq!(reply, json!({"tiled": true, "panes": 3, "layout": "horizontal"})); + frame(&mut app, &ctx, vec![]); + let (docs, rects) = panes(&app); + assert_eq!(docs, [0, 1, 2]); + assert!(rects.windows(2).all(|p| p[0].left() == p[1].left() && p[0].width() == p[1].width() && p[0].bottom() == p[1].top()), "{rects:?}"); + // Each document fits its new pane. + let artboard = Rect::new(0.0, 0.0, 400.0, 300.0); + let canvas = app.canvas_rect.unwrap(); + for (i, r) in docs.iter().zip(&rects) { + let shown = if *i == 2 { canvas } else { view_rects(&app, *r, ctx.pixels_per_point()).1 }; + let v = app.views[*i]; + assert!(v.fitted && (v.zoom - fit_zoom(shown, artboard, 0.0, 1.0)).abs() < 1e-9, "document {i} fits its pane: {v:?}"); + } + assert_eq!(crate::control::inspect(&app, &ctx)["tileLayout"], json!("horizontal")); + assert_eq!(app.run("window.arrange.tile", json!({})).unwrap()["layout"], json!("grid"), "Tile without a layout is the grid"); +} + +#[test] +fn n_up_shows_that_many_documents_and_keeps_the_rest_under_their_tabs() { + let mut app = app_with(5); + let ctx = egui::Context::default(); + assert_eq!(app.run("window.arrange.tile", json!({"layout": "2up"})).unwrap(), json!({"tiled": true, "panes": 2, "layout": "2up"})); + frame(&mut app, &ctx, vec![]); + assert_eq!(panes(&app).0, [0, 4], "the current document takes the last pane"); + app.run("document.activate", json!({"index": 1})).unwrap(); + frame(&mut app, &ctx, vec![]); + assert_eq!(panes(&app).0, [0, 1], "the first documents in tab order"); + let second = (app.session.documents()[1].uid, 1); + app.run("document.activate", json!({"index": 0})).unwrap(); + frame(&mut app, &ctx, vec![]); + assert!(app.canvas.panes.shown.contains_key(&second), "the second document is rendered for its pane"); + app.run("document.activate", json!({"index": 3})).unwrap(); + frame(&mut app, &ctx, vec![]); + let (docs, rects) = panes(&app); + assert_eq!(docs, [0, 3], "a document chosen under its tab comes into the last pane"); + assert!(!app.canvas.panes.shown.contains_key(&second), "a document under its tab keeps no render"); + let artboard = Rect::new(0.0, 0.0, 400.0, 300.0); + let shown = view_rects(&app, rects[0], ctx.pixels_per_point()).1; + assert!((app.views[0].zoom - fit_zoom(shown, artboard, 0.0, 1.0)).abs() < 1e-9); + assert!(app.canvas_rect.is_some_and(|c| rects[1].contains_rect(c)), "the current document's pane is the canvas"); + // A document brought into the last pane leaves the first pane's zoom as it is. + app.views[0].zoom *= 2.0; + let zoomed = app.views[0].zoom; + app.run("document.activate", json!({"index": 2})).unwrap(); + frame(&mut app, &ctx, vec![]); + assert_eq!(panes(&app).0, [0, 2]); + assert_eq!(app.views[0].zoom, zoomed, "the document that stayed in its pane keeps its zoom"); + let last = app.canvas_rect.unwrap(); + assert!((app.views[2].zoom - fit_zoom(last, artboard, 0.0, 1.0)).abs() < 1e-9, "the document brought in fits its pane"); + assert_eq!(app.run("window.arrange.tile", json!({"layout": "4up"})).unwrap()["panes"], json!(4)); + frame(&mut app, &ctx, vec![]); + let (docs, rects) = panes(&app); + assert_eq!((docs, columns_and_rows(&rects)), (vec![0, 1, 2, 3], (2, 2))); + assert_eq!(app.run("window.arrange.tile", json!({"layout": "6up"})).unwrap()["panes"], json!(5), "6-Up with five documents shows them all"); + frame(&mut app, &ctx, vec![]); + let (docs, rects) = panes(&app); + assert_eq!((docs, columns_and_rows(&rects)), (vec![0, 1, 2, 3, 4], (3, 2))); + assert_eq!(app.run("window.arrange.tile", json!({"layout": "3up"})).unwrap()["panes"], json!(3)); + frame(&mut app, &ctx, vec![]); + let (docs, rects) = panes(&app); + assert_eq!((docs, columns_and_rows(&rects)), (vec![0, 1, 2], (3, 1))); + app.run("document.activate", json!({"index": 4})).unwrap(); + frame(&mut app, &ctx, vec![]); + assert_eq!(panes(&app).0, [0, 1, 4]); +} + +/// A document closed before the panes shifts the indices of the ones after it: the document that +/// moves into another pane fits it. +#[test] +fn closing_a_document_in_an_n_up_layout_fits_the_documents_that_change_panes() { + let mut app = app_with(4); + let ctx = egui::Context::default(); + app.run("document.activate", json!({"index": 1})).unwrap(); + app.run("window.arrange.tile", json!({"layout": "2up"})).unwrap(); + frame(&mut app, &ctx, vec![]); + app.run("document.activate", json!({"index": 3})).unwrap(); + frame(&mut app, &ctx, vec![]); + assert_eq!(panes(&app).0, [0, 3]); + let moving = app.session.documents()[1].uid; + // The second document's view, under its tab, is zoomed away from its fit. + app.views[1].zoom *= 3.0; + app.run("file.close", json!({"index": 0})).unwrap(); + frame(&mut app, &ctx, vec![]); + let (docs, rects) = panes(&app); + assert_eq!(docs, [0, 2], "the former second document is first now, the current one stays last"); + assert_eq!(app.session.documents()[0].uid, moving); + let area = view_rects(&app, rects[0], ctx.pixels_per_point()).1; + let v = app.views[0]; + assert!(v.fitted && (v.zoom - fit_zoom(area, Rect::new(0.0, 0.0, 400.0, 300.0), 0.0, 1.0)).abs() < 1e-9, "it fits its new pane: {v:?}"); +} + +#[test] +fn tile_refuses_a_layout_it_does_not_have() { + let mut app = app_with(3); + for bad in [json!("5up"), json!("Vertical"), json!(3), json!(null), json!({})] { + let err = app.run("window.arrange.tile", json!({"layout": bad})).unwrap_err(); + assert_eq!(err, "`layout` must be one of grid, vertical, horizontal, 2up, 3up, 4up, 6up", "{bad}"); + assert!(!app.ui.tiled && app.ui.tile_layout == Layout::Grid, "{bad}: the view stays as it is"); + } + app.run("window.arrange.tile", json!({"layout": "vertical"})).unwrap(); + assert!(app.run("window.arrange.tile", json!({"layout": "diagonal"})).is_err()); + assert_eq!(app.ui.tile_layout, Layout::Vertical, "a refused layout leaves the tiled one"); + // With one document the layout is still checked, and nothing changes. + let mut one = app_with(1); + assert!(one.run("window.arrange.tile", json!({"layout": "7up"})).is_err()); + assert_eq!(one.run("window.arrange.tile", json!({"layout": "2up"})).unwrap(), json!({"tiled": false, "panes": 1, "layout": "grid"})); +} + +#[test] +fn the_tile_items_check_the_layout_the_panes_show() { + let mut app = app_with(3); + let checked = |app: &VectorcraftApp, layout: Option<&str>| { + let p = layout.map_or(serde_json::Value::Null, |l| json!({"layout": l})); + crate::menus::checked(app, "window.arrange.tile", &p) + }; + assert_eq!(checked(&app, None), Some(false), "not tiled"); + app.run("window.arrange.tile", json!({"layout": "4up"})).unwrap(); + assert_eq!(checked(&app, Some("4up")), Some(true)); + assert_eq!(checked(&app, None), Some(false)); + assert_eq!(checked(&app, Some("2up")), Some(false)); + app.run("window.arrange.tile", json!({})).unwrap(); + assert_eq!(checked(&app, None), Some(true), "Tile is the grid"); + app.run("window.arrange.consolidateAllWindows", json!({})).unwrap(); + assert_eq!(checked(&app, None), Some(false)); + // Window › Arrange lists every layout, after Cascade and before Float in Window. + let window = crate::menus::menu_tree().into_iter().find(|(t, _)| *t == "Window").map(|(_, items)| items).unwrap(); + let arrange = window + .into_iter() + .find_map(|i| match i { + crate::menus::Item::Sub("Arrange", items) => Some(items), + _ => None, + }) + .unwrap(); + let labels: Vec<&str> = arrange + .iter() + .filter_map(|i| match i { + crate::menus::Item::Cmd(l, ..) => Some(*l), + _ => None, + }) + .collect(); + assert_eq!( + labels, + [ + "Cascade", + "Tile", + "Tile All Vertically", + "Tile All Horizontally", + "2-Up Layout", + "3-Up Layout", + "4-Up Layout", + "6-Up Layout", + "Float in Window", + "Float All in Windows", + "Consolidate All Windows" + ] + ); + // Each item's params run, as the menu sends them. + for item in &arrange { + if let crate::menus::Item::Cmd(_, "window.arrange.tile", p) = item { + let p = if p.is_null() { json!({}) } else { p.clone() }; + assert!(app.run("window.arrange.tile", p.clone()).is_ok(), "{p}"); + } + } +} + +/// One frame of the application bar with screen-reader nodes on → the nodes. +fn app_bar_frame(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec) -> Vec { + let screen = egui::Rect::from_min_size(Pos2::ZERO, vec2(1400.0, 800.0)); + let mut out = ctx.run_ui(egui::RawInput { events, screen_rect: Some(screen), ..Default::default() }, |ui| crate::chrome::app_bar(app, ui)); + out.textures_delta.clear(); + out.platform_output.accesskit_update.map(|u| u.nodes.into_iter().map(|(_, n)| n).collect()).unwrap_or_default() +} + +/// The center of the application bar's node whose label, without its leading spaces, is `name` +/// (or starts with it and a shortcut in parentheses). +fn app_bar_node(nodes: &[egui::accesskit::Node], name: &str) -> Option { + let named = |l: &str| l.trim_start().strip_prefix(name).is_some_and(|rest| rest.is_empty() || rest.trim_start().starts_with('(')); + let b = nodes.iter().find(|n| n.label().is_some_and(named))?.bounds()?; + Some(pos2(((b.x0 + b.x1) / 2.0) as f32, ((b.y0 + b.y1) / 2.0) as f32)) +} + +/// Click the application bar's node labeled `name`. +fn click_app_bar(app: &mut VectorcraftApp, ctx: &egui::Context, name: &str) { + let at = app_bar_node(&app_bar_frame(app, ctx, vec![]), name).unwrap_or_else(|| panic!("{name} is drawn")); + app_bar_frame(app, ctx, vec![egui::Event::PointerMoved(at), button(at, true)]); + app_bar_frame(app, ctx, vec![button(at, false)]); +} + +#[test] +fn the_arrange_documents_button_tiles_and_consolidates() { + crate::i18n::set_current(crate::i18n::Lang::EN); + let mut app = app_with(3); + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + crate::theme::install_fonts(&ctx); + app_bar_frame(&mut app, &ctx, vec![]); + let nodes = app_bar_frame(&mut app, &ctx, vec![]); + let (arrange, search) = (app_bar_node(&nodes, "Arrange Documents"), app_bar_node(&nodes, "Search commands and tools")); + let (arrange, search) = (arrange.expect("the application bar has Arrange Documents"), search.expect("the search icon shows")); + assert!(arrange.x > search.x && (arrange.y - search.y).abs() < 1.0, "right of the search icon: {arrange:?}, {search:?}"); + click_app_bar(&mut app, &ctx, "Arrange Documents"); + let menu = app_bar_frame(&mut app, &ctx, vec![]); + for item in [ + "Consolidate All Windows", + "Tile", + "Tile All Vertically", + "Tile All Horizontally", + "2-Up Layout", + "3-Up Layout", + "4-Up Layout", + "6-Up Layout", + ] { + assert!(app_bar_node(&menu, item).is_some(), "the menu lists {item}"); + } + click_app_bar(&mut app, &ctx, "Tile All Vertically"); + assert!(app.ui.tiled && app.ui.tile_layout == Layout::Vertical, "{}", app.ui.status); + click_app_bar(&mut app, &ctx, "Arrange Documents"); + click_app_bar(&mut app, &ctx, "Consolidate All Windows"); + assert!(!app.ui.tiled); +} + #[test] fn tile_shows_a_pane_for_each_document_fitted_to_it() { let mut app = app_with(3); @@ -91,7 +369,7 @@ fn tile_shows_a_pane_for_each_document_fitted_to_it() { frame(&mut app, &ctx, vec![]); assert!(panes(&app).0.is_empty(), "documents open under their tabs"); let tabbed = app.canvas_rect.unwrap(); - assert_eq!(app.run("window.arrange.tile", json!({})).unwrap(), json!({"tiled": true, "panes": 3})); + assert_eq!(app.run("window.arrange.tile", json!({})).unwrap(), json!({"tiled": true, "panes": 3, "layout": "grid"})); frame(&mut app, &ctx, vec![]); let (docs, rects) = panes(&app); assert_eq!(docs, [0, 1, 2]); @@ -206,7 +484,7 @@ fn arrange_items_follow_the_open_documents() { fn tile_with_one_document_leaves_the_next_one_under_its_tab() { let mut app = app_with(1); let ctx = egui::Context::default(); - assert_eq!(app.run("window.arrange.tile", json!({})).unwrap(), json!({"tiled": false, "panes": 1})); + assert_eq!(app.run("window.arrange.tile", json!({})).unwrap(), json!({"tiled": false, "panes": 1, "layout": "grid"})); assert!(!app.ui.tiled); assert!(!enabled(&app, "window.arrange.consolidateAllWindows")); app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); diff --git a/crates/ui-egui/src/chrome.rs b/crates/ui-egui/src/chrome.rs index fc0234885b..96b4d12965 100644 --- a/crates/ui-egui/src/chrome.rs +++ b/crates/ui-egui/src/chrome.rs @@ -85,7 +85,7 @@ pub fn app_bar(app: &mut VectorcraftApp, ui: &mut Ui) { // The right-side group fills the space after the menus from the right; when it runs // short, Discord goes first (it is also under Help), then Explore tutorials (also // Window › Learn), then the search icon (the palette stays under its shortcut), then - // the workspace switcher narrows. + // Arrange Documents (also Window › Arrange), then the workspace switcher narrows. let full = ui.max_rect(); let right_edge = if captions_right > 0.0 { full.right() - captions_right - 10.0 } else { full.right() }; let right = egui::Rect::from_min_max(egui::pos2(menus_end + 8.0, full.top()), egui::pos2(right_edge, full.bottom())); @@ -105,13 +105,16 @@ pub fn app_bar(app: &mut VectorcraftApp, ui: &mut Ui) { let ws = ui.painter().layout_no_wrap(ws_name, egui::FontId::proportional(12.0), t.text); let ws_w = (ws.size().x + 36.0).clamp(112.0, 190.0); let gap = ui.spacing().item_spacing.x; - // The search icon, as in PhotoCraft: shown while a minimal switcher fits beside it. + // Arrange Documents, beside the switcher, then the search icon, as in PhotoCraft: each + // shown while a minimal switcher fits beside it. let icon = 28.0; - let search = switcher && room >= 64.0 + 8.0 + gap + icon; - let ws_w = ws_w.min(room - 8.0 - gap - if search { icon } else { 0.0 }).max(64.0); + let arrange = switcher && room >= 64.0 + 8.0 + gap + icon; + let search = arrange && room >= 64.0 + 8.0 + 2.0 * (gap + icon); + let icons = f32::from(u8::from(arrange) + u8::from(search)); + let ws_w = ws_w.min(room - 8.0 - icons * (gap + icon)).max(64.0); // Explore tutorials, beside the search icon, opens the Learn panel. - let learn = search && room >= ws_w + 8.0 + 2.0 * (gap + icon); - let discord = learn && room >= ws_w + 8.0 + 2.0 * (gap + icon) + 10.0 + gap + crate::community::discord_width(ui, false); + let learn = search && room >= ws_w + 8.0 + 3.0 * (gap + icon); + let discord = learn && room >= ws_w + 8.0 + 3.0 * (gap + icon) + 10.0 + gap + crate::community::discord_width(ui, false); let mut rui = ui.new_child(egui::UiBuilder::new().max_rect(right).layout(egui::Layout::right_to_left(egui::Align::Center))); let ui = &mut rui; // Workspace switcher: shows the current workspace, opens Window → Workspace. @@ -130,6 +133,11 @@ pub fn app_bar(app: &mut VectorcraftApp, ui: &mut Ui) { } ui.add_space(8.0); } + // Arrange Documents: Consolidate All Windows and the Tile layouts. + if arrange { + let resp = widgets::icon_button(ui, "layout-grid", tl!("Arrange Documents"), app.ui.tiled, icon); + egui::Popup::menu(&resp).show(|ui| arrange_documents_popup(app, ui)); + } // Search → command palette (its shortcut opens it too). if search { let tip = match menus::shortcut_of("help.commandPalette") { @@ -168,6 +176,33 @@ pub fn app_bar(app: &mut VectorcraftApp, ui: &mut Ui) { } } +/// The Arrange Documents menu ([`menus::arrange_documents_items`]): each item as the Window menu +/// shows it, grayed out while its command can't run, the Tile layout the panes show checked. +fn arrange_documents_popup(app: &mut VectorcraftApp, ui: &mut Ui) { + ui.set_min_width(200.0); + let mut clicked = None; + for it in menus::arrange_documents_items() { + match it { + menus::Item::Sep => { + ui.separator(); + } + menus::Item::Cmd(label, id, p) => { + let Some((enabled, checked)) = menus::shown_state(app, id, &p) else { continue }; + let label = crate::i18n::t_id(id, label); + let text = if checked == Some(true) { format!("✓ {label}") } else { format!(" {label}") }; + if ui.add_enabled(enabled, egui::Button::new(text).min_size(vec2(200.0, 0.0))).clicked() { + clicked = Some((id, if p.is_null() { json!({}) } else { p })); + ui.close(); + } + } + _ => {} + } + } + if let Some((id, p)) = clicked { + menus::invoke(app, id, p); + } +} + /// Whether the window shows the system's title bar instead of the app drawing its own /// ([`VectorcraftApp::desktop_frame`]): Windows with Preferences › User Interface › System Title /// Bar, and Linux whenever the desktop draws the frame, with or without the preference. The diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 26f67a0365..461b352c4e 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -273,11 +273,12 @@ pub fn inspect(app: &VectorcraftApp, ctx: &egui::Context) -> Value { // The display profile the canvas is drawn through, or why none (Preferences › // Performance › Use Monitor Profile for Canvas). "displayProfile": app.display_profile.status(app.session.prefs.monitor_profile_display), - // Window › Arrange › Tile (not saved, so not in `ui`) and the panes the last frame drew: - // each one's document index, view number (Window › New Window) and rect. Canvas - // coordinates map to the current window's pane, inside its rulers and scroll bars + // Window › Arrange › Tile and its layout (not saved, so not in `ui`) and the panes the + // last frame drew: each one's document index, view number (Window › New Window) and rect. + // Canvas coordinates map to the current window's pane, inside its rulers and scroll bars // (`canvasRect`). "tiled": app.ui.tiled, + "tileLayout": app.ui.tile_layout.name(), "panes": app.canvas.panes.last.iter().map(|(w, c)| json!({ "document": w.0, "view": w.1, diff --git a/crates/ui-egui/src/doc_windows/tests.rs b/crates/ui-egui/src/doc_windows/tests.rs index 64a693a09b..91a0ef23e4 100644 --- a/crates/ui-egui/src/doc_windows/tests.rs +++ b/crates/ui-egui/src/doc_windows/tests.rs @@ -259,7 +259,7 @@ fn tile_brings_floating_documents_back_into_the_grid() { frame(&mut app, &ctx, vec![]); let docs: Vec = app.canvas.panes.last.iter().map(|(w, _)| w.0).collect(); assert_eq!(docs, [0, 1], "a floating document leaves the grid; the tabbed ones share it"); - assert_eq!(app.run("window.arrange.tile", json!({})).unwrap(), json!({"tiled": true, "panes": 3})); + assert_eq!(app.run("window.arrange.tile", json!({})).unwrap(), json!({"tiled": true, "panes": 3, "layout": "grid"})); frame(&mut app, &ctx, vec![]); let docs: Vec = app.canvas.panes.last.iter().map(|(w, _)| w.0).collect(); assert_eq!(docs, [0, 1, 2]); @@ -844,7 +844,7 @@ fn arrange_treats_each_view_as_a_window() { assert!(!enabled(&app, "window.arrange.tile") && !enabled(&app, "window.arrange.cascade"), "one window"); app.run("window.newWindow", json!({})).unwrap(); assert!(enabled(&app, "window.arrange.tile") && enabled(&app, "window.arrange.cascade"), "two views of one document"); - assert_eq!(app.run("window.arrange.tile", json!({})).unwrap(), json!({"tiled": true, "panes": 2})); + assert_eq!(app.run("window.arrange.tile", json!({})).unwrap(), json!({"tiled": true, "panes": 2, "layout": "grid"})); app.run("window.arrange.cascade", json!({})).unwrap(); frame(&mut app, &ctx, vec![]); let uid = app.session.documents()[0].uid; diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index d0a770b2b1..ffeacfc3f5 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -3643,6 +3643,13 @@ digits Malayalam Малаялам Thumbnail View Изглед с миниатюри Thumbnails: Миниатюри: Tile Мозайка + Tile All Vertically Всички в мозайка вертикално + Tile All Horizontally Всички в мозайка хоризонтално + 2-Up Layout Подредба по 2 + 3-Up Layout Подредба по 3 + 4-Up Layout Подредба по 4 + 6-Up Layout Подредба по 6 + Arrange Documents Подреждане на документите Tile Edge Color Цвят на ръба на плочката Tile Edge Color… Цвят на ръба на плочката… Tile Full Pages Покриване на цели страници diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 5fca937f98..916a3e6b5f 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -689,6 +689,13 @@ Previous Document Prethodni dokument Cascade Kaskadno Tile Popločaj + Tile All Vertically Popločaj sve okomito + Tile All Horizontally Popločaj sve vodoravno + 2-Up Layout Raspored po 2 + 3-Up Layout Raspored po 3 + 4-Up Layout Raspored po 4 + 6-Up Layout Raspored po 6 + Arrange Documents Rasporedi dokumente Float in Window Odvoji u prozor Float All in Windows Odvoji sve u prozore Consolidate All Windows Objedini sve prozore diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index b6fdc2a6a6..7fe0977ead 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -4740,6 +4740,13 @@ digits Malayalam Malaiàlam TIFF (8-bit Color) TIFF (color de 8 bits) TIFF (Black & White) TIFF (blanc i negre) Tile Mosaic + Tile All Vertically Mosaic vertical de tot + Tile All Horizontally Mosaic horitzontal de tot + 2-Up Layout Disposició de 2 + 3-Up Layout Disposició de 3 + 4-Up Layout Disposició de 4 + 6-Up Layout Disposició de 6 + Arrange Documents Organitza els documents Tile Edge Color Color de la vora del mosaic Tile Edge Color… Color de la vora del mosaic… Tile Full Pages Mosaic de pàgines senceres diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 47ca092cc0..d9fa87f2bf 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -702,6 +702,13 @@ Previous Document Předchozí dokument Cascade Do kaskády Tile Vedle sebe + Tile All Vertically Vše vedle sebe svisle + Tile All Horizontally Vše vedle sebe vodorovně + 2-Up Layout Rozvržení po 2 + 3-Up Layout Rozvržení po 3 + 4-Up Layout Rozvržení po 4 + 6-Up Layout Rozvržení po 6 + Arrange Documents Uspořádat dokumenty Float in Window Uvolnit do samostatného okna Float All in Windows Uvolnit vše do samostatných oken Consolidate All Windows Sloučit všechna okna diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index ca27bdd2f9..57322a818e 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -1257,6 +1257,13 @@ Previous Document Forrige dokument Cascade Kaskade Tile Fliselæg + Tile All Vertically Fliselæg alle lodret + Tile All Horizontally Fliselæg alle vandret + 2-Up Layout Layout med 2 + 3-Up Layout Layout med 3 + 4-Up Layout Layout med 4 + 6-Up Layout Layout med 6 + Arrange Documents Arrangér dokumenter Float in Window Flyd i vindue Float All in Windows Flyd alle i vinduer Consolidate All Windows Saml alle vinduer diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index df4d5df82e..3da18ee5ba 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -3686,6 +3686,13 @@ effect Points Punkte Thumbnail View Miniaturansicht Thumbnails: Miniaturen: Tile Nebeneinander + Tile All Vertically Alle vertikal nebeneinander + Tile All Horizontally Alle horizontal nebeneinander + 2-Up Layout Layout mit 2 + 3-Up Layout Layout mit 3 + 4-Up Layout Layout mit 4 + 6-Up Layout Layout mit 6 + Arrange Documents Dokumente anordnen Tile Edge Color Farbe der Kachelkante Tile Edge Color… Farbe der Kachelkante… Tile Full Pages Ganze Seiten aufteilen diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 9f3ee177e5..739d63f664 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -2171,6 +2171,13 @@ font-technology Variable Μεταβλητές Templates Πρότυπα Threshold Κατώφλι Tile Παράθεση + Tile All Vertically Παράθεση όλων κατακόρυφα + Tile All Horizontally Παράθεση όλων οριζόντια + 2-Up Layout Διάταξη ανά 2 + 3-Up Layout Διάταξη ανά 3 + 4-Up Layout Διάταξη ανά 4 + 6-Up Layout Διάταξη ανά 6 + Arrange Documents Διάταξη εγγράφων Tint Χρωματική απόχρωση Fill Tint Χρωματική απόχρωση γεμίσματος Stroke Tint Χρωματική απόχρωση περιγράμματος diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 555e51b8c7..8244d1fee3 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -3734,6 +3734,13 @@ digits Malayalam Malayálam Thumbnail View Vista de miniaturas Thumbnails: Miniaturas: Tile Mosaico + Tile All Vertically Mosaico vertical de todo + Tile All Horizontally Mosaico horizontal de todo + 2-Up Layout Disposición de 2 + 3-Up Layout Disposición de 3 + 4-Up Layout Disposición de 4 + 6-Up Layout Disposición de 6 + Arrange Documents Organizar documentos Tile Edge Color Color del borde del mosaico Tile Edge Color… Color del borde del mosaico… Tile Full Pages Mosaico de páginas completas diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 363042b43d..85043309b2 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -693,6 +693,13 @@ Previous Document Edellinen asiakirja Cascade Porrasta Tile Vierekkäin + Tile All Vertically Kaikki vierekkäin pystysuunnassa + Tile All Horizontally Kaikki vierekkäin vaakasuunnassa + 2-Up Layout 2 ikkunan asettelu + 3-Up Layout 3 ikkunan asettelu + 4-Up Layout 4 ikkunan asettelu + 6-Up Layout 6 ikkunan asettelu + Arrange Documents Järjestä asiakirjat Float in Window Kelluta ikkunassa Float All in Windows Kelluta kaikki ikkunoissa Consolidate All Windows Yhdistä kaikki ikkunat diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 494a2d944a..6ea29e0c88 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -3726,6 +3726,13 @@ digits Malayalam Malayalam Thumbnail View Vignettes Thumbnails: Vignettes : Tile Mosaïque + Tile All Vertically Tout en mosaïque verticale + Tile All Horizontally Tout en mosaïque horizontale + 2-Up Layout Disposition par 2 + 3-Up Layout Disposition par 3 + 4-Up Layout Disposition par 4 + 6-Up Layout Disposition par 6 + Arrange Documents Disposer les documents Tile Edge Color Couleur du bord du carreau Tile Edge Color… Couleur du bord du carreau… Tile Full Pages Mosaïque de pages entières diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 7382b4fe9e..f7d8b1c2a9 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -3837,6 +3837,13 @@ Three Point Perspective Preset 5 ત્રણ બિંદુ પર્સ્પેક્ટિવ પ્રીસેટ 5 Thumbnails: થંબનેલ: Tile ટાઇલ + Tile All Vertically બધું ઊભી રીતે ટાઇલ કરો + Tile All Horizontally બધું આડી રીતે ટાઇલ કરો + 2-Up Layout 2 નું લેઆઉટ + 3-Up Layout 3 નું લેઆઉટ + 4-Up Layout 4 નું લેઆઉટ + 6-Up Layout 6 નું લેઆઉટ + Arrange Documents દસ્તાવેજો ગોઠવો Tile Edge Color ટાઇલ કિનારીનો રંગ Tile Edge Color… ટાઇલ કિનારીનો રંગ… Tile Range: ટાઇલ શ્રેણી: diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index edfbe0818f..a1bbffcb84 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -5130,6 +5130,13 @@ antiAlias Sharp शार्प TIFF (8-bit Color) TIFF (8-बिट रंग) TIFF (Black & White) TIFF (ब्लैक एंड व्हाइट) Tile टाइल + Tile All Vertically सभी को लंबवत टाइल करें + Tile All Horizontally सभी को क्षैतिज टाइल करें + 2-Up Layout 2 का लेआउट + 3-Up Layout 3 का लेआउट + 4-Up Layout 4 का लेआउट + 6-Up Layout 6 का लेआउट + Arrange Documents दस्तावेज़ व्यवस्थित करें tile {number} टाइल {number} Tile Edge Color टाइल एज रंग Tile Edge Color… टाइल एज रंग… diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 27dda10840..b57ce2d524 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -4420,6 +4420,13 @@ mark-style Japanese Japán TIFF (8-bit Color) TIFF (8 bites színes) TIFF (Black & White) TIFF (fekete-fehér) Tile Mozaikelrendezés + Tile All Vertically Összes mozaikelrendezése függőlegesen + Tile All Horizontally Összes mozaikelrendezése vízszintesen + 2-Up Layout 2-es elrendezés + 3-Up Layout 3-as elrendezés + 4-Up Layout 4-es elrendezés + 6-Up Layout 6-os elrendezés + Arrange Documents Dokumentumok elrendezése Tile Edge Color Csempeszél színe Tile Edge Color… Csempeszél színe… Tile Full Pages Teljes oldalak csempézése diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index f870492477..d323f3fb3d 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -648,6 +648,13 @@ Previous Document Dokumen sebelumnya Cascade Bertingkat Tile Ubin + Tile All Vertically Ubin semua secara vertikal + Tile All Horizontally Ubin semua secara horizontal + 2-Up Layout Tata letak 2 + 3-Up Layout Tata letak 3 + 4-Up Layout Tata letak 4 + 6-Up Layout Tata letak 6 + Arrange Documents Susun dokumen Float in Window Mengambang di jendela Float All in Windows Mengambangkan semua di jendela Consolidate All Windows Konsolidasikan semua jendela diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 7ef7dedc00..be1847efa5 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -3780,6 +3780,13 @@ digits Malayalam Malayalam Thumbnail View Vista miniature Thumbnails: Miniature: Tile Affianca + Tile All Vertically Affianca tutto verticalmente + Tile All Horizontally Affianca tutto orizzontalmente + 2-Up Layout Layout a 2 + 3-Up Layout Layout a 3 + 4-Up Layout Layout a 4 + 6-Up Layout Layout a 6 + Arrange Documents Disponi documenti Tile Edge Color Colore bordo tassello Tile Edge Color… Colore bordo tassello… Tile Full Pages Affianca pagine intere diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index c18d4c55ca..aabea31a78 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -725,6 +725,13 @@ digits Malayalam マラヤーラム数字 Previous Document 前のドキュメント Cascade 重ねて表示 Tile 並べて表示 + Tile All Vertically すべてを左右に並べて表示 + Tile All Horizontally すべてを上下に並べて表示 + 2-Up Layout 2 分割レイアウト + 3-Up Layout 3 分割レイアウト + 4-Up Layout 4 分割レイアウト + 6-Up Layout 6 分割レイアウト + Arrange Documents ドキュメントの配置 Float in Window ウィンドウを分離 Float All in Windows すべてをウィンドウに分離 Consolidate All Windows すべてのウィンドウを統合 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 5ab6945aec..33cafdc24e 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -622,6 +622,13 @@ Previous Document წინა დოკუმენტი Cascade კასკადად Tile ფილებად + Tile All Vertically ყველა ფილებად ვერტიკალურად + Tile All Horizontally ყველა ფილებად ჰორიზონტალურად + 2-Up Layout 2-იანი განლაგება + 3-Up Layout 3-იანი განლაგება + 4-Up Layout 4-იანი განლაგება + 6-Up Layout 6-იანი განლაგება + Arrange Documents დოკუმენტების დალაგება Float in Window ცალკე ფანჯარაში გამოტანა Float All in Windows ყველას ცალკე ფანჯრებში გამოტანა Consolidate All Windows ყველა ფანჯრის გაერთიანება diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 9ed9cd6a98..bbfc3bfed6 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -718,6 +718,13 @@ digits Malayalam 말라얄람어 Previous Document 이전 문서 Cascade 계단식 배열 Tile 바둑판식 배열 + Tile All Vertically 모두 세로로 바둑판식 배열 + Tile All Horizontally 모두 가로로 바둑판식 배열 + 2-Up Layout 2분할 레이아웃 + 3-Up Layout 3분할 레이아웃 + 4-Up Layout 4분할 레이아웃 + 6-Up Layout 6분할 레이아웃 + Arrange Documents 문서 정렬 Float in Window 창에 플로팅 Float All in Windows 모두 창에 플로팅 Consolidate All Windows 모든 창 통합 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 711ce4c8a8..002aabacc0 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -1166,6 +1166,13 @@ Previous Document Vorig document Cascade Trapsgewijs schikken Tile Naast elkaar schikken + Tile All Vertically Alles verticaal naast elkaar schikken + Tile All Horizontally Alles horizontaal naast elkaar schikken + 2-Up Layout Indeling met 2 + 3-Up Layout Indeling met 3 + 4-Up Layout Indeling met 4 + 6-Up Layout Indeling met 6 + Arrange Documents Documenten schikken Float in Window In venster zweven Float All in Windows Alles in vensters zweven Consolidate All Windows Alle vensters samenvoegen diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 7e29ed89c5..cde65748c8 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -659,6 +659,13 @@ Previous Document Poprzedni dokument Cascade Kaskadowo Tile Sąsiadująco + Tile All Vertically Wszystkie sąsiadująco w pionie + Tile All Horizontally Wszystkie sąsiadująco w poziomie + 2-Up Layout Układ po 2 + 3-Up Layout Układ po 3 + 4-Up Layout Układ po 4 + 6-Up Layout Układ po 6 + Arrange Documents Rozmieść dokumenty Float in Window Pływające w oknie Float All in Windows Wszystkie pływające w oknach Consolidate All Windows Scal wszystkie okna diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index b9d233f1c9..8867015300 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -3088,6 +3088,13 @@ digits Malayalam Malaiala Threshold Limite Thumbnail View Exibição em Miniatura Tile Bloco + Tile All Vertically Todos em Bloco na Vertical + Tile All Horizontally Todos em Bloco na Horizontal + 2-Up Layout Layout de 2 + 3-Up Layout Layout de 3 + 4-Up Layout Layout de 4 + 6-Up Layout Layout de 6 + Arrange Documents Organizar Documentos Tile Edge Color Cor da Borda do Bloco Tile Edge Color… Cor da Borda do Bloco… Tile Range: Intervalo de Blocos: diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 5845c34c1d..3940cb892d 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -3766,6 +3766,13 @@ digits Malayalam Малаялам Thumbnail View Миниатюры Thumbnails: Миниатюры: Tile Плитка + Tile All Vertically Все плиткой по вертикали + Tile All Horizontally Все плиткой по горизонтали + 2-Up Layout Макет на 2 + 3-Up Layout Макет на 3 + 4-Up Layout Макет на 4 + 6-Up Layout Макет на 6 + Arrange Documents Упорядочить документы Tile Edge Color Цвет края плитки Tile Edge Color… Цвет края плитки… Tile Full Pages Плитка целых страниц diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 9e37b924b0..b070c937a1 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -3656,6 +3656,13 @@ digits Malayalam Malayalam Thumbnail View Miniatyrvy Thumbnails: Miniatyrer: Tile Sida vid sida + Tile All Vertically Alla sida vid sida lodrätt + Tile All Horizontally Alla sida vid sida vågrätt + 2-Up Layout Layout med 2 + 3-Up Layout Layout med 3 + 4-Up Layout Layout med 4 + 6-Up Layout Layout med 6 + Arrange Documents Ordna dokument Tile Edge Color Rutkantsfärg Tile Edge Color… Rutkantsfärg… Tile Full Pages Dela upp i hela sidor diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index b23fc994a9..7f86184a60 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -421,6 +421,17 @@ fn built_in_library_brush_names_are_in_complete_catalogs() { assert!(bad.is_empty(), "{}", bad.join("\n")); } +/// Window › Arrange's Tile layouts and the application bar's Arrange Documents button. +#[test] +fn tile_layout_labels_are_in_complete_catalogs() { + for lang in LANGUAGES.iter().filter(|lang| lang.complete_menus) { + for label in ["Tile All Vertically", "Tile All Horizontally", "2-Up Layout", "3-Up Layout", "4-Up Layout", "6-Up Layout", "Arrange Documents"] + { + assert!(lang.catalog().plain(label).is_some(), "{} is missing {label}", lang.code); + } + } +} + /// Preference choices and the marquee's E hint share the same translated labels. #[test] fn marquee_selection_labels_are_in_complete_catalogs() { diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index e5278e58c6..9096a2d401 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -3519,6 +3519,13 @@ digits Malayalam Malayalam Thumbnail View Küçük Resim Görünümü Thumbnails: Küçük resimler: Tile Fayans + Tile All Vertically Tümünü Dikey Fayans + Tile All Horizontally Tümünü Yatay Fayans + 2-Up Layout 2'li Düzen + 3-Up Layout 3'lü Düzen + 4-Up Layout 4'lü Düzen + 6-Up Layout 6'lı Düzen + Arrange Documents Belgeleri Düzenle Tile Edge Color Döşeme Kenar Rengi Tile Edge Color… Döşeme Kenar Rengi… Tile Full Pages Tam Sayfaları Döşe diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 160d9a2c09..c01d0a2141 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -3773,6 +3773,13 @@ effect Points Точки Thumbnail View Мініатюри Thumbnails: Мініатюри: Tile Плитка + Tile All Vertically Усі плиткою вертикально + Tile All Horizontally Усі плиткою горизонтально + 2-Up Layout Макет на 2 + 3-Up Layout Макет на 3 + 4-Up Layout Макет на 4 + 6-Up Layout Макет на 6 + Arrange Documents Упорядкувати документи Tile Edge Color Колір краю плитки Tile Edge Color… Колір краю плитки… Tile Full Pages Плитка цілих сторінок diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 45312793f3..66942a71d3 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -4130,6 +4130,13 @@ mark-style Japanese Kiểu Nhật Thumbnail View Dạng xem hình thu nhỏ Thumbnails: Hình thu nhỏ: Tile Ô + Tile All Vertically Xếp tất cả theo chiều dọc + Tile All Horizontally Xếp tất cả theo chiều ngang + 2-Up Layout Bố cục 2 + 3-Up Layout Bố cục 3 + 4-Up Layout Bố cục 4 + 6-Up Layout Bố cục 6 + Arrange Documents Sắp xếp tài liệu Tile Edge Color Màu cạnh ô Tile Edge Color… Màu cạnh ô… Tile Full Pages Ô toàn trang diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 0b3c38c9ca..a9f4e1d7e0 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -3594,6 +3594,13 @@ digits Malayalam 马拉雅拉姆数字 Threshold 阈值 Thumbnail View 缩略图视图 Tile 平铺 + Tile All Vertically 全部垂直平铺 + Tile All Horizontally 全部水平平铺 + 2-Up Layout 双联布局 + 3-Up Layout 三联布局 + 4-Up Layout 四联布局 + 6-Up Layout 六联布局 + Arrange Documents 排列文档 Tile Edge Color 拼贴边缘颜色 Tile Edge Color… 拼贴边缘颜色… Tile Full Pages 并排完整页面 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 4c8b7f2d3e..d63d2a05fc 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -4853,6 +4853,13 @@ digits Malayalam 馬來亞拉姆數字 Thumbnail View 縮圖檢視 Thumbnails: 縮圖: Tile 並排顯示 + Tile All Vertically 全部垂直並排顯示 + Tile All Horizontally 全部水平並排顯示 + 2-Up Layout 雙聯版面 + 3-Up Layout 三聯版面 + 4-Up Layout 四聯版面 + 6-Up Layout 六聯版面 + Arrange Documents 排列文件 Tile Edge Color 拼貼邊緣顏色 Tile Edge Color… 拼貼邊緣顏色… Tile Full Pages 並排完整頁面 diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 4e2d80bb45..8cb75fdae9 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -80,6 +80,7 @@ pub(crate) use run::{normalize_panel, opt_bool, opt_index, opt_number}; use slots::RECENT_FONT_IDS; pub use state::{checked, enabled, plugin_revision, shortcut_of, shown_state}; pub(crate) use submenus::PATH_EFFECTS; +pub(crate) use tree::arrange_documents_items; pub use tree::{menu_tree, menu_tree_named}; pub use ui_commands::UI_COMMANDS; diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index 7b7f7a6b21..4be65589c9 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -671,7 +671,7 @@ fn run_ui_part6(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option crate::doc_windows::new_window(app), "window.arrange.cascade" => crate::doc_windows::cascade(app), - "window.arrange.tile" => crate::canvas::tile(app), + "window.arrange.tile" => crate::canvas::tile(app, p), "window.arrange.floatInWindow" => crate::doc_windows::float_in_window(app, p), "window.arrange.floatAllInWindows" => crate::doc_windows::float_all(app), "window.arrange.consolidateAllWindows" if p.get("index").is_some_and(|i| !i.is_null()) => crate::doc_windows::dock(app, p), diff --git a/crates/ui-egui/src/menus/state.rs b/crates/ui-egui/src/menus/state.rs index 0d5775ffe9..5f76ce6efd 100644 --- a/crates/ui-egui/src/menus/state.rs +++ b/crates/ui-egui/src/menus/state.rs @@ -98,6 +98,8 @@ pub fn checked(app: &VectorcraftApp, id: &str, p: &Value) -> Option { } "window.collapseDock" => crate::panel_docking::dock_collapsed(&app.ui), "window.workspace" => p.get("name").and_then(Value::as_str) == Some(app.ui.workspace.as_str()), + // The Tile layout the panes show. + "window.arrange.tile" => app.ui.tiled && crate::canvas::TileLayout::from_params(p) == Ok(app.ui.tile_layout), "window.brightness" => p.get("brightness").and_then(Value::as_str).and_then(Brightness::parse) == Some(app.ui.brightness), "view.slices.lock" => app.session.slices_locked(), "object.slice.clipToArtboard" => app.session.active().is_some_and(|d| d.doc.slices_clip_to_artboard), diff --git a/crates/ui-egui/src/menus/tree.rs b/crates/ui-egui/src/menus/tree.rs index 4b86b4152d..2f93db6520 100644 --- a/crates/ui-egui/src/menus/tree.rs +++ b/crates/ui-egui/src/menus/tree.rs @@ -631,16 +631,16 @@ pub fn menu_tree_named(english_names: bool) -> Vec<(&'static str, Vec)> { ("Window", { let mut window_items = vec![ c("New Window", "window.newWindow"), - sub( - "Arrange", - vec![ - c("Cascade", "window.arrange.cascade"), - c("Tile", "window.arrange.tile"), + sub("Arrange", { + let mut arrange = vec![c("Cascade", "window.arrange.cascade")]; + arrange.extend(tile_items()); + arrange.extend([ c("Float in Window", "window.arrange.floatInWindow"), c("Float All in Windows", "window.arrange.floatAllInWindows"), c("Consolidate All Windows", "window.arrange.consolidateAllWindows"), - ], - ), + ]); + arrange + }), sub("Workspace", crate::workspaces::menu_items()), Sep, c("Control", "window.control"), @@ -755,6 +755,27 @@ pub(super) fn transform_items() -> Vec { ] } +/// Window → Arrange's Tile layouts, one `window.arrange.tile` `layout` each (also under the +/// application bar's Arrange Documents button). +fn tile_items() -> Vec { + vec![ + c("Tile", "window.arrange.tile"), + cp("Tile All Vertically", "window.arrange.tile", json!({"layout": "vertical"})), + cp("Tile All Horizontally", "window.arrange.tile", json!({"layout": "horizontal"})), + cp("2-Up Layout", "window.arrange.tile", json!({"layout": "2up"})), + cp("3-Up Layout", "window.arrange.tile", json!({"layout": "3up"})), + cp("4-Up Layout", "window.arrange.tile", json!({"layout": "4up"})), + cp("6-Up Layout", "window.arrange.tile", json!({"layout": "6up"})), + ] +} + +/// The application bar's Arrange Documents menu: Consolidate All Windows, then the Tile layouts. +pub(crate) fn arrange_documents_items() -> Vec { + let mut items = vec![c("Consolidate All Windows", "window.arrange.consolidateAllWindows"), Sep]; + items.extend(tile_items()); + items +} + /// Object → Arrange (also in the canvas context menu). pub(super) fn arrange_items() -> Vec { vec![ diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 21b8795662..e54b366be3 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -769,7 +769,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "window.arrange.tile", "Tile", "", - "{} show every open document and each further view of one (window.newWindow) at once, edge to edge in the document area, one pane each in a grid (columns: the square root of the number of panes, rounded up), each fitted to its pane; the current window's pane takes the tools, a click in another pane makes its window the current one; the tabs stay; windows floating come back under the tabs first; with fewer than two windows open the view stays as it is; returns {tiled, panes}", + "{layout?: grid|vertical|horizontal|2up|3up|4up|6up} show the open documents and each further view of one (window.newWindow) at once, edge to edge in the document area, one pane each, each fitted to its pane: `grid` (the default) in a grid (columns: the square root of the number of panes, rounded up), `vertical` side by side in one row (Tile All Vertically), `horizontal` stacked in one column (Tile All Horizontally), `2up`, `3up`, `4up` and `6up` at most that many panes (2up and 3up side by side, 4up two by two, 6up three by two) with the other windows under their tabs: the first windows in tab order, the current window in the last pane when it is not among them; the current window's pane takes the tools, a click in another pane makes its window the current one; the tabs stay; windows floating come back under the tabs first; with fewer than two windows open the view and the layout stay as they are; any other `layout` is an error; returns {tiled, panes, layout}", ), ( "window.arrange.floatInWindow", diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 80a87b4563..97ffd12af0 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -598,6 +598,10 @@ pub struct UiState { /// Consolidate All Windows. Not saved: the reference app does not save windows with a document. #[serde(skip)] pub tiled: bool, + /// How Tile lays the panes out: in a grid, side by side, stacked, or 2-up to 6-up. Not saved, + /// as `tiled` is not. + #[serde(skip)] + pub tile_layout: crate::canvas::TileLayout, /// Window › Arrange › Float in Window, Float All in Windows and Cascade: the documents in /// floating windows of their own, out of the tab strip, until Consolidate All Windows. Not /// saved, as `tiled` is not. @@ -1176,6 +1180,7 @@ impl Default for UiState { palette_query: String::new(), screen_mode: 0, tiled: false, + tile_layout: crate::canvas::TileLayout::Grid, floating: Vec::new(), tab_document: None, draw_mode: 0, diff --git a/docs/mcp.md b/docs/mcp.md index fc03d070b6..550e2249dd 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -6606,14 +6606,20 @@ current, or the one before it when it was the last tab. In the desktop app a mod to ask whether to save it. `window.arrange.tile` (Window › Arrange › Tile) shows every open document in its own pane, edge to edge in the document area, in a grid of as many columns as the square root of the number of documents, rounded up, and fits each document to -its pane; with fewer than two documents open it leaves the view and `tiled` as they are. It returns `{tiled, panes}`. -The current document's pane is the canvas, and a press in another pane makes its document the current one. -`window.arrange.consolidateAllWindows` (Window › Arrange › Consolidate All Windows) shows one document under its tab -again and returns `{tiled: false}`. The arrangement is not saved. `ui.inspect` reports `tiled` and `panes` (each pane's -`document` index, `rect` and whether it is `active`); canvas coordinates map to the current document's pane -(`canvasRect`). -its pane; it returns `{tiled, panes}`. The current document's pane is the canvas, and a press in another pane makes its -document the current one. `window.arrange.floatInWindow` (Window › Arrange › Float in Window) moves the current document +its pane; with fewer than two documents open it leaves the view, `tiled` and the layout as they are. It returns +`{tiled, panes, layout}`. `window.arrange.tile {layout}` picks another layout, as the other Tile items of Window › +Arrange and of the application bar's Arrange Documents button do: `grid` (the default), `vertical` (Tile All +Vertically: side by side in one row), `horizontal` (Tile All Horizontally: stacked in one column), and `2up`, `3up`, +`4up` and `6up`, which show at most that many documents (2-Up and 3-Up side by side, 4-Up two by two, 6-Up three by +two) and leave the others under their tabs. Those layouts show the first documents in tab order, and the current +document takes the last pane when it is not among them, so a click on another tab brings that document into the last +pane. Any other `layout` is an error, and the view stays as it is. The set of layouts and how each one places the panes +are VectorCraft's own. The current document's pane is the canvas, and a press in another pane makes its document the +current one. `window.arrange.consolidateAllWindows` (Window › Arrange › Consolidate All Windows, also first in Arrange +Documents) shows one document under its tab again and returns `{tiled: false}`. The arrangement is not saved. +`ui.inspect` reports `tiled`, `tileLayout` and `panes` (each pane's `document` index, `rect` and whether it is +`active`); canvas coordinates map to the current document's pane (`canvasRect`). +`window.arrange.floatInWindow` (Window › Arrange › Float in Window) moves the current document out of the tab strip into a floating window of its own, `window.arrange.floatAllInWindows` (Float All in Windows) does so for every tabbed document, and `window.arrange.cascade` (Cascade) floats every document and stacks the windows 30 pt apart from the upper left of the document area; each returns `{floating}`, the floating documents' indices. On the diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 0a1f7c81b8..51d04da8c8 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -724,6 +724,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Fade Region Outside Artboard:** Artboard Options' Global checkboxes Fade Region Outside Artboard and Update While Dragging ([user guide, Artboard options](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf)) are application preferences (`fadeRegionOutsideArtboard`, `artboardUpdateWhileDragging`), both on by default. While the Artboard tool is active the canvas draws everything outside the artboards, the pasteboard and the art on it, with each color channel at 60% of its value (VectorCraft's own amount), or only outside the box around all the artboards when crossing artboards would leave more than 4,096 rectangles in view; with Update While Dragging off it draws as usual during an artboard move or resize. Presentation Mode, exports and print do not change. Regression tests: `canvas::tests` (`the_artboard_tool_fades_the_pasteboard`, `presentation_mode_draws_no_fade`, `the_fade_darkens_art_on_the_pasteboard_and_not_on_the_artboard`, `outside_rects_cover_the_bounds_minus_the_boards`, `outside_rects_of_a_row_of_boards_stay_few`, `the_fade_of_crossing_boards_stays_bounded`, `update_while_dragging_keeps_or_drops_the_fade_during_an_artboard_drag`, `the_pasteboard_fade_leaves_exports_unchanged`), `dialogs/tests.rs` (`artboard_options_global_checkboxes_set_the_preferences`, `artboard_options_error_leaves_the_global_preferences_unchanged`). - **Saved views (G7):** View › New View… and Edit Views… ([public source](https://helpx.adobe.com/illustrator/using/viewing-artwork.html): up to 25 views per document, saved with it, renamed or deleted in Edit Views, chosen from the bottom of the View menu). Each view keeps the zoom, centre and rotation; the View menu lists all 25 (`view.goto1`–`view.goto25`), and Edit Views… lists them to rename or delete, applied together as one undo step. A file's views are checked when it opens (at most 25, unique names up to 255 characters, a finite centre and a positive zoom). Tests: `saved_views_round_trip_and_from_a_file_are_tidied` (`crates/format/tests/prop_format.rs`), `crates/engine/src/cmd/views.rs`, `crates/ui-egui/src/dialogs/edit_views.rs` and `every_saved_view_is_listed_at_the_bottom_of_the_view_menu` (`crates/ui-egui/src/menus.rs`). - **Window › Arrange › Tile (G7):** Tile (`window.arrange.tile`) shows every open document at once, edge to edge in the document area ([public source](https://helpx.adobe.com/illustrator/using/viewing-artwork.html)), one pane each in a grid of as many columns as the square root of the number of documents, rounded up, each fitted to its pane. The current document's pane is the canvas; the other panes draw their documents with their artboards, guides and selected objects, and a press in one makes its document the current one. Consolidate All Windows (`window.arrange.consolidateAllWindows`) shows one document under its tab again. The grid and when the two items are enabled (Tile with two documents or more, Consolidate All Windows while they are tiled) are VectorCraft's own. Tests: `crates/ui-egui/src/canvas/panes/tests.rs`. +- **Arrange Documents (G7):** the application bar's Arrange Documents button arranges the open documents in grid and tile layouts ([public source](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/workspace-overview.html)). Its menu, and Window › Arrange, have Consolidate All Windows, Tile (the grid), Tile All Vertically (side by side), Tile All Horizontally (stacked) and the 2-Up, 3-Up, 4-Up and 6-Up layouts, which show that many documents and leave the others under their tabs, the current one in the last pane (`window.arrange.tile {layout}`). The set of layouts and how each places the panes are VectorCraft's own. Tests: `crates/ui-egui/src/canvas/panes/tests.rs`. - **Window › Arrange › Float in Window, Float All in Windows and Cascade (G7):** documents float in windows of their own, out of the tab strip ([public source](https://helpx.adobe.com/illustrator/using/customizing-workspace.html)). Float in Window (`window.arrange.floatInWindow`) floats the current document, Float All in Windows (`window.arrange.floatAllInWindows`) every tabbed one, and Cascade (`window.arrange.cascade`) floats every document and stacks the windows from the upper left to the lower right ([public source](https://helpx.adobe.com/illustrator/using/viewing-artwork.html)). On the desktop each window is an OS window; on the web and on Wayland it is a window inside the app's window. The window of the current document holds the canvas; the others draw their documents as Tile's panes do, and a press in one makes its document the current one. Closing a window closes its document, asking to save unsaved changes. Consolidate All Windows brings every document back under the tabs, and Tile brings them back into its grid. The cascade's 30 pt step, the windows' size and when the items are enabled (Cascade with two documents or more, Float in Window for a tabbed current document, Float All in Windows while a document is tabbed, Consolidate All Windows while documents are tiled or floating) are VectorCraft's own. Tests: `crates/ui-egui/src/doc_windows/tests.rs`. - **Dragging a document tab out and a document window back (G7):** a document tab dragged more than 24 pt above or below the tab strip floats its document in a window under the pointer, and a document window dragged onto the tab strip goes back under the tabs ([public source](https://helpx.adobe.com/illustrator/using/customizing-workspace.html)). A window inside the app's window is dragged by its title bar; an OS window by the document's tab at its top, and the window follows the pointer. The 24 pt distance and the tab at the top of an OS window are VectorCraft's own. Tests: `crates/ui-egui/src/doc_windows/tests.rs`. - **Reordering document tabs (G7, #5663):** a document tab dragged along the tab strip moves its document among the others ([public source](https://helpx.adobe.com/illustrator/using/customizing-workspace.html)); a line marks the gap it goes in. The current document stays current, each document keeps its own zoom, centre and artboard, the views Window › New Window opened move with their document, and Window › Next/Previous Document follow the new order. `document.move` (`{from?, to}`) does the same from MCP, the control channel and recordings. `crates/ui-egui/src/tests/tab_reorder.rs`, `crates/engine/src/tests/document_move.rs`. From 40e1a80d5cdfce1feb7a1c1a8d8c8ed49b40180f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 16:26:11 -0800 Subject: [PATCH 044/176] Window: a document that keeps its pane keeps its zoom when another closes Panes refit a view when its slot or its place in the layout changes, not when the number of panes changes. Closing the sixth document in 6-Up leaves the other five in their panes with their zoom and scroll; side by side and stacked, every pane changes size and each document fits its new pane. --- crates/ui-egui/src/canvas/panes.rs | 16 +++++++----- crates/ui-egui/src/canvas/panes/tests.rs | 33 ++++++++++++++++++++++++ 2 files changed, 42 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/canvas/panes.rs b/crates/ui-egui/src/canvas/panes.rs index 6b8eea9440..703c6b46bd 100644 --- a/crates/ui-egui/src/canvas/panes.rs +++ b/crates/ui-egui/src/canvas/panes.rs @@ -322,16 +322,18 @@ pub(crate) fn tiled_area(app: &mut VectorcraftApp, ui: &mut Ui) -> bool { app.canvas.panes.shown.retain(|s, _| live.contains(s)); app.canvas.panes.pending.retain(|s, _| live.contains(s)); app.canvas.panes.fits.retain(|s, _| live.contains(s)); - // A window opened, closed, floated or docked changes the panes, and so does coming back to the - // panes from one window: each window fits its new pane. With as many panes as before, only a - // window that moved to another pane fits it, as when a tab brings its window into the last pane - // of a 2-up to 6-up layout: the others keep their zoom and scroll. Windows are compared by - // their slots, since a closed document shifts the indices of the documents after it. + // A window that moved to another pane fits it, and so does a window whose pane changed place or + // size because a window opened, closed, floated or docked, or because the panes came back from + // one window. A window that keeps its pane keeps its zoom and scroll, as when a tab brings its + // window into the last pane of a 2-up to 6-up layout, or when 6-Up loses its sixth document. + // Windows are compared by their slots, since a closed document shifts the indices of the + // documents after it, and panes by their place in the layout. let before = std::mem::take(&mut app.canvas.panes.last_slots); let now: Vec> = shown.iter().map(|w| slot(app, *w)).collect(); - let same_panes = before.len() == now.len(); + let unit = egui::Rect::from_min_size(pos2(0.0, 0.0), vec2(1.0, 1.0)); + let (cells_before, cells_now) = (layout_cells(layout, before.len(), unit), layout_cells(layout, now.len(), unit)); for (i, (w, s)) in shown.iter().zip(&now).enumerate() { - if same_panes && s.is_some() && before.get(i) == Some(s) { + if s.is_some() && before.get(i) == Some(s) && cells_before.get(i) == cells_now.get(i) { continue; } if let Some(v) = crate::doc_windows::view_mut(app, *w) { diff --git a/crates/ui-egui/src/canvas/panes/tests.rs b/crates/ui-egui/src/canvas/panes/tests.rs index 2ad0af3dc1..1fcbd7cc61 100644 --- a/crates/ui-egui/src/canvas/panes/tests.rs +++ b/crates/ui-egui/src/canvas/panes/tests.rs @@ -232,6 +232,39 @@ fn closing_a_document_in_an_n_up_layout_fits_the_documents_that_change_panes() { assert!(v.fitted && (v.zoom - fit_zoom(area, Rect::new(0.0, 0.0, 400.0, 300.0), 0.0, 1.0)).abs() < 1e-9, "it fits its new pane: {v:?}"); } +/// 6-Up keeps its three columns and two rows with five documents: closing the sixth leaves the +/// others in their panes with the zoom they had. Side by side, closing one widens every pane, and +/// each document fits its new pane. +#[test] +fn closing_a_document_keeps_the_zoom_of_the_documents_whose_panes_stay() { + let mut app = app_with(6); + let ctx = egui::Context::default(); + app.run("document.activate", json!({"index": 0})).unwrap(); + app.run("window.arrange.tile", json!({"layout": "6up"})).unwrap(); + frame(&mut app, &ctx, vec![]); + assert_eq!(panes(&app).0, [0, 1, 2, 3, 4, 5]); + app.views[1].zoom *= 2.0; + let zoomed = app.views[1].zoom; + app.run("file.close", json!({"index": 5})).unwrap(); + frame(&mut app, &ctx, vec![]); + let (docs, rects) = panes(&app); + assert_eq!((docs, columns_and_rows(&rects)), (vec![0, 1, 2, 3, 4], (3, 2))); + assert_eq!(app.views[1].zoom, zoomed, "the document that kept its pane keeps its zoom"); + + let mut app = app_with(3); + app.run("document.activate", json!({"index": 0})).unwrap(); + app.run("window.arrange.tile", json!({"layout": "vertical"})).unwrap(); + frame(&mut app, &ctx, vec![]); + app.views[1].zoom *= 2.0; + app.run("file.close", json!({"index": 2})).unwrap(); + frame(&mut app, &ctx, vec![]); + let (docs, rects) = panes(&app); + assert_eq!(docs, [0, 1]); + let area = view_rects(&app, rects[1], ctx.pixels_per_point()).1; + let v = app.views[1]; + assert!(v.fitted && (v.zoom - fit_zoom(area, Rect::new(0.0, 0.0, 400.0, 300.0), 0.0, 1.0)).abs() < 1e-9, "it fits its wider pane: {v:?}"); +} + #[test] fn tile_refuses_a_layout_it_does_not_have() { let mut app = app_with(3); From 02351b0105c30c98d9e6e1122b49abd9769cfb12 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 16:45:34 -0800 Subject: [PATCH 045/176] Window: a narrow application bar drops Arrange Documents before the search icon The search icon takes the first icon slot beside the workspace switcher, as before Arrange Documents was added; Arrange Documents shows only when a second slot fits. --- crates/ui-egui/src/canvas/panes/tests.rs | 26 +++++++++++++++++++++++- crates/ui-egui/src/chrome.rs | 14 ++++++------- 2 files changed, 32 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/src/canvas/panes/tests.rs b/crates/ui-egui/src/canvas/panes/tests.rs index 1fcbd7cc61..e3da1a6a60 100644 --- a/crates/ui-egui/src/canvas/panes/tests.rs +++ b/crates/ui-egui/src/canvas/panes/tests.rs @@ -341,7 +341,12 @@ fn the_tile_items_check_the_layout_the_panes_show() { /// One frame of the application bar with screen-reader nodes on → the nodes. fn app_bar_frame(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec) -> Vec { - let screen = egui::Rect::from_min_size(Pos2::ZERO, vec2(1400.0, 800.0)); + app_bar_frame_in(app, ctx, events, 1400.0) +} + +/// [`app_bar_frame`] on a window `width` points wide. +fn app_bar_frame_in(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec, width: f32) -> Vec { + let screen = egui::Rect::from_min_size(Pos2::ZERO, vec2(width, 800.0)); let mut out = ctx.run_ui(egui::RawInput { events, screen_rect: Some(screen), ..Default::default() }, |ui| crate::chrome::app_bar(app, ui)); out.textures_delta.clear(); out.platform_output.accesskit_update.map(|u| u.nodes.into_iter().map(|(_, n)| n).collect()).unwrap_or_default() @@ -395,6 +400,25 @@ fn the_arrange_documents_button_tiles_and_consolidates() { assert!(!app.ui.tiled); } +/// As the application bar narrows, Arrange Documents goes before the search icon. +#[test] +fn a_narrow_application_bar_keeps_search_before_arrange_documents() { + crate::i18n::set_current(crate::i18n::Lang::EN); + let mut app = app_with(3); + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + crate::theme::install_fonts(&ctx); + let mut search_alone = false; + for width in (200..=1400).rev().step_by(4) { + app_bar_frame_in(&mut app, &ctx, vec![], width as f32); + let nodes = app_bar_frame_in(&mut app, &ctx, vec![], width as f32); + let (arrange, search) = (app_bar_node(&nodes, "Arrange Documents").is_some(), app_bar_node(&nodes, "Search commands and tools").is_some()); + assert!(search || !arrange, "{width} pt: Arrange Documents shows without the search icon"); + search_alone |= search && !arrange; + } + assert!(search_alone, "some width shows the search icon without Arrange Documents"); +} + #[test] fn tile_shows_a_pane_for_each_document_fitted_to_it() { let mut app = app_with(3); diff --git a/crates/ui-egui/src/chrome.rs b/crates/ui-egui/src/chrome.rs index 96b4d12965..989cebadc0 100644 --- a/crates/ui-egui/src/chrome.rs +++ b/crates/ui-egui/src/chrome.rs @@ -84,8 +84,8 @@ pub fn app_bar(app: &mut VectorcraftApp, ui: &mut Ui) { let menus_end = if app.services.native_menu.is_some() { ui.cursor().min.x } else { menus::menu_bar(app, ui) }; // The right-side group fills the space after the menus from the right; when it runs // short, Discord goes first (it is also under Help), then Explore tutorials (also - // Window › Learn), then the search icon (the palette stays under its shortcut), then - // Arrange Documents (also Window › Arrange), then the workspace switcher narrows. + // Window › Learn), then Arrange Documents (also Window › Arrange), then the search icon + // (the palette stays under its shortcut), then the workspace switcher narrows. let full = ui.max_rect(); let right_edge = if captions_right > 0.0 { full.right() - captions_right - 10.0 } else { full.right() }; let right = egui::Rect::from_min_max(egui::pos2(menus_end + 8.0, full.top()), egui::pos2(right_edge, full.bottom())); @@ -105,15 +105,15 @@ pub fn app_bar(app: &mut VectorcraftApp, ui: &mut Ui) { let ws = ui.painter().layout_no_wrap(ws_name, egui::FontId::proportional(12.0), t.text); let ws_w = (ws.size().x + 36.0).clamp(112.0, 190.0); let gap = ui.spacing().item_spacing.x; - // Arrange Documents, beside the switcher, then the search icon, as in PhotoCraft: each - // shown while a minimal switcher fits beside it. + // The search icon, as in PhotoCraft, then Arrange Documents between it and the switcher: + // each shown while a minimal switcher fits beside it. let icon = 28.0; - let arrange = switcher && room >= 64.0 + 8.0 + gap + icon; - let search = arrange && room >= 64.0 + 8.0 + 2.0 * (gap + icon); + let search = switcher && room >= 64.0 + 8.0 + gap + icon; + let arrange = search && room >= 64.0 + 8.0 + 2.0 * (gap + icon); let icons = f32::from(u8::from(arrange) + u8::from(search)); let ws_w = ws_w.min(room - 8.0 - icons * (gap + icon)).max(64.0); // Explore tutorials, beside the search icon, opens the Learn panel. - let learn = search && room >= ws_w + 8.0 + 3.0 * (gap + icon); + let learn = arrange && room >= ws_w + 8.0 + 3.0 * (gap + icon); let discord = learn && room >= ws_w + 8.0 + 3.0 * (gap + icon) + 10.0 + gap + crate::community::discord_width(ui, false); let mut rui = ui.new_child(egui::UiBuilder::new().max_rect(right).layout(egui::Layout::right_to_left(egui::Align::Center))); let ui = &mut rui; From 5bc67b464250bcb6a206d46e8f5f3a05ed2346d6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 18:05:05 -0800 Subject: [PATCH 046/176] Export: painted clipping type keeps its fill and stroke under a group's geometry effect When a geometry effect on a group outlined type used as a clipping path, the type became a plain outline group, which paints nothing as a clipping path, so its fill and stroke were missing from the canvas and from SVG and PDF export. The clip group now becomes the type's outlines as the clipping path, the type's fills as art behind the clipped members inside the clip and, when it strokes, its strokes as art over the clip group, outside the clip. The group's effect reshapes all three alike. Unpainted clipping type still gives only the clip. A clip group with fills of its own keeps painting them inside the clip. --- crates/effects/src/bake.rs | 8 +- crates/effects/src/group.rs | 14 ++- crates/effects/src/reshape.rs | 49 ++++++++++- crates/effects/src/tests/clipfx.rs | 122 ++++++++++++++++++++++++++ crates/pdf/src/tests/fx.rs | 57 +++++++++++- crates/svg/tests/it/effects_export.rs | 49 +++++++++++ docs/target-app-parity.md | 2 +- 7 files changed, 290 insertions(+), 11 deletions(-) diff --git a/crates/effects/src/bake.rs b/crates/effects/src/bake.rs index 54d97a4527..05e9600425 100644 --- a/crates/effects/src/bake.rs +++ b/crates/effects/src/bake.rs @@ -27,7 +27,9 @@ use vectorcraft_geom::{Affine, FillRule, PathData, Rect, Vec2}; use crate::distort::{transform_move, transform_offsets}; use crate::group::{has_own_paint, paints}; -use crate::reshape::{as_art, clipping_text_outline, dressed, geometry_effects, glyph_outlines, outline_nested_text, reshape_leaves}; +use crate::reshape::{ + as_art, clipping_text_outline, dressed, geometry_effects, glyph_outlines, outline_nested_text, painted_type_clip, reshape_leaves, +}; use crate::{ GeomContext, adjust_in_document, apply_geometry_carrying, crop_marks_art, evaluate_container, has_adjustment, has_crop_marks, has_geometry, has_instance_row_raster, has_item_geometry, has_pathfinder, is_pathfinder, merged_params, needs_outline, reshape, @@ -689,6 +691,10 @@ fn moved_type_group(n: &Node) -> Option { /// them. `None` when no type stays type. fn container_keeping_type(d: &Document, n: &Node) -> Option { fn keep(d: &Document, n: &mut Node, moves: &[serde_json::Value], clipping: bool, kept: &mut bool) { + // Clipping type that paints becomes the art of its fills and strokes around the clip. + if !clipping && let Some(painted) = painted_type_clip(Some(d), n) { + *n = painted; + } let clips = n.clips(); let Some(ch) = n.children_mut() else { return }; for (i, c) in ch.iter_mut().enumerate() { diff --git a/crates/effects/src/group.rs b/crates/effects/src/group.rs index 1b64971a3a..73684a008f 100644 --- a/crates/effects/src/group.rs +++ b/crates/effects/src/group.rs @@ -879,14 +879,22 @@ pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option { m.appearance.effects = crate::raster::without_geometry(&m.appearance.effects); m.appearance.effects.retain(|e| !is_pathfinder(&e.id)); if paint { - let shapes = member_shapes(doc, &m); + // A clip group whose clipping type paints strokes is now a group of a clip group and those + // strokes ([`crate::reshape::painted_type_clip`]): its own fills and strokes paint inside + // that clip group. + let wrapped = n.clips() && !m.clips(); + let shapes = match m.children().and_then(|ch| ch.first()).filter(|_| wrapped) { + Some(inner) => member_shapes(doc, inner), + None => member_shapes(doc, &m), + }; let bounds = m.geometric_bounds(); let art = |items: &[AppearanceItem]| -> Vec> { items.iter().filter_map(|i| item_art(n.id, i, &shapes, bounds)).map(Arc::new).collect() }; let (below, above) = m.appearance.split_contents(); let (below, above) = (art(below), art(above)); - let at = usize::from(m.clips()); - if let Some(ch) = m.children_mut() { + let at = usize::from(n.clips()); + let target = if wrapped { m.children_mut().and_then(|ch| ch.first_mut()).map(Arc::make_mut) } else { Some(&mut m) }; + if let Some(ch) = target.and_then(Node::children_mut) { let at = at.min(ch.len()); ch.splice(at..at, below); ch.extend(above); diff --git a/crates/effects/src/reshape.rs b/crates/effects/src/reshape.rs index 70e5994cb5..376a1f8ba8 100644 --- a/crates/effects/src/reshape.rs +++ b/crates/effects/src/reshape.rs @@ -744,11 +744,56 @@ pub(crate) fn clipping_text_outline(t: &Node) -> Option { Some(Node { visible: t.visible, ..o }) } +/// Clip group or clipping layer `n` whose clipping path is type that paints ([`Node::clip_paint`]), +/// with that type as plain art drawn as the renderer draws it: its outlines clip +/// ([`clipping_text_outline`]), its fills become art behind the clipped members inside the clip, +/// and its strokes become art over the clip group, outside the clip. Each part is the type's art +/// with only those fills or strokes ([`as_art`]), its own geometry effects applied. With strokes, +/// `n` becomes a group with its id, name, visibility and transparency that holds a clip group of +/// the clipping path, the fills and the members, then the strokes; a clipping layer keeps its +/// ruler guides last. `None` when `n` does not clip, its clipping path is not type, or the type +/// paints nothing. +pub(crate) fn painted_type_clip(doc: Option<&Document>, n: &Node) -> Option { + let first = n.children()?.first().filter(|_| n.clips())?; + if !matches!(first.kind, NodeKind::Text(_)) { + return None; + } + let paint = first.clip_paint(); + if paint.fill.is_none() && paint.stroke.is_none() { + return None; + } + let clip = clipping_text_outline(first)?; + let fill = paint.fill.and_then(|p| as_art(doc, &p, None)); + let stroke = paint.stroke.and_then(|p| as_art(doc, &p, None)); + let mut m = n.clone(); + let ch = m.children_mut()?; + *ch.first_mut()? = Arc::new(clip); + if let Some(fill) = fill { + ch.insert(1, Arc::new(fill)); + } + let Some(stroke) = stroke else { return Some(m) }; + let guides = ch.split_off(Node::guide_run_start(ch)); + let inner = Node::new(n.id, NodeKind::Group { children: std::mem::take(ch), clip: true }); + match &mut m.kind { + NodeKind::Group { children, clip } | NodeKind::Layer { children, clip, .. } => { + *children = [Arc::new(inner), Arc::new(stroke)].into_iter().chain(guides).collect(); + *clip = false; + } + _ => return None, + } + Some(m) +} + /// Replace type anywhere inside `n` by its outlines, as art that keeps the type's look /// ([`as_art`]). Type in a clip group's clipping path (all of `n` when `clipping` is set) becomes -/// its outlines with its visibility and effects ([`clipping_text_outline`]). The swatches and -/// patterns that live-effect plug-ins painting their pieces name are looked up in `doc`. +/// its outlines with its visibility and effects ([`clipping_text_outline`]); when it paints, the +/// clip group becomes its art with the type's fills and strokes ([`painted_type_clip`]). The +/// swatches and patterns that live-effect plug-ins painting their pieces name are looked up in +/// `doc`. pub(crate) fn outline_nested_text(doc: Option<&Document>, n: &mut Node, clipping: bool) { + if !clipping && let Some(painted) = painted_type_clip(doc, n) { + *n = painted; + } let clips = n.clips(); let Some(ch) = n.children_mut() else { return }; for (i, c) in ch.iter_mut().enumerate() { diff --git a/crates/effects/src/tests/clipfx.rs b/crates/effects/src/tests/clipfx.rs index bf63df61ab..4a795236e3 100644 --- a/crates/effects/src/tests/clipfx.rs +++ b/crates/effects/src/tests/clipfx.rs @@ -441,3 +441,125 @@ fn raster_and_hidden_effects_leave_the_clip_as_it_is() { assert_eq!(bounds(&clipping_path(1, effects)), Rect::new(50.0, 50.0, 150.0, 150.0)); } } + +fn blue() -> Paint { + Paint::solid(Color::rgb(0.0, 0.0, 1.0)) +} + +fn green() -> Paint { + Paint::solid(Color::rgb(0.0, 1.0, 0.0)) +} + +/// "IIII" at 40 pt from (5, 60) in a test font built from the bundled Source Sans 3 +/// ([`vectorcraft_text::test_fonts::height_font`]), its characters filled blue when `fill` and +/// stroked green 2 pt wide when `stroke`. +fn painted_type(id: u64, fill: bool, stroke: bool) -> Node { + use vectorcraft_doc::text::{CharStyle, TextObject}; + use vectorcraft_text::test_fonts::{HEIGHT_FAMILY, height_font}; + static FONT: std::sync::Once = std::sync::Once::new(); + FONT.call_once(|| { + vectorcraft_text::FontDb::global().add_font(height_font(true).expect("the test font builds")); + }); + let style = CharStyle { + font_family: HEIGHT_FAMILY.into(), + size: 40.0, + fill: if fill { blue() } else { Paint::None }, + stroke: if stroke { green() } else { Paint::None }, + stroke_width: 2.0, + ..Default::default() + }; + Node::new(NodeId(id), NodeKind::Text(Box::new(TextObject::point(vectorcraft_geom::Point::new(5.0, 60.0), "IIII", style)))) +} + +/// Does `n` or an object in it have a blue fill (`fill`) or a green stroke? +fn paints(n: &Node, fill: bool) -> bool { + use vectorcraft_doc::AppearanceItem; + let own = n.appearance.items.iter().any(|i| match i { + AppearanceItem::Fill(f) => fill && f.paint == blue(), + AppearanceItem::Stroke(s) => !fill && s.paint == green() && s.width > 0.0, + }); + own || n.children().into_iter().flatten().any(|c| paints(c, fill)) +} + +/// What the first clip group in `n` paints: the bounds of the region it clips to, the bounds of +/// the blue fill art right after its clipping path (behind the clipped art), the bounds of the +/// green stroke art right after the clip group (over it, outside the clip), and whether a green +/// stroke paints inside the clip group. +type Painted = (Rect, Option, Option, bool); + +fn painted_clip(n: &Node) -> Option { + let ch = n.children()?; + for (i, c) in ch.iter().enumerate() { + if let NodeKind::Group { children, clip: true } = &c.kind { + let region = clip_outline(children.first()?)?.0.bounding_box(); + let fill = children.get(1).filter(|f| paints(f, true)).and_then(|f| f.geometric_bounds()); + let stroke = ch.get(i + 1).filter(|s| paints(s, false)).and_then(|s| s.geometric_bounds()); + let inside = children.iter().skip(1).any(|m| paints(m, false)); + return Some((region, fill, stroke, inside)); + } + if let Some(found) = painted_clip(c) { + return Some(found); + } + } + None +} + +fn near_rect(a: Rect, b: Rect) -> bool { + (a.x0 - b.x0).abs() < 0.5 && (a.y0 - b.y0).abs() < 0.5 && (a.x1 - b.x1).abs() < 0.5 && (a.y1 - b.y1).abs() < 0.5 +} + +#[test] +fn painted_clipping_type_survives_enclosing_geometry_effect() { + // Type that paints a fill, a stroke, both or neither clips a red square, in a group whose + // Transform (moving everything 10 pt down, beside other type that stays type in the export) or + // Offset Path reshapes its members: the canvas and the export keep the type's fill as art + // behind the square inside the clip and its stroke as art over the clip group, both reshaped + // with the clip. + let plain = clip_outline(&painted_type(3, false, false)).expect("the type clips").0.bounding_box(); + assert!(plain.width() > 10.0 && plain.height() > 10.0, "the type has glyph outlines: {plain:?}"); + let effects = [fx("distort.transform", json!({"moveV": 10})), fx("path.offsetPath", json!({"offset": 1}))]; + for effect in effects { + for (fill, stroke) in [(true, false), (false, true), (true, true), (false, false)] { + let clipped = clip_group(2, painted_type(3, fill, stroke)); + let mut outer = Node::group(NodeId(1), vec![Arc::new(clipped), Arc::new(painted_type(5, true, false))]); + outer.appearance.effects.push(effect.clone()); + let canvas = crate::evaluate_container(None, &outer).unwrap(); + let mut d = Document::new(400.0, 400.0); + let layer = d.layers[0].id; + d.insert(Some(layer), 0, outer).unwrap(); + let baked = bake_document(&d).unwrap(); + let exported = baked.layers.iter().find_map(|l| painted_clip(l)); + for (what, found) in [("canvas", painted_clip(&canvas)), ("export", exported)] { + let case = format!("{what}, {}, fill {fill}, stroke {stroke}", effect.id); + let (region, fills, strokes, inside) = found.unwrap_or_else(|| panic!("{case}: no clip group")); + if effect.id == "distort.transform" { + assert!((region.y0 - plain.y0 - 10.0).abs() < 0.5 && (region.x0 - plain.x0).abs() < 0.5, "{case}: {region:?} from {plain:?}"); + } + assert_eq!(fills.is_some(), fill, "{case}: fill art {fills:?}"); + assert_eq!(strokes.is_some(), stroke, "{case}: stroke art {strokes:?}"); + assert!(!inside, "{case}: the stroke paints outside the clip"); + for art in fills.into_iter().chain(strokes) { + assert!(near_rect(art, region), "{case}: the paint {art:?} follows the clip {region:?}"); + } + } + } + } +} + +#[test] +fn a_clip_groups_own_fill_stays_in_the_clip_when_its_clipping_type_strokes() { + // A clip group with a yellow fill of its own and an Offset Path effect, clipped by type that + // strokes: the group's fill still paints inside the clip, and the type's stroke over it. + let yellow = Paint::solid(Color::rgb(1.0, 1.0, 0.0)); + let mut group = clip_group(2, painted_type(3, false, true)); + group.appearance = + Appearance { effects: vec![fx("path.offsetPath", json!({"offset": 0}))], ..Appearance::basic(yellow.clone(), Paint::None, 0.0) }.into(); + let canvas = crate::evaluate_container(None, &group).unwrap(); + let (_, _, strokes, inside) = painted_clip(&Node::group(NodeId(9), vec![Arc::new(canvas.clone())])).unwrap(); + assert!(strokes.is_some() && !inside, "{canvas:?}"); + let NodeKind::Group { children, clip: false } = &canvas.kind else { panic!("not a group around the clip: {canvas:?}") }; + let NodeKind::Group { children: clipped, clip: true } = &children[0].kind else { panic!("no clip group first: {children:?}") }; + let yellow_in = |n: &Node| n.appearance.items.iter().any(|i| matches!(i, vectorcraft_doc::AppearanceItem::Fill(f) if f.paint == yellow)); + assert!(clipped.iter().skip(1).any(|c| yellow_in(c)), "the group's fill paints inside the clip: {clipped:?}"); + assert!(!children.iter().skip(1).any(|c| yellow_in(c)), "{children:?}"); +} diff --git a/crates/pdf/src/tests/fx.rs b/crates/pdf/src/tests/fx.rs index cd73c01bb9..709031a6a2 100644 --- a/crates/pdf/src/tests/fx.rs +++ b/crates/pdf/src/tests/fx.rs @@ -1,9 +1,11 @@ -//! Raster effects in PDF export: not written yet, so a fill's, a stroke's or the object's own -//! raster effect is reported. +//! Effects in PDF export: raster effects are not written yet, so a fill's, a stroke's or the +//! object's own raster effect is reported; geometry effects are baked into what the file draws. + +use std::sync::Arc; use vectorcraft_color::{Color, Paint}; -use vectorcraft_doc::{Appearance, Document, Effect, Node, NodeId}; -use vectorcraft_geom::{Rect, shapes}; +use vectorcraft_doc::{Appearance, AppearanceItem, CharStyle, Document, Effect, Node, NodeId, NodeKind, TextObject}; +use vectorcraft_geom::{Point, Rect, shapes}; use crate::*; @@ -27,3 +29,50 @@ fn raster_effects_warn_on_fills_strokes_and_objects() { assert!(warnings(item).iter().any(|w| w.starts_with("raster effects")), "{item:?}"); } } + +/// What `n` paints, in paint order, with consecutive repeats dropped: 'b' for a blue fill, 'r' for a +/// red fill and 'g' for a green stroke, each with whether a clip group clips it. Clipping paths +/// themselves are left out. +fn painted_order(n: &Node, clipped: bool, out: &mut Vec<(char, bool)>) { + let solid = |p: &Paint, r: f32, g: f32, b: f32| matches!(p, Paint::Solid { color, .. } if *color == Color::rgb(r, g, b)); + for i in &n.appearance.items { + let mark = match i { + AppearanceItem::Fill(f) if solid(&f.paint, 0.0, 0.0, 1.0) => 'b', + AppearanceItem::Fill(f) if solid(&f.paint, 1.0, 0.0, 0.0) => 'r', + AppearanceItem::Stroke(s) if s.width > 0.0 && solid(&s.paint, 0.0, 1.0, 0.0) => 'g', + _ => continue, + }; + if out.last() != Some(&(mark, clipped)) { + out.push((mark, clipped)); + } + } + let clips = matches!(n.kind, NodeKind::Group { clip: true, .. }); + for c in n.children().into_iter().flatten().skip(usize::from(clips)) { + painted_order(c, clipped || clips, out); + } +} + +#[test] +fn painted_clipping_type_exports_with_group_effect() { + // Type filled blue and stroked green clips a red square in a group with an Offset Path effect: + // the PDF paints the type's fill inside the clip behind the square, and its stroke over the + // clipped art, outside the clip. + let blue = Paint::solid(Color::rgb(0.0, 0.0, 1.0)); + let green = Paint::solid(Color::rgb(0.0, 1.0, 0.0)); + let style = CharStyle { size: 40.0, fill: blue, stroke: green, stroke_width: 2.0, ..Default::default() }; + let mut d = Document::new(200.0, 200.0); + let text = Node::new(d.alloc_id(), NodeKind::Text(Box::new(TextObject::point(Point::new(5.0, 60.0), "IIII", style)))); + let red = Appearance::basic(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0); + let square = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 200.0, 200.0)), red); + let clip = Node::new(d.alloc_id(), NodeKind::Group { children: vec![Arc::new(text), Arc::new(square)], clip: true }); + let mut outer = Node::group(d.alloc_id(), vec![Arc::new(clip)]); + outer.appearance.effects.push(Effect { id: "path.offsetPath".into(), params: serde_json::json!({"offset": 1}), visible: true }); + let layer = d.default_layer().unwrap(); + d.insert(Some(layer), 0, outer).unwrap(); + let back = import(&export(&d, &PdfOptions::default()).unwrap()).unwrap(); + let mut order = vec![]; + for l in &back.layers { + painted_order(l, false, &mut order); + } + assert_eq!(order, [('b', true), ('r', true), ('g', false)]); +} diff --git a/crates/svg/tests/it/effects_export.rs b/crates/svg/tests/it/effects_export.rs index c1a19e8d53..9a0f2aaeba 100644 --- a/crates/svg/tests/it/effects_export.rs +++ b/crates/svg/tests/it/effects_export.rs @@ -145,3 +145,52 @@ fn geometry_effects_on_type_export_as_its_reshaped_outlines() { assert!(!svg.contains(") { + use vectorcraft_doc::AppearanceItem; + let solid = |p: &Paint, r: f32, g: f32, b: f32| matches!(p, Paint::Solid { color, .. } if *color == Color::rgb(r, g, b)); + for i in &n.appearance.items { + let mark = match i { + AppearanceItem::Fill(f) if solid(&f.paint, 0.0, 0.0, 1.0) => 'b', + AppearanceItem::Fill(f) if solid(&f.paint, 1.0, 0.0, 0.0) => 'r', + AppearanceItem::Stroke(s) if s.width > 0.0 && solid(&s.paint, 0.0, 1.0, 0.0) => 'g', + _ => continue, + }; + if out.last() != Some(&(mark, clipped)) { + out.push((mark, clipped)); + } + } + let clips = matches!(n.kind, NodeKind::Group { clip: true, .. }); + for c in n.children().into_iter().flatten().skip(usize::from(clips)) { + painted_order(c, clipped || clips, out); + } +} + +#[test] +fn painted_clipping_type_exports_with_group_effect() { + // Type filled blue and stroked green clips a red square in a group with an Offset Path effect: + // the SVG paints the type's fill inside the clip behind the square, and its stroke over the + // clipped art, outside the clip. + let blue = Paint::solid(Color::rgb(0.0, 0.0, 1.0)); + let green = Paint::solid(Color::rgb(0.0, 1.0, 0.0)); + let style = CharStyle { size: 40.0, fill: blue, stroke: green, stroke_width: 2.0, ..Default::default() }; + let mut d = Document::new(200.0, 200.0); + let text = Node::new(d.alloc_id(), NodeKind::Text(Box::new(TextObject::point(Point::new(5.0, 60.0), "IIII", style)))); + let red = Appearance::basic(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0); + let square = Node::path(d.alloc_id(), shapes::rectangle(Rect::new(0.0, 0.0, 200.0, 200.0)), red); + let clip = Node::new(d.alloc_id(), NodeKind::Group { children: vec![std::sync::Arc::new(text), std::sync::Arc::new(square)], clip: true }); + let mut outer = Node::group(d.alloc_id(), vec![std::sync::Arc::new(clip)]); + outer.appearance.effects.push(Effect { params: json!({"offset": 1}), ..fx("path.offsetPath") }); + let l = d.layers[0].id; + d.insert(Some(l), 0, outer).unwrap(); + let svg = export(&d, &ExportOptions::default()); + let back = vectorcraft_svg::import(&svg).unwrap_or_else(|e| panic!("{e}: {svg}")); + let mut order = vec![]; + for layer in &back.layers { + painted_order(layer, false, &mut order); + } + assert_eq!(order, [('b', true), ('r', true), ('g', false)], "{svg}"); +} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 9f3d8b94b8..eeca9638ba 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1644,7 +1644,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Object › Expand Appearance keeps each stroke of a path a stroke (weight, caps, joins, dashes, arrowheads, alignment and width profile) on a copy of the path with the geometry effects baked in, and Object › Expand… is dimmed, with a tooltip, while the selection has appearance attributes, so a stroked line with Zig Zag becomes a stroked zig-zag line and only Expand then outlines it, the two steps the [Expand objects](https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/expand-objects.html) help page describes (#3089). Brushed strokes still become their brush art; `object.expand` still bakes and outlines in one step for agents. - **Masks and clipping:** opacity-mask controls work while the mask is being edited; transparency commands take ids and work without a selection; clipping sets clip by compound paths, even-odd paths, text and groups on screen and in raster export, matching SVG/PDF. Alt-click shows only the mask; SVG masks keep Clip and Invert; the transparency grid is per-document state; a clipping path's own fill and stroke paint behind and over the clipped art; layers can be clipping masks. - **Masks and clipping:** opacity-mask controls work while the mask is being edited; transparency commands take ids and work without a selection; clipping sets clip by compound paths, even-odd paths, text and groups on screen and in raster export, matching SVG/PDF. Alt-click shows only the mask; SVG masks keep Clip and Invert; the transparency grid is per-document view state saved in native files (#1968); a clipping path's own fill and stroke paint behind and over the clipped art; layers can be clipping masks. - The geometry effects of a clipping path (Roughen, Transform and the other effects that reshape a path), of its fills and strokes, and of the members of a group used as one, shape the area it clips to on the canvas and in raster export, as in SVG and PDF export: a roughened clipping path clips by its roughened outline. They apply before the geometry effects of the clip group or of a group around it, on the canvas and in every export. When the clipping path has a fill or stroke of its own, the geometry effects of those fills and strokes apply after the group's geometry effects instead. Type used as a clipping path keeps its geometry effects when a group's effect outlines it. Raster effects such as Gaussian Blur leave that area as it is. `effects::tests::clipfx` and the renderer's `tests::clip` cover it. + The geometry effects of a clipping path (Roughen, Transform and the other effects that reshape a path), of its fills and strokes, and of the members of a group used as one, shape the area it clips to on the canvas and in raster export, as in SVG and PDF export: a roughened clipping path clips by its roughened outline. They apply before the geometry effects of the clip group or of a group around it, on the canvas and in every export. When the clipping path has a fill or stroke of its own, the geometry effects of those fills and strokes apply after the group's geometry effects instead. Type used as a clipping path keeps its geometry effects when a group's effect outlines it, and keeps the fill and stroke it was given after the mask was made ([the help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/edit-objects/edit-clipping-masks.html)): its fill still paints behind the clipped art inside the clip and its stroke over it, reshaped with the clip, on the canvas and in SVG and PDF export (the `painted_clipping_type_exports_with_group_effect` tests in `vectorcraft-svg` and `vectorcraft-pdf`). Raster effects such as Gaussian Blur leave that area as it is. `effects::tests::clipfx` and the renderer's `tests::clip` cover it. Clicks, Select Behind, the Unlock submenu, marquees and the Enclosing Lasso inside a clip group or a clipping layer follow that area too: the clipped art is found where the effects moved it and not where they took it away. The clipping path itself is still found by its own outline and anchors. A hidden member of a group used as a clipping path does not clip, and a geometry effect on it does not change where clicks land. Outline view and layers with Preview off draw the plain clipping path, and clicks and marquees there count it. Direct Selection picks and outlines an object of a dynamic symbol's art by the same rules. `doc::hit::tests` and the engine's `tests::clip` cover it. - **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. From 1c8cf681cdfd73bef81456a2139996af2559a5e7 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 19:47:50 -0800 Subject: [PATCH 047/176] Export: clipping type's strokes paint over a knockout clip group's art A clip group whose clipping type strokes becomes a group of a clip group and the strokes when it is evaluated or exported. That group took the clip group's Knockout Group setting, so the strokes knocked out the clipped art under them. The inner clip group now takes the setting and the group around it is set Off, so the clipped art knocks out as before and the strokes paint over it, as the canvas draws the live clip group. A neutral clip group stays neutral on both. --- crates/effects/src/bake.rs | 5 +-- crates/effects/src/reshape.rs | 14 +++++++- crates/effects/src/tests/clipfx.rs | 52 ++++++++++++++++++++++++++++++ 3 files changed, 68 insertions(+), 3 deletions(-) diff --git a/crates/effects/src/bake.rs b/crates/effects/src/bake.rs index 05e9600425..70c426c870 100644 --- a/crates/effects/src/bake.rs +++ b/crates/effects/src/bake.rs @@ -28,7 +28,7 @@ use vectorcraft_geom::{Affine, FillRule, PathData, Rect, Vec2}; use crate::distort::{transform_move, transform_offsets}; use crate::group::{has_own_paint, paints}; use crate::reshape::{ - as_art, clipping_text_outline, dressed, geometry_effects, glyph_outlines, outline_nested_text, painted_type_clip, reshape_leaves, + as_art, clipping_text_outline, dressed, geometry_effects, glyph_outlines, knockout_inside, outline_nested_text, painted_type_clip, reshape_leaves, }; use crate::{ GeomContext, adjust_in_document, apply_geometry_carrying, crop_marks_art, evaluate_container, has_adjustment, has_crop_marks, has_geometry, @@ -502,7 +502,8 @@ fn clip_group_with_type_clip(d: &mut Document, n: &Node) -> Option { return Some(m); }; // `n` keeps its id, name and transparency, and holds the clip group and the strokes over it. - let inner = Node::new(d.alloc_id(), NodeKind::Group { children: members, clip: true }); + let mut inner = Node::new(d.alloc_id(), NodeKind::Group { children: members, clip: true }); + knockout_inside(&mut m, &mut inner); match &mut m.kind { NodeKind::Group { children, clip } | NodeKind::Layer { children, clip, .. } => { *children = vec![Arc::new(inner), stroke]; diff --git a/crates/effects/src/reshape.rs b/crates/effects/src/reshape.rs index 376a1f8ba8..0993ced244 100644 --- a/crates/effects/src/reshape.rs +++ b/crates/effects/src/reshape.rs @@ -773,7 +773,8 @@ pub(crate) fn painted_type_clip(doc: Option<&Document>, n: &Node) -> Option { *children = [Arc::new(inner), Arc::new(stroke)].into_iter().chain(guides).collect(); @@ -784,6 +785,17 @@ pub(crate) fn painted_type_clip(doc: Option<&Document>, n: &Node) -> Option Option<(&Node, &Node)> { + let ch = n.children()?; + if let [inner, stroke, ..] = ch.as_slice() + && matches!(inner.kind, NodeKind::Group { clip: true, .. }) + && !n.clips() + && paints(stroke, false) + { + return Some((n, inner)); + } + ch.iter().find_map(|c| stroke_wrapper(c)) +} + +#[test] +fn clipping_type_strokes_paint_over_a_knockout_clip_group() { + // A clip group set to Knockout Group On, Off or neutral, clipped by type that strokes: its + // clipped art knocks out as the clip group says, and the type's stroke paints over it without + // knocking it out, as the canvas draws the live clip group. The type is reshaped by a group's + // Transform around it, or by its own Offset Path. + use vectorcraft_doc::Knockout; + for (knockout, around) in [(Knockout::On, Knockout::Off), (Knockout::Off, Knockout::Off), (Knockout::Neutral, Knockout::Neutral)] { + for own in [false, true] { + let mut ty = painted_type(3, true, true); + if own { + ty.appearance.effects.push(fx("path.offsetPath", json!({"offset": 1}))); + } + let mut clipped = clip_group(2, ty); + clipped.knockout = knockout; + let mut outer = Node::group(NodeId(1), vec![Arc::new(clipped)]); + if !own { + outer.appearance.effects.push(fx("distort.transform", json!({"moveV": 10}))); + } + let mut d = Document::new(400.0, 400.0); + let layer = d.layers[0].id; + d.insert(Some(layer), 0, outer.clone()).unwrap(); + let baked = bake_document(&d).unwrap(); + let canvas = if own { None } else { crate::evaluate_container(None, &outer) }; + let exported = baked.layers.iter().find_map(|l| stroke_wrapper(l)); + for (what, found) in [("canvas", canvas.as_ref().and_then(stroke_wrapper)), ("export", exported)] { + if own && what == "canvas" { + continue; + } + let case = format!("{what}, own effect {own}, knockout {knockout:?}"); + let (wrapper, inner) = found.unwrap_or_else(|| panic!("{case}: no group around the clip")); + assert_eq!(inner.knockout, knockout, "{case}: the clipped art knocks out as before"); + assert_eq!(wrapper.knockout, around, "{case}: the stroke does not knock out the clipped art"); + } + } + } +} + #[test] fn a_clip_groups_own_fill_stays_in_the_clip_when_its_clipping_type_strokes() { // A clip group with a yellow fill of its own and an Offset Path effect, clipped by type that From cf3eac7d6f1946aecf56bf182eb00f2ecd3a9154 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 19:49:33 -0800 Subject: [PATCH 048/176] Docs: one Hindi row in the localization table --- docs/localization-parity.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/docs/localization-parity.md b/docs/localization-parity.md index 6774685176..e392e4df32 100644 --- a/docs/localization-parity.md +++ b/docs/localization-parity.md @@ -31,8 +31,7 @@ Chinese by `imachus`). Georgian and the original Gujarati catalog are recorded a | English | `en` | source, 100% | all | Latin | — | full | — | | Simplified Chinese (Mandarin) | `zh-hans` | 5,102 rows, 791 of them `@msg` (counted 2026-10-21): menus, `tl!` literals and messages complete when counted | all (3,554 `@msg` and 48 `@msgplural` rows, counted 2026-11-13: the untranslated report lists 55 missing messages for it, which open #7116, #7211, #7330, #7378 and #7405 translate) | CJK UI font from craft-fonts (BIZ UDPGothic) when embedded, else a system font; IME with marked text at the caret; vertical type partial ([type-parity.md](type-parity.md)) | no | full | — (review) | | Spanish | `es` | 4,009 / 4,020 (99.7%) | all (604 messages) | Latin | no | full | — (review) | -| Hindi | `hi` | 8,782 rows (2026-11-13): 3,014 `@msg`, 47 `@msgplural`, 41 `@plural`; the untranslated report on main `f793044f83` (2026-11-14) lists 676 missing rows for it: 608 in its own section and 68 that every checked language lacks | menus, dialogs, tooltips and scanned messages; contributor-approved loanword terminology; agent wording pass | UI and document text shape with HarfRust; installed desktop Devanagari fallback, or a `Deva` craft-fonts face; web font still needed | contributor terminology review; 2026-11-13 wording pass on messages and longer labels, and a word-sense pass on short labels, with a glossary-term test; wider proofread welcome | complete catalog, machine-assisted draft | reported missing rows, native review, layout and web font | -| Hindi | `hi` | 8,782 rows (2026-11-13): 3,014 `@msg`, 47 `@msgplural`, 41 `@plural`; the untranslated report on main `f793044f83` (2026-11-14) lists 676 missing rows for it: 608 in its own section and 68 that every checked language lacks | menus, dialogs, tooltips and scanned messages; contributor-approved loanword terminology; agent wording pass | UI and document text shape with HarfRust; installed desktop Devanagari fallback, or a `Deva` craft-fonts face; the web fetches Noto Sans Devanagari when the interface needs it | contributor terminology review; 2026-11-13 wording pass on messages and longer labels, with a glossary-term test; wider proofread welcome | complete catalog, machine-assisted draft | reported missing rows, native review and layout | +| Hindi | `hi` | 8,782 rows (2026-11-13): 3,014 `@msg`, 47 `@msgplural`, 41 `@plural`; the untranslated report on main `f793044f83` (2026-11-14) lists 676 missing rows for it: 608 in its own section and 68 that every checked language lacks | menus, dialogs, tooltips and scanned messages; contributor-approved loanword terminology; agent wording pass | UI and document text shape with HarfRust; installed desktop Devanagari fallback, or a `Deva` craft-fonts face; the web fetches Noto Sans Devanagari when the interface needs it | contributor terminology review; 2026-11-13 wording pass on messages and longer labels, and a word-sense pass on short labels, with a glossary-term test; wider proofread welcome | complete catalog, machine-assisted draft | reported missing rows, native review and layout | | Gujarati | `gu` | 4,673 rows (2026-11-14): original 4,286 unchanged; all 387 additions contributor-reviewed and approved | menus and dialogs; status/error messages partial | installed Gujarati fonts on desktop; optional `Gujr` craft-fonts fallback; no Gujarati face in the pinned CI/release fonts or web startup list | original catalog reviewed by a native speaker; all 387 later additions approved by the contributor, with 11 wording corrections | contributor-reviewed catalog | remaining messages and a bundled Gujarati web font | | Arabic | `ar` | 0 | none | document text: bidi layout and Paragraph Direction; interface: no right-to-left layout, no Arabic shaping in egui | no | none | 25–40 | | French | `fr` | 9,166 rows, 3,436 of them `@msg` and 48 `@msgplural` (counted 2026-11-13): the untranslated report lists 178 missing messages for it | all | Latin | no | full | — (review) | From ecfbf0849ec68e4affc70ed0590b82637e21b94d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 21:56:09 -0800 Subject: [PATCH 049/176] Effects: a clip group's own gradients fit its clipping path when its clipping type strokes When a clip group with a geometry effect is clipped by type that paints strokes, its own unplaced gradients are pinned to the box of the clip group inside the result, the same node its fills and strokes paint in, instead of the box of the group around it that also holds the strokes. --- crates/effects/src/group.rs | 7 +++---- crates/effects/src/tests/clipfx.rs | 31 ++++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+), 4 deletions(-) diff --git a/crates/effects/src/group.rs b/crates/effects/src/group.rs index 73684a008f..912ae64793 100644 --- a/crates/effects/src/group.rs +++ b/crates/effects/src/group.rs @@ -883,11 +883,10 @@ pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option { // strokes ([`crate::reshape::painted_type_clip`]): its own fills and strokes paint inside // that clip group. let wrapped = n.clips() && !m.clips(); - let shapes = match m.children().and_then(|ch| ch.first()).filter(|_| wrapped) { - Some(inner) => member_shapes(doc, inner), - None => member_shapes(doc, &m), + let (shapes, bounds) = match m.children().and_then(|ch| ch.first()).filter(|_| wrapped) { + Some(inner) => (member_shapes(doc, inner), inner.geometric_bounds()), + None => (member_shapes(doc, &m), m.geometric_bounds()), }; - let bounds = m.geometric_bounds(); let art = |items: &[AppearanceItem]| -> Vec> { items.iter().filter_map(|i| item_art(n.id, i, &shapes, bounds)).map(Arc::new).collect() }; let (below, above) = m.appearance.split_contents(); diff --git a/crates/effects/src/tests/clipfx.rs b/crates/effects/src/tests/clipfx.rs index 0c11430e83..7359a78989 100644 --- a/crates/effects/src/tests/clipfx.rs +++ b/crates/effects/src/tests/clipfx.rs @@ -615,3 +615,34 @@ fn a_clip_groups_own_fill_stays_in_the_clip_when_its_clipping_type_strokes() { assert!(clipped.iter().skip(1).any(|c| yellow_in(c)), "the group's fill paints inside the clip: {clipped:?}"); assert!(!children.iter().skip(1).any(|c| yellow_in(c)), "{children:?}"); } + +#[test] +fn a_clip_groups_own_gradient_spans_the_clip_when_its_clipping_type_strokes() { + // A clip group with an unplaced linear gradient fill of its own and an Offset Path effect, + // clipped by type with a stroke whose Transform effect moves it 60 pt right: the gradient + // spans the region the clipping path clips to. + use vectorcraft_color::{Gradient, GradientKind, GradientPaint, GradientStop}; + let stops = vec![GradientStop::new(0.0, Color::BLACK), GradientStop::new(1.0, Color::WHITE)]; + let unplaced = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, stops)))); + let mut ty = painted_type(3, false, false); + ty.appearance = Appearance::basic(Paint::None, green(), 2.0).into(); + for item in &mut ty.appearance.items { + if let vectorcraft_doc::AppearanceItem::Stroke(s) = item { + s.effects.push(fx("distort.transform", json!({"moveH": 60}))); + } + } + let mut group = clip_group(2, ty); + group.appearance = + Appearance { effects: vec![fx("path.offsetPath", json!({"offset": 0}))], ..Appearance::basic(unplaced, Paint::None, 0.0) }.into(); + let canvas = crate::evaluate_container(None, &group).unwrap(); + let NodeKind::Group { children, clip: false } = &canvas.kind else { panic!("not a group around the clip: {canvas:?}") }; + let NodeKind::Group { children: clipped, clip: true } = &children[0].kind else { panic!("no clip group first: {children:?}") }; + let region = clip_outline(&clipped[0]).expect("the type clips").0.bounding_box(); + let fill = clipped.iter().skip(1).find_map(|c| match c.appearance.fill_paint() { + Paint::Gradient(g) => g.geom, + _ => None, + }); + let geom = fill.unwrap_or_else(|| panic!("no gradient fill inside the clip: {clipped:?}")); + let (left, right) = (geom.start.x.min(geom.end.x), geom.start.x.max(geom.end.x)); + assert!((left - region.x0).abs() < 0.5 && (right - region.x1).abs() < 0.5, "the gradient {geom:?} spans the clip {region:?}"); +} From 24e9565bec4b5ef52622ce9f2b656378379c36e3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 14 Nov 2026 23:00:13 -0800 Subject: [PATCH 050/176] Effects: a group's own fill and effects measure clipping type by its clip, not its strokes When a group with a geometry effect holds a clip group whose clipping type paints strokes, the clip group becomes a group of a clip group and the type's stroke art. The clipping path in it is now the region the live clip uses, so the geometry effects of the type's fills and strokes reshape what they paint and leave the clip as it is. The group's own fills and strokes, their unplaced gradients and the box its geometry effects scale around count that group as its clip group, so a stroke moved outside the clip no longer widens them. --- crates/effects/src/bake.rs | 11 ++--- crates/effects/src/group.rs | 16 +++--- crates/effects/src/reshape.rs | 78 +++++++++++++++++++++++++---- crates/effects/src/tests/clipfx.rs | 79 ++++++++++++++++++++++++++++++ 4 files changed, 159 insertions(+), 25 deletions(-) diff --git a/crates/effects/src/bake.rs b/crates/effects/src/bake.rs index 70c426c870..ac43922bf0 100644 --- a/crates/effects/src/bake.rs +++ b/crates/effects/src/bake.rs @@ -28,7 +28,8 @@ use vectorcraft_geom::{Affine, FillRule, PathData, Rect, Vec2}; use crate::distort::{transform_move, transform_offsets}; use crate::group::{has_own_paint, paints}; use crate::reshape::{ - as_art, clipping_text_outline, dressed, geometry_effects, glyph_outlines, knockout_inside, outline_nested_text, painted_type_clip, reshape_leaves, + as_art, clip_region_path, clipping_text_outline, dressed, geometry_effects, glyph_outlines, knockout_inside, outline_nested_text, + painted_type_clip, reshape_leaves, }; use crate::{ GeomContext, adjust_in_document, apply_geometry_carrying, crop_marks_art, evaluate_container, has_adjustment, has_crop_marks, has_geometry, @@ -472,13 +473,7 @@ fn clip_group_with_type_clip(d: &mut Document, n: &Node) -> Option { { return None; } - let (bp, rule) = crate::clip_outline(first)?; - let mut clip = Node::path(first.id, PathData::from_bezpath(&bp), Appearance::default()); - if let NodeKind::Path { rule: r, clipping, .. } = &mut clip.kind { - (*r, *clipping) = (rule, true); - } - clip.name = first.name.clone(); - clip.visible = first.visible; + let clip = clip_region_path(first)?; let paint = first.clip_paint(); // The type's fills and strokes as art: baked with the type's id, as the renderer draws them, // then given ids of their own. diff --git a/crates/effects/src/group.rs b/crates/effects/src/group.rs index 912ae64793..13ec71f87a 100644 --- a/crates/effects/src/group.rs +++ b/crates/effects/src/group.rs @@ -691,6 +691,11 @@ pub fn member_shapes(doc: Option<&Document>, n: &Node) -> Vec<(PathData, FillRul } } fn members(doc: Option<&Document>, n: &Node, out: &mut Vec<(PathData, FillRule)>) { + // A clip group whose clipping type's strokes paint around it is outlined as that clip + // group: the strokes outside the clip add nothing. + if let Some(inner) = crate::reshape::painted_clip_inner(n) { + return members(doc, inner, out); + } // A clip group shows its members only inside its clipping path: its outline is that // region, not the clipped members' own shapes, which may reach far outside it (#7289). if n.clips() { @@ -881,17 +886,14 @@ pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option { if paint { // A clip group whose clipping type paints strokes is now a group of a clip group and those // strokes ([`crate::reshape::painted_type_clip`]): its own fills and strokes paint inside - // that clip group. - let wrapped = n.clips() && !m.clips(); - let (shapes, bounds) = match m.children().and_then(|ch| ch.first()).filter(|_| wrapped) { - Some(inner) => (member_shapes(doc, inner), inner.geometric_bounds()), - None => (member_shapes(doc, &m), m.geometric_bounds()), - }; + // that clip group. Such groups among the members are measured as their clip groups. + let wrapped = n.clips() && crate::reshape::painted_clip_inner(&m).is_some(); + let (shapes, bounds) = (member_shapes(doc, &m), crate::reshape::clip_bounds(&m)); let art = |items: &[AppearanceItem]| -> Vec> { items.iter().filter_map(|i| item_art(n.id, i, &shapes, bounds)).map(Arc::new).collect() }; let (below, above) = m.appearance.split_contents(); let (below, above) = (art(below), art(above)); - let at = usize::from(n.clips()); + let at = usize::from(wrapped || m.clips()); let target = if wrapped { m.children_mut().and_then(|ch| ch.first_mut()).map(Arc::make_mut) } else { Some(&mut m) }; if let Some(ch) = target.and_then(Node::children_mut) { let at = at.min(ch.len()); diff --git a/crates/effects/src/reshape.rs b/crates/effects/src/reshape.rs index 0993ced244..c6812c63a9 100644 --- a/crates/effects/src/reshape.rs +++ b/crates/effects/src/reshape.rs @@ -744,15 +744,30 @@ pub(crate) fn clipping_text_outline(t: &Node) -> Option { Some(Node { visible: t.visible, ..o }) } +/// Clipping path `clip` of a clip group as a clipping path of the region it clips to +/// ([`crate::clip_outline`]), with its id, name and visibility. For type that paints, the geometry +/// effects of its fills and strokes reshape what they paint and leave that region as it is. +/// `None` when it has nothing to clip by. +pub(crate) fn clip_region_path(clip: &Node) -> Option { + let (bp, rule) = crate::clip_outline(clip)?; + let mut p = Node::path(clip.id, PathData::from_bezpath(&bp), Appearance::default()); + if let NodeKind::Path { rule: r, clipping, .. } = &mut p.kind { + (*r, *clipping) = (rule, true); + } + p.name = clip.name.clone(); + p.visible = clip.visible; + Some(p) +} + /// Clip group or clipping layer `n` whose clipping path is type that paints ([`Node::clip_paint`]), -/// with that type as plain art drawn as the renderer draws it: its outlines clip -/// ([`clipping_text_outline`]), its fills become art behind the clipped members inside the clip, +/// with that type as plain art drawn as the renderer draws it: a path of the region it clips to +/// clips ([`clip_region_path`]), its fills become art behind the clipped members inside the clip, /// and its strokes become art over the clip group, outside the clip. Each part is the type's art /// with only those fills or strokes ([`as_art`]), its own geometry effects applied. With strokes, /// `n` becomes a group with its id, name, visibility and transparency that holds a clip group of -/// the clipping path, the fills and the members, then the strokes; a clipping layer keeps its -/// ruler guides last. `None` when `n` does not clip, its clipping path is not type, or the type -/// paints nothing. +/// the clipping path, the fills and the members (with `n`'s id), then the strokes; a clipping +/// layer keeps its ruler guides last ([`painted_clip_inner`] finds that clip group). `None` when +/// `n` does not clip, its clipping path is not type, or the type paints nothing. pub(crate) fn painted_type_clip(doc: Option<&Document>, n: &Node) -> Option { let first = n.children()?.first().filter(|_| n.clips())?; if !matches!(first.kind, NodeKind::Text(_)) { @@ -762,7 +777,7 @@ pub(crate) fn painted_type_clip(doc: Option<&Document>, n: &Node) -> Option Option<&Node> { + if n.clips() || !matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }) { + return None; + } + let [inner, stroke, ..] = n.children()?.as_slice() else { return None }; + let clip = inner.children()?.first()?; + (inner.clips() && inner.id == n.id && stroke.id == clip.id && !stroke.clips()).then_some(&**inner) +} + +/// The geometric bounds of `n` ([`Node::geometric_bounds`]) with each group or layer in it that +/// [`painted_clip_inner`] finds measured as its clip group, so the strokes of a clipping type +/// outside the clip do not widen them. +pub(crate) fn clip_bounds(n: &Node) -> Option { + fn holds(n: &Node) -> bool { + painted_clip_inner(n).is_some() || n.children().into_iter().flatten().any(|c| holds(c)) + } + fn unwrap(n: &mut Node) { + if let Some(inner) = painted_clip_inner(n) { + let mut inner = inner.clone(); + inner.visible = n.visible; + *n = inner; + } + for c in n.children_mut().into_iter().flatten() { + if holds(c) { + unwrap(Arc::make_mut(c)); + } + } + } + if !holds(n) { + return n.geometric_bounds(); + } + let mut probe = n.clone(); + unwrap(&mut probe); + probe.geometric_bounds() +} + /// Replace type anywhere inside `n` by its outlines, as art that keeps the type's look /// ([`as_art`]). Type in a clip group's clipping path (all of `n` when `clipping` is set) becomes /// its outlines with its visibility and effects ([`clipping_text_outline`]); when it paints, the @@ -1585,7 +1642,7 @@ impl Step<'_> { if !groups.is_empty() { carry_groups(art, groups, after, &|from, to| crate::Carry::of(&e.id, params, bounds, from, to, seed)); } - let drawn = warped.as_deref().map_or_else(|| art.geometric_bounds(), |w| w.bounds(art)); + let drawn = warped.as_deref().map_or_else(|| clip_bounds(art), |w| w.bounds(art)); let whole = (follows && !held).then(|| crate::Carry::of(&e.id, params, bounds, Some(bounds), drawn, seed)); Ran { kept: !kept_ids.is_empty(), took, masks, short, whole } } @@ -3113,16 +3170,17 @@ impl WarpedImages { /// The geometric bounds of `art` as it draws after the effects so far: each image this table /// lists measured by the pieces the warps and moves it took would cut it into, when the art - /// has room for them ([`cut_warped_images`]). + /// has room for them ([`cut_warped_images`]). The strokes of clipping type outside its clip + /// are left out ([`clip_bounds`]). pub(crate) fn bounds(&self, art: &Node) -> Option { if self.images.is_empty() || !self.fits(art, crate::distort::MAX_COPY_OBJECTS) { - return art.geometric_bounds(); + return clip_bounds(art); } // The pieces the images would be cut into now: each group of pieces is shown or hidden as // its image is, and hidden objects are left out of a layer's bounds. let mut probe = art.clone(); restore_warped_images(&mut probe, self, true); - probe.geometric_bounds() + clip_bounds(&probe) } /// The geometric bounds of image `n`: when this table lists it, measured by the pieces the diff --git a/crates/effects/src/tests/clipfx.rs b/crates/effects/src/tests/clipfx.rs index 7359a78989..1847a2ab0d 100644 --- a/crates/effects/src/tests/clipfx.rs +++ b/crates/effects/src/tests/clipfx.rs @@ -646,3 +646,82 @@ fn a_clip_groups_own_gradient_spans_the_clip_when_its_clipping_type_strokes() { let (left, right) = (geom.start.x.min(geom.end.x), geom.start.x.max(geom.end.x)); assert!((left - region.x0).abs() < 0.5 && (right - region.x1).abs() < 0.5, "the gradient {geom:?} spans the clip {region:?}"); } + +#[test] +fn a_groups_own_fill_paints_only_the_clip_of_clipping_type_whose_stroke_moves() { + // A group with a fill of its own (solid, or an unplaced linear gradient) and a Transform effect + // (moving everything 10 pt down, or scaling it to half its width around its middle) holds a + // clip group clipped by type whose stroke has a Transform effect moving it 60 pt right, + // outside the clip. On the canvas and in the export, the clip region is the type's glyphs + // reshaped by the group's effect, and the group's fill paints that region alone, its gradient + // spanning it: the moved stroke adds nothing to the region, the fill or the box the group's + // effect scales around. + use vectorcraft_color::{Gradient, GradientKind, GradientPaint, GradientStop}; + let yellow = Paint::solid(Color::rgb(1.0, 1.0, 0.0)); + let stops = vec![GradientStop::new(0.0, Color::BLACK), GradientStop::new(1.0, Color::WHITE)]; + let unplaced = Paint::Gradient(Box::new(GradientPaint::new(Gradient::new(GradientKind::Linear, stops)))); + let mut ty = painted_type(3, false, false); + ty.appearance = Appearance::basic(Paint::None, green(), 2.0).into(); + for item in &mut ty.appearance.items { + if let vectorcraft_doc::AppearanceItem::Stroke(s) = item { + s.effects.push(fx("distort.transform", json!({"moveH": 60}))); + } + } + let live = clip_outline(&ty).expect("the type clips").0.bounding_box(); + let moved = Rect::new(live.x0, live.y0 + 10.0, live.x1, live.y1 + 10.0); + // Scaled to half its width around the middle of the clip, which the stroke does not move. + let (mid, quarter) = ((live.x0 + live.x1) / 2.0, live.width() / 4.0); + let narrowed = Rect::new(mid - quarter, live.y0, mid + quarter, live.y1); + // The group's own fill art: every object outside the clip groups whose own fill is `paint`. + fn own_fills<'a>(n: &'a Node, paint: &Paint, out: &mut Vec<&'a Node>) { + let mine = n.appearance.items.iter().any(|i| match (i, paint) { + (vectorcraft_doc::AppearanceItem::Fill(f), Paint::Gradient(_)) => matches!(f.paint, Paint::Gradient(_)), + (vectorcraft_doc::AppearanceItem::Fill(f), p) => f.paint == *p, + _ => false, + }); + if mine { + out.push(n); + } + for c in n.children().into_iter().flatten().filter(|c| !c.clips()) { + own_fills(c, paint, out); + } + } + let cases = [(json!({"moveV": 10}), moved), (json!({"scaleH": 50, "scaleV": 100}), narrowed)]; + for ((params, region), paint) in cases.iter().flat_map(|c| [yellow.clone(), unplaced.clone()].map(|p| (c.clone(), p))) { + let mut outer = Node::group(NodeId(1), vec![Arc::new(clip_group(2, ty.clone()))]); + outer.appearance = + Appearance { effects: vec![fx("distort.transform", params.clone())], ..Appearance::basic(paint.clone(), Paint::None, 0.0) }.into(); + let canvas = crate::evaluate_container(None, &outer).unwrap(); + let mut d = Document::new(400.0, 400.0); + let layer = d.layers[0].id; + d.insert(Some(layer), 0, outer).unwrap(); + let baked = bake_document(&d).unwrap(); + let exported = baked.layers[0].children().and_then(|ch| ch.first()).cloned().expect("the export holds the group"); + for (what, art) in [("canvas", &canvas), ("export", &*exported)] { + let case = format!("{what}, {params}, {}", if matches!(paint, Paint::Gradient(_)) { "gradient" } else { "solid" }); + let (clip, _, strokes, _) = painted_clip(art).unwrap_or_else(|| panic!("{case}: no clip group in {art:?}")); + assert!(near_rect(clip, region), "{case}: the clip {clip:?} is the type's glyphs reshaped {region:?}"); + let strokes = strokes.unwrap_or_else(|| panic!("{case}: no stroke art")); + assert!(strokes.x1 > region.x1 + 25.0, "{case}: the stroke {strokes:?} moves outside the clip {region:?}"); + let mut fills = vec![]; + own_fills(art, &paint, &mut fills); + assert!(!fills.is_empty(), "{case}: no fill art of the group in {art:?}"); + let painted = fills.iter().filter_map(|f| f.geometric_bounds()).reduce(|a, b| a.union(b)).unwrap(); + assert!(near_rect(painted, region), "{case}: the group's fill {painted:?} paints the clip {region:?}"); + if let Paint::Gradient(_) = paint { + for fill in fills { + let geom = match fill.appearance.fill_paint() { + Paint::Gradient(g) => g.geom, + _ => None, + }; + let geom = geom.unwrap_or_else(|| panic!("{case}: the gradient is not placed: {fill:?}")); + let (left, right) = (geom.start.x.min(geom.end.x), geom.start.x.max(geom.end.x)); + assert!( + (left - region.x0).abs() < 0.5 && (right - region.x1).abs() < 0.5, + "{case}: the gradient {geom:?} spans the clip {region:?}" + ); + } + } + } + } +} From 829d42ed02584cbd24d11ffe2e4e826c86981aff Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 00:46:04 -0800 Subject: [PATCH 051/176] Effects: name paint_type_clip in the clip group fill comment --- crates/effects/src/group.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/effects/src/group.rs b/crates/effects/src/group.rs index 13ec71f87a..c460ef0644 100644 --- a/crates/effects/src/group.rs +++ b/crates/effects/src/group.rs @@ -885,7 +885,7 @@ pub fn evaluate_container(doc: Option<&Document>, n: &Node) -> Option { m.appearance.effects.retain(|e| !is_pathfinder(&e.id)); if paint { // A clip group whose clipping type paints strokes is now a group of a clip group and those - // strokes ([`crate::reshape::painted_type_clip`]): its own fills and strokes paint inside + // strokes ([`crate::reshape::paint_type_clip`]): its own fills and strokes paint inside // that clip group. Such groups among the members are measured as their clip groups. let wrapped = n.clips() && crate::reshape::painted_clip_inner(&m).is_some(); let (shapes, bounds) = (member_shapes(doc, &m), crate::reshape::clip_bounds(&m)); From 41c62bc66e9d573f371c9651201d06f002cf34f6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 06:41:16 -0800 Subject: [PATCH 052/176] Effects: the type-clip bake test expects the clip group's region path A clip group whose clipping type paints a fill now clips by a path of the region the type clips to, so the test checks for that path, and that the region is copied with the type, instead of a group of glyph outlines. --- crates/effects/src/bake/tests.rs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/crates/effects/src/bake/tests.rs b/crates/effects/src/bake/tests.rs index fba4f75e5f..760839372b 100644 --- a/crates/effects/src/bake/tests.rs +++ b/crates/effects/src/bake/tests.rs @@ -776,7 +776,7 @@ fn type_outlined_next_to_type_that_stays_type_keeps_its_look() { let mut shadowed = type_node(55); shadowed.opacity = 0.5; shadowed.appearance.effects.push(fx("stylize.dropShadow", json!({}))); - // Type that clips a group is outlined as the plain outlines it clips by. + // Type that clips a group is outlined as a plain path of the region it clips by. let square = Node::path(NodeId(57), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), Appearance::default_art()); let clip = Node::new(NodeId(58), NodeKind::Group { children: vec![Arc::new(type_node(56)), Arc::new(square)], clip: true }); g.children_mut().unwrap().extend([Arc::new(shadowed), Arc::new(clip)]); @@ -789,7 +789,10 @@ fn type_outlined_next_to_type_that_stays_type_keeps_its_look() { let b = o.geometric_bounds().unwrap(); assert!(b.x0 < 30.0 && b.x1 > 220.0, "{b:?}"); let clipped = d.node(NodeId(58)).and_then(|n| n.children()).and_then(|c| c.first()).unwrap(); - assert!(matches!(clipped.kind, NodeKind::Group { .. }) && clipped.opacity == 1.0, "{clipped:?}"); + assert!(matches!(clipped.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) && clipped.opacity == 1.0, "{clipped:?}"); + // The region is copied with the type. + let b = clipped.geometric_bounds().unwrap(); + assert!(b.x0 < 30.0 && b.x1 > 220.0, "{b:?}"); } #[test] From b6cdcca6225df0d7eabe03147a97fc469c468ed8 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 07:25:36 -0800 Subject: [PATCH 053/176] Symbols: instance fill and stroke effects keep clipping reach, Pathfinder results and Shaper faces The merge of main left two match arms for symbol instances in `Node::reach`, so the arm that takes in the region of a clipping path with live geometry effects in the art no longer ran, and clippy stopped on the unreachable pattern. Symbol instances now have one arm that takes in both that region and the shapes the art paints with the effects of the instance's own fill or stroke. The shapes an instance's fill or stroke effects paint now come from the result of a Pathfinder effect on a group or layer in the art, not from the members it combines, and leave out the original shapes a Shaper group holds. A click where only those shapes would grow no longer selects the instance. --- crates/doc/src/node/ops.rs | 31 +++++++++-------- crates/effects/src/reshape.rs | 17 +++++---- crates/engine/src/tests/expand.rs | 57 +++++++++++++++++++++++++++++++ 3 files changed, 85 insertions(+), 20 deletions(-) diff --git a/crates/doc/src/node/ops.rs b/crates/doc/src/node/ops.rs index d626bbb65d..1cb4b7309f 100644 --- a/crates/doc/src/node/ops.rs +++ b/crates/doc/src/node/ops.rs @@ -256,17 +256,8 @@ impl Node { .map(|b| b.inflate(o, o)) } NodeKind::Intertwine { children } => children.iter().fold(None, |acc, c| vectorcraft_geom::union_opt(acc, c.reach(symbols))), - // The frame and each shape the image's own fills and strokes paint, or a symbol - // instance's box and each shape its art paints with the geometry effects of the - // instance's own fill or stroke, a stroke's grown by the farthest it can reach from its - // shape. - NodeKind::Image(_) | NodeKind::SymbolInstance { .. } => { - let start = if matches!(self.kind, NodeKind::Image(_)) { self.geometric(symbols) } else { self.visual(symbols) }; - crate::hit::image_paint(symbols.map(SymbolBoxes::document), self).iter().fold(start, |acc, (bp, _, item)| { - let o = if let crate::AppearanceItem::Stroke(s) = item { s.reach() } else { 0.0 }; - vectorcraft_geom::union_opt(acc, (!bp.elements().is_empty()).then(|| bp.bounding_box().inflate(o, o))) - }) - } + // The frame and each shape the image's own fills and strokes paint. + NodeKind::Image(_) => self.with_own_paint(self.geometric(symbols), symbols), // Keys and steps placed on a spine, turned to it with Align to Path, can reach past the // keys and the spine. NodeKind::Blend { children, spec } => { @@ -277,13 +268,15 @@ impl Node { NodeKind::Layer { children, clip: true, .. } | NodeKind::Group { children, clip: true } => { vectorcraft_geom::union_opt(self.visual(symbols), children.first().and_then(|c| crate::hit::reshaped_clip_box(c))) } - // The live geometry effects of the clipping paths in the art can draw it past its box. + // The live geometry effects of the clipping paths in the art can draw it past its box, + // and the box takes in each shape the art paints with the geometry effects of the + // instance's own fill or stroke. NodeKind::SymbolInstance { symbol, xf } => { let Some((s, art, region)) = symbols.and_then(|s| { let a = s.art(symbol)?; Some((s, a, a.reshaped?)) }) else { - return self.visual(symbols); + return self.with_own_paint(self.visual(symbols), symbols); }; let map = s.document().symbol_slice_map_of(symbol, art.geometric, *xf); let placed = if moves_only(*xf) && map.is_none() { @@ -299,12 +292,22 @@ impl Node { map.map_or_else(|| xf.transform_rect_bbox(all), |m| m.placement_bounds(all)).inflate(grow, grow) }; let o = self.appearance.outset(); - vectorcraft_geom::union_opt(self.visual(symbols), self.projected(Some(placed)).map(|b| b.inflate(o, o))) + self.with_own_paint(vectorcraft_geom::union_opt(self.visual(symbols), self.projected(Some(placed)).map(|b| b.inflate(o, o))), symbols) } _ => self.visual(symbols), } } + /// `start` grown by each shape the node's own fills and strokes paint + /// ([`crate::hit::set_image_paint`]), a stroke's grown by the farthest it can reach from its + /// shape. + fn with_own_paint(&self, start: Option, symbols: Option<&SymbolBoxes>) -> Option { + crate::hit::image_paint(symbols.map(SymbolBoxes::document), self).iter().fold(start, |acc, (bp, _, item)| { + let o = if let crate::AppearanceItem::Stroke(s) = item { s.reach() } else { 0.0 }; + vectorcraft_geom::union_opt(acc, (!bp.elements().is_empty()).then(|| bp.bounding_box().inflate(o, o))) + }) + } + /// Geometric bounds (no stroke), recursively. Clip groups are bounded by their clip path. A /// symbol instance is measured as its transform applied to the 20 × 20 square around the origin /// that symbols made in the app keep their art in ([`Node::geometric_bounds_with`] measures diff --git a/crates/effects/src/reshape.rs b/crates/effects/src/reshape.rs index cb4200a684..bee8e66e56 100644 --- a/crates/effects/src/reshape.rs +++ b/crates/effects/src/reshape.rs @@ -489,10 +489,11 @@ fn push_painted(doc: Option<&Document>, c: &Node, out: &mut Vec<(BezPath, FillRu /// its active fill and stroke ([`has_item_geometry`]): the paths of the art [`reshape`] makes of it, /// each with its own geometry effects and those of each fill and stroke applied /// ([`crate::bake_type_appearance`], [`push_painted`]), the paths that the own fills and strokes of -/// the groups and layers in the art paint ([`crate::evaluate_container`]), the shapes that the own -/// fills and strokes of the images in the art paint ([`image_paint`]), and the instances in that -/// art that took those effects, in turn. Hidden objects, clipping paths, guides and the members of -/// clip groups add nothing, and neither does an instance more than +/// the groups and layers in the art paint and the results of their Pathfinder effects +/// ([`crate::evaluate_container`]), the shapes that the own fills and strokes of the images in the +/// art paint ([`image_paint`]), and the instances in that art that took those effects, in turn. +/// Hidden objects, clipping paths, guides, the members of clip groups and the original shapes of +/// Shaper groups add nothing, and neither does an instance more than /// [`vectorcraft_doc::depth::MAX_DEPTH`] deep or whose symbol's art would take the objects measured /// so far past `budget`. fn instance_paint(doc: Option<&Document>, n: &Node, depth: usize, budget: &mut u64, out: &mut Vec<(BezPath, FillRule, AppearanceItem)>) { @@ -526,12 +527,16 @@ fn painted_in(doc: Option<&Document>, n: &Node, depth: usize, budget: &mut u64, NodeKind::SymbolInstance { .. } => instance_paint(doc, n, depth + 1, budget, out), _ if n.clips() => {} _ => { - let evaluated = crate::has_container_appearance(n).then(|| crate::evaluate_container(doc, n)).flatten(); + // A Pathfinder effect paints its result, not the members it combines. + let evaluated = (crate::has_container_appearance(n) || crate::has_pathfinder(n)).then(|| crate::evaluate_container(doc, n)).flatten(); let g = evaluated.as_ref().unwrap_or(n); if g.clips() { return; } - for c in g.children().into_iter().flatten() { + // A Shaper group's first member holds its original shapes, which are not drawn. The + // group's own fills and strokes can be painted before it, so it is found by its id. + let sources = n.extras().shaper.is_some().then(|| n.children().and_then(|c| c.first()).map(|c| c.id)).flatten(); + for c in g.children().into_iter().flatten().filter(|c| Some(c.id) != sources) { painted_in(doc, c, depth, budget, out); } } diff --git a/crates/engine/src/tests/expand.rs b/crates/engine/src/tests/expand.rs index 51739267f8..b2f92cd16b 100644 --- a/crates/engine/src/tests/expand.rs +++ b/crates/engine/src/tests/expand.rs @@ -415,6 +415,63 @@ fn a_click_on_the_grown_fill_of_an_image_in_the_art_selects_the_instance() { assert_eq!(hit_at(&s, 60.0, opt), None, "a click past the grown fill"); } +/// A group in the symbol's art with Effect › Pathfinder › Subtract: the instance's fill effect +/// grows the result, and a click past both shapes where only the subtracted shape would grow does +/// not select the instance. +#[test] +fn a_click_on_a_shape_a_pathfinder_effect_in_the_art_subtracts_misses_the_instance() { + let mut s = session(); + // The back square runs from 50 to 110 and the front one from 80 to 140; the result runs from 50 to 80. + let back = NodeId(run(&mut s, "shape.rectangle", json!({"x": 50, "y": 50, "width": 60, "height": 100}))["id"].as_u64().unwrap()); + run(&mut s, "paint.setFill", json!({"color": "#ff0000"})); + run(&mut s, "paint.setStroke", json!({"color": "#0000ff"})); + run(&mut s, "stroke.set", json!({"weight": 4})); + let front = NodeId(run(&mut s, "shape.rectangle", json!({"x": 80, "y": 50, "width": 60, "height": 100}))["id"].as_u64().unwrap()); + let g = NodeId(run(&mut s, "object.group", json!({"ids": [back.0, front.0]}))["id"].as_u64().unwrap()); + run(&mut s, "effect.apply", json!({"ids": [g.0], "effect": "pathfinder.subtract"})); + run(&mut s, "select.set", json!({"ids": [g.0]})); + let id = NodeId(run(&mut s, "symbol.new", json!({"name": "Subtracted"}))["id"].as_u64().unwrap()); + run(&mut s, "appearance.addFill", json!({"ids": [id.0]})); + let row = node(&s, id).appearance.items.len() - 1; + run(&mut s, "appearance.setItem", json!({"ids": [id.0], "index": row, "none": true})); + let opt = vectorcraft_doc::hit::HitOptions { tol: 1.0, ..Default::default() }; + assert_eq!(hit_at(&s, 45.0, opt), None); + offset_row(&mut s, id, row, 10.0); + let r = render(&s); + assert!(near(r.pixel(45, 100), RED), "the result's fill grows by the offset: {:?}", r.pixel(45, 100)); + assert!(near(r.pixel(145, 100), WHITE), "the subtracted shape is not drawn: {:?}", r.pixel(145, 100)); + assert_eq!(hit_at(&s, 45.0, opt), Some(id), "a click on the result's grown fill"); + assert_eq!(hit_at(&s, 145.0, opt), None, "a click where only the subtracted shape would grow"); +} + +/// A Shaper group in the symbol's art: the instance's fill effect grows the faces it shows, and a +/// click where only its original shapes would grow does not select the instance. +#[test] +fn a_click_on_a_shaper_groups_original_shapes_in_the_art_misses_the_instance() { + let mut s = session(); + run(&mut s, "paint.setStroke", json!({"none": true, "ids": []})); + for x in [0, 50] { + run(&mut s, "paint.setFill", json!({"color": "#ff0000", "ids": []})); + run(&mut s, "shape.rectangle", json!({"x": x, "y": 50, "width": 100, "height": 100})); + } + // The scribble inside the overlap removes the front rectangle's face; the face left runs from 0 to 50. + let g = NodeId(run(&mut s, "shaper.scribble", json!({"points": [[65, 70], [85, 90], [65, 110], [85, 130]]}))["id"].as_u64().unwrap()); + assert!(node(&s, g).extras().shaper.is_some()); + run(&mut s, "select.set", json!({"ids": [g.0]})); + let id = NodeId(run(&mut s, "symbol.new", json!({"name": "Shaped"}))["id"].as_u64().unwrap()); + run(&mut s, "appearance.addFill", json!({"ids": [id.0]})); + let row = node(&s, id).appearance.items.len() - 1; + run(&mut s, "appearance.setItem", json!({"ids": [id.0], "index": row, "none": true})); + let opt = vectorcraft_doc::hit::HitOptions { tol: 1.0, ..Default::default() }; + assert_eq!(hit_at(&s, 57.0, opt), None); + offset_row(&mut s, id, row, 10.0); + let r = render(&s); + assert!(near(r.pixel(57, 100), RED), "the face's fill grows by the offset: {:?}", r.pixel(57, 100)); + assert!(near(r.pixel(125, 100), WHITE), "the original shapes are not drawn: {:?}", r.pixel(125, 100)); + assert_eq!(hit_at(&s, 57.0, opt), Some(id), "a click on the face's grown fill"); + assert_eq!(hit_at(&s, 125.0, opt), None, "a click on an original shape"); +} + /// Of several fills, only the topmost one's effects reach the art, and only while it is visible. #[test] fn only_the_topmost_visible_instance_fill_reshapes_the_art() { From b4f18641ea9c11d91ed7c8f7f920893059541990 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 08:25:25 -0800 Subject: [PATCH 054/176] Tests: an instance's stroke effect moves a Shaper group's stroke below its contents A Shaper group in a symbol's art with a stroke of its own below its Contents row paints that stroke before its original shapes. A click on the stroke the instance's stroke effect moves selects the instance, and a click inside the original shapes does not. --- crates/engine/src/tests/expand.rs | 33 +++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/crates/engine/src/tests/expand.rs b/crates/engine/src/tests/expand.rs index b2f92cd16b..75f67430e0 100644 --- a/crates/engine/src/tests/expand.rs +++ b/crates/engine/src/tests/expand.rs @@ -472,6 +472,39 @@ fn a_click_on_a_shaper_groups_original_shapes_in_the_art_misses_the_instance() { assert_eq!(hit_at(&s, 125.0, opt), None, "a click on an original shape"); } +/// A Shaper group in the symbol's art with a stroke of its own below its Contents row: the +/// instance's stroke effect moves what that stroke paints, and a click selects the instance where +/// the canvas draws the moved stroke, not inside the original shapes. +#[test] +fn a_click_on_a_shaper_group_with_a_stroke_below_its_contents_selects_the_instance_where_it_draws() { + let mut s = session(); + run(&mut s, "paint.setStroke", json!({"none": true, "ids": []})); + for x in [0, 50] { + run(&mut s, "paint.setFill", json!({"color": "#ff0000", "ids": []})); + run(&mut s, "shape.rectangle", json!({"x": x, "y": 50, "width": 100, "height": 100})); + } + // The scribble removes the front rectangle's face; the group's stroke outlines both rectangles. + let g = NodeId(run(&mut s, "shaper.scribble", json!({"points": [[65, 70], [85, 90], [65, 110], [85, 130]]}))["id"].as_u64().unwrap()); + run(&mut s, "appearance.addStroke", json!({"ids": [g.0]})); + let stroke = node(&s, g).appearance.items.len() - 1; + run(&mut s, "paint.setStroke", json!({"ids": [g.0], "item": stroke, "color": "#0000ff"})); + run(&mut s, "stroke.set", json!({"ids": [g.0], "item": stroke, "weight": 4})); + run(&mut s, "appearance.moveItem", json!({"ids": [g.0], "from": "contents", "to": stroke + 1})); + assert_eq!(node(&s, g).appearance.split_contents().0.len(), stroke + 1, "the group's stroke is below its Contents row"); + run(&mut s, "select.set", json!({"ids": [g.0]})); + let id = NodeId(run(&mut s, "symbol.new", json!({"name": "Shaped"}))["id"].as_u64().unwrap()); + run(&mut s, "appearance.addStroke", json!({"ids": [id.0]})); + let row = node(&s, id).appearance.items.len() - 1; + run(&mut s, "appearance.setItem", json!({"ids": [id.0], "index": row, "none": true})); + offset_row(&mut s, id, row, 10.0); + let r = render(&s); + let opt = vectorcraft_doc::hit::HitOptions { tol: 1.0, ..Default::default() }; + assert!(near(r.pixel(160, 100), BLUE), "the group's stroke moves out by the offset: {:?}", r.pixel(160, 100)); + assert!(near(r.pixel(125, 100), WHITE), "the original shapes are not drawn: {:?}", r.pixel(125, 100)); + assert_eq!(hit_at(&s, 160.0, opt), Some(id), "a click on the group's moved stroke"); + assert_eq!(hit_at(&s, 125.0, opt), None, "a click inside an original shape"); +} + /// Of several fills, only the topmost one's effects reach the art, and only while it is visible. #[test] fn only_the_topmost_visible_instance_fill_reshapes_the_art() { From 23bdbada815d4c3d9a3b1d016eff480ded25879d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 11:22:47 -0800 Subject: [PATCH 055/176] Tools: tool.setOption takes the Eraser's angle and roundness modes and variations The Eraser reports angleMode, roundnessMode, angleVariation and roundnessVariation, but the check before tool.setOption sent every key it did not list to the true-or-false check, so the Freehand dialog's OK for the Eraser failed. sizeMode was also limited to fixed and pressure for the Eraser, which takes every mode. The gesture tools' check now takes each mode (any of the six for the Eraser, fixed or pressure for the Blob Brush's size), the angle variation from 0 to 180 and the roundness variation from 0 to 100, and names its true-or-false options instead of defaulting to them. A new test checks that every tool in the catalog takes back the options it reports, apart from the state it reports and does not take. --- crates/tools/src/draw2/gesture.rs | 10 ++++++-- crates/tools/src/draw2/gesture/tests.rs | 14 +++++++++++ crates/tools/src/option_check.rs | 33 +++++++++++++++++++++++++ 3 files changed, 55 insertions(+), 2 deletions(-) diff --git a/crates/tools/src/draw2/gesture.rs b/crates/tools/src/draw2/gesture.rs index 7276311076..0b2be462b8 100644 --- a/crates/tools/src/draw2/gesture.rs +++ b/crates/tools/src/draw2/gesture.rs @@ -1841,8 +1841,14 @@ impl Tool for GestureTool { "angle" => c::number(key, v, -180.0, 180.0), "roundness" => c::number(key, v, if self.id == "blobBrush" { 0.0 } else { 1.0 }, 100.0), "editWithin" | "closeWithin" => c::number(key, v, 0.0, 100.0), - "sizeMode" => c::one_of(key, v, &["fixed", "pressure"]), - _ => c::boolean(key, v), + "angleVariation" => c::number(key, v, 0.0, 180.0), + "roundnessVariation" => c::number(key, v, 0.0, 100.0), + // The Blob Brush's Size is Fixed or Pressure; the Eraser's Angle, Roundness and Size + // take any mode (`set_option`). + "sizeMode" if self.id != "eraser" => c::one_of(key, v, &[Variation::Fixed.id(), Variation::Pressure.id()]), + "sizeMode" | "angleMode" | "roundnessMode" => c::one_of(key, v, &Variation::ALL.map(Variation::id)), + "fill" | "altSmooth" | "livePreview" | "liveFit" | "keepSelected" | "mergeOnlySelection" => c::boolean(key, v), + _ => Err(c::unknown(key)), } } } diff --git a/crates/tools/src/draw2/gesture/tests.rs b/crates/tools/src/draw2/gesture/tests.rs index 9dfbdba2de..b554cfd045 100644 --- a/crates/tools/src/draw2/gesture/tests.rs +++ b/crates/tools/src/draw2/gesture/tests.rs @@ -2822,6 +2822,20 @@ fn the_eraser_tip_follows_its_variation_modes() { [&o["angleMode"], &o["angleVariation"], &o["roundnessMode"], &o["roundnessVariation"], &o["sizeMode"], &o["sizeVariation"]], [&json!("rotation"), &json!(90.0), &json!("random"), &json!(10.0), &json!("tilt"), &json!(8.0)] ); + // `tool.setOption` takes back what the tool reports, and refuses a mode or Variation it does + // not take. + let reported = o.as_object().unwrap().clone(); + assert_eq!(t.check_options(&reported), Ok(())); + for mode in Variation::ALL { + for k in ["sizeMode", "angleMode", "roundnessMode"] { + assert_eq!(t.check_option(k, &json!(mode.id())), Ok(()), "{k} {mode:?}"); + } + } + let modes = "must be one of `fixed`, `random`, `pressure`, `tilt`, `bearing`, `rotation`"; + assert_eq!(t.check_option("angleMode", &json!("wheel")), Err(format!("`angleMode` {modes}"))); + assert_eq!(t.check_option("angleVariation", &json!(181)), Err("`angleVariation` must be a number from 0 to 180".into())); + assert_eq!(t.check_option("roundnessVariation", &json!(500)), Err("`roundnessVariation` must be a number from 0 to 100".into())); + assert_eq!(GestureTool::new("blobBrush").check_option("sizeMode", &json!("tilt")), Err("`sizeMode` must be one of `fixed`, `pressure`".into())); // A mode it does not have leaves the mode as it was; a Variation is kept within its range. t.set_option("angleMode", &json!("wheel")); t.set_option("roundnessVariation", &json!(500)); diff --git a/crates/tools/src/option_check.rs b/crates/tools/src/option_check.rs index 8507a82184..8389c6c297 100644 --- a/crates/tools/src/option_check.rs +++ b/crates/tools/src/option_check.rs @@ -159,6 +159,39 @@ mod tests { assert!(string_or_null("prev", &json!(3)).is_err()); } + /// Every tool takes back the options it reports, each on its own and all together: a dialog's + /// OK sends every field the tool showed it. The state a tool reports and doesn't take (the + /// picked mesh points, the text being edited, the pins, the queue of files to place) is left + /// out. + #[test] + fn every_tool_takes_the_options_it_reports() { + const TYPE: &[&str] = &["type", "areaType", "typeOnPath", "verticalType", "verticalAreaType", "verticalTypeOnPath"]; + const READ_ONLY: &[(&[&str], &[&str])] = &[ + (&["directSelection", "groupSelection", "lasso", "mesh", "magicWand"], &["meshPoints"]), + (TYPE, &["editing"]), + (&["puppetWarp"], &["pins", "selected"]), + // With nothing queued, `current` (0) is no file's index either. + (&["place"], &["count", "current", "name", "width", "height", "names"]), + ]; + let read_only = |id: &str, k: &str| READ_ONLY.iter().any(|(ids, keys)| ids.contains(&id) && keys.contains(&k)); + let extra = ["place", "dimension"]; + let mut refused = Vec::new(); + for id in crate::catalog::all_tools().map(|t| t.id).chain(extra) { + let tool = crate::create(id); + let Some(mut options) = tool.options().as_object().cloned() else { continue }; + options.retain(|k, _| !read_only(id, k)); + for (k, v) in &options { + if let Err(e) = tool.check_option(k, v) { + refused.push(format!("tool `{id}`, option `{k}` = {v}: {e}")); + } + } + if let Err(e) = check_values(tool.as_ref(), &options) { + refused.push(e); + } + } + assert!(refused.is_empty(), "{}", refused.join("\n")); + } + #[test] fn set_option_params_reads_the_tool_and_the_options() { let p = json!({"tool": "smooth", "key": "fidelity", "value": 2, "values": {"x": 1}}); From b1f9081feb7e78b5f6f85087a10e107ceec62f48 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 11:57:06 -0800 Subject: [PATCH 056/176] Tools: the Arc tool keeps its lengths at most 1e6 pt, as tool.setOption takes them The Arc tool's setter took a length of any size, while its option check takes a number above 0 and at most 1e6, so a length set past 1e6 was reported back and then refused. The setter now keeps a length within that range. The catalog test also checks what each tool reports after a number option is set past either end and after a true-or-false option is flipped. docs/mcp.md gives the range tool.setOption takes for the Eraser's sizeVariation (0 to 1000). --- crates/tools/src/draw2/family.rs | 9 +++++++-- crates/tools/src/option_check.rs | 30 ++++++++++++++++++++++++------ docs/mcp.md | 2 +- 3 files changed, 32 insertions(+), 9 deletions(-) diff --git a/crates/tools/src/draw2/family.rs b/crates/tools/src/draw2/family.rs index ae18ccd103..76c85fa4dd 100644 --- a/crates/tools/src/draw2/family.rs +++ b/crates/tools/src/draw2/family.rs @@ -531,9 +531,10 @@ impl Tool for FamilyTool { } } -/// Arc segment length from a dialog or preference value. +/// Arc segment length from a dialog or preference value, at most 1e6 pt (as the option check +/// takes it). fn arc_length(v: &Value, current: f64) -> f64 { - v.as_f64().filter(|n| n.is_finite()).map_or(current, |n| n.abs().max(1e-9)) + v.as_f64().filter(|n| n.is_finite()).map_or(current, |n| n.abs().clamp(1e-9, 1e6)) } /// A grid's Default Size side from option value `v`: a finite positive length (at most 1e6 pt), @@ -1030,6 +1031,10 @@ mod tests { "fillArc": true, }) ); + // A length past 1e6 pt is kept at 1e6, which `tool.setOption` takes back. + t.set_option("lengthX", &json!(-1e9)); + assert_eq!(t.options()["lengthX"], json!(1e6)); + assert_eq!(t.check_option("lengthX", &t.options()["lengthX"]), Ok(())); } /// While an arc is dragged out, C switches it between open and closed, F switches its base diff --git a/crates/tools/src/option_check.rs b/crates/tools/src/option_check.rs index 8389c6c297..8b8d749d64 100644 --- a/crates/tools/src/option_check.rs +++ b/crates/tools/src/option_check.rs @@ -176,17 +176,35 @@ mod tests { let read_only = |id: &str, k: &str| READ_ONLY.iter().any(|(ids, keys)| ids.contains(&id) && keys.contains(&k)); let extra = ["place", "dimension"]; let mut refused = Vec::new(); - for id in crate::catalog::all_tools().map(|t| t.id).chain(extra) { - let tool = crate::create(id); - let Some(mut options) = tool.options().as_object().cloned() else { continue }; + let mut check = |id: &str, tool: &dyn Tool, after: &str| { + let Some(mut options) = tool.options().as_object().cloned() else { return }; options.retain(|k, _| !read_only(id, k)); for (k, v) in &options { if let Err(e) = tool.check_option(k, v) { - refused.push(format!("tool `{id}`, option `{k}` = {v}: {e}")); + refused.push(format!("tool `{id}`{after}, option `{k}` = {v}: {e}")); } } - if let Err(e) = check_values(tool.as_ref(), &options) { - refused.push(e); + if let Err(e) = check_values(tool, &options) { + refused.push(format!("{e}{after}")); + } + }; + for id in crate::catalog::all_tools().map(|t| t.id).chain(extra) { + let tool = crate::create(id); + check(id, tool.as_ref(), ""); + // A number set past either end, or a true-or-false option flipped, is still taken back + // as the tool then reports it. + let Some(defaults) = tool.options().as_object().cloned() else { continue }; + for (k, v) in defaults.iter().filter(|(k, _)| !read_only(id, k)) { + let tries = match v { + Value::Number(_) => vec![json!(-1e9), json!(1e9)], + Value::Bool(b) => vec![json!(!b)], + _ => continue, + }; + for value in tries { + let mut changed = crate::create(id); + changed.set_option(k, &value); + check(id, changed.as_ref(), &format!(" after setting `{k}` to {value}")); + } } } assert!(refused.is_empty(), "{}", refused.join("\n")); diff --git a/docs/mcp.md b/docs/mcp.md index 73960b0b5a..21e8369e9a 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5734,7 +5734,7 @@ drag without that reading, such as a mouse drag, erases at the value itself. One Tilt, Bearing and Rotation run, and the value itself without a reading are VectorCraft's own rules. The command refuses another mode, and a variation below 0 or past its range, and erases nothing. In the desktop app the Eraser's tip outline at the pointer takes the angle, roundness and size the pen gives while it erases. -`tool.setOption {tool: "eraser"}` takes the same keys. +`tool.setOption {tool: "eraser"}` takes the same keys, with `sizeVariation` from 0 to 1000. These commands refuse a string or another value that is not a number with `` `dy` must be a number, not "10" ``, naming the key; the document does not change and no undo step is recorded: `t`, `dx` and `dy` in From 33ff9103922a4ea1236a5b24dd001ec600e178d6 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 21:40:56 -0800 Subject: [PATCH 057/176] Tools: tool.setOption takes Crop Image's and the shape tools' newer options Crop Image's ppi, reference and linked and the shape tools' anchors reached main after the option checks were written, so tool.setOption refused them as unknown. Crop Image now checks them with the ranges check_options uses (the selected image's ppi limit stays in tool.setOption), and the shape tools take anchors from 2 to 1000 and refuse other counts, which the Ellipse dialog test now expects. The test that every tool takes back the options it reports now also covers the Crop Image and Intertwine tools, which the tool catalog does not list. --- crates/tools/src/cropimage.rs | 16 +++++++++++++++- crates/tools/src/option_check.rs | 3 ++- crates/tools/src/shape.rs | 1 + crates/tools/src/shape/tests.rs | 12 ++++++++++++ crates/ui-egui/src/dialogs/shapes.rs | 8 +++++--- 5 files changed, 35 insertions(+), 5 deletions(-) diff --git a/crates/tools/src/cropimage.rs b/crates/tools/src/cropimage.rs index ae96ce5f5e..2e23159e5c 100644 --- a/crates/tools/src/cropimage.rs +++ b/crates/tools/src/cropimage.rs @@ -419,8 +419,13 @@ impl Tool for CropImageTool { }; } - /// `rect` is `[x, y, width, height]`, or null to put the box back where it starts. + /// `rect` is `[x, y, width, height]`, or null to put the box back where it starts. `ppi`, + /// `reference` and `linked` take the values [`check_options`] takes (the selected image's + /// limit on `ppi` is checked by `tool.setOption`, which knows the selection). fn check_option(&self, key: &str, value: &Value) -> Result<(), String> { + if matches!(key, "ppi" | "reference" | "linked") { + return check_options(&serde_json::Map::from_iter([(key.to_string(), value.clone())]), None); + } if key != "rect" { return Err(crate::option_check::unknown(key)); } @@ -648,6 +653,15 @@ mod tests { ] { assert_eq!(check_options(&values(v.clone()), Some(36.0)), Err(want.to_string()), "{v}"); } + // The tool takes the same values on its own, without an image's limit. + let t = CropImageTool::default(); + for (k, v) in [("ppi", json!(72)), ("ppi", json!(null)), ("reference", json!(0)), ("linked", json!(true)), ("rect", json!(null))] { + assert_eq!(t.check_option(k, &v), Ok(()), "{k}: {v}"); + } + assert_eq!(t.check_option("reference", &json!(9)), Err("`reference` must be a whole number from 0 to 8, not 9".into())); + assert_eq!(t.check_option("linked", &json!(1)), Err("`linked` must be true or false, not 1".into())); + assert_eq!(t.check_option("ppi", &json!(2401)), Err("`ppi` must be a number from 1 to 2400 or null, not 2401".into())); + assert_eq!(t.check_option("size", &json!(1)), Err("unknown option `size`".into())); } /// An image's own resolution, and the most it can be cropped to. diff --git a/crates/tools/src/option_check.rs b/crates/tools/src/option_check.rs index 8b8d749d64..e84c316261 100644 --- a/crates/tools/src/option_check.rs +++ b/crates/tools/src/option_check.rs @@ -174,7 +174,8 @@ mod tests { (&["place"], &["count", "current", "name", "width", "height", "names"]), ]; let read_only = |id: &str, k: &str| READ_ONLY.iter().any(|(ids, keys)| ids.contains(&id) && keys.contains(&k)); - let extra = ["place", "dimension"]; + // Tools that `create` makes and the catalog doesn't list. + let extra = ["place", "dimension", crate::cropimage::ID, "intertwine"]; let mut refused = Vec::new(); let mut check = |id: &str, tool: &dyn Tool, after: &str| { let Some(mut options) = tool.options().as_object().cloned() else { return }; diff --git a/crates/tools/src/shape.rs b/crates/tools/src/shape.rs index ae5864f73d..e4afa964fc 100644 --- a/crates/tools/src/shape.rs +++ b/crates/tools/src/shape.rs @@ -875,6 +875,7 @@ impl Tool for ShapeTool { use crate::option_check as c; match key { "sides" | "points" => c::whole(key, v, 3, 1000), + "anchors" => c::whole(key, v, 2, 1000), "cornerRadius" => c::number(key, v, 0.0, MAX_CORNER_RADIUS), "starRatio" => c::number(key, v, 0.01, 1.0), "length" => c::number(key, v, 0.0, 1e6), diff --git a/crates/tools/src/shape/tests.rs b/crates/tools/src/shape/tests.rs index 4e0ee1d1dc..359b96ff2d 100644 --- a/crates/tools/src/shape/tests.rs +++ b/crates/tools/src/shape/tests.rs @@ -1119,3 +1119,15 @@ fn a_move_from_the_centre_point_snaps_and_shows_the_hollow_arrow() { assert!(matches!(a.last(), Some(Action::Preview(_, v)) if v["matrix"][4] == json!(10.0)), "{a:?}"); assert_eq!(t.cursor(&c, Point::new(160.0, 150.0), Mods::default()), Cursor::Arrow); } + +/// `tool.setOption` takes an ellipse's anchor count from 2 to 1000, as the tool keeps it. +#[test] +fn the_anchor_count_is_checked_against_its_range() { + let t = ShapeTool::new("ellipse"); + for n in [2, 4, 1000] { + assert_eq!(t.check_option("anchors", &json!(n)), Ok(()), "{n}"); + } + for bad in [json!(1), json!(1001), json!(4.5), json!("4")] { + assert_eq!(t.check_option("anchors", &bad), Err("`anchors` must be a whole number from 2 to 1000".into()), "{bad}"); + } +} diff --git a/crates/ui-egui/src/dialogs/shapes.rs b/crates/ui-egui/src/dialogs/shapes.rs index e911d3f519..fb84701016 100644 --- a/crates/ui-egui/src/dialogs/shapes.rs +++ b/crates/ui-egui/src/dialogs/shapes.rs @@ -701,9 +701,11 @@ mod tests { super::super::open_tool_dialog(&mut app, "ellipse", json!({"x": 10.0, "y": 150.0})); assert_eq!(app.ui.dialog.as_ref().unwrap().f64("anchors", 0.0), 6.0); app.ui.dialog = None; - // `tool.setOption` keeps it from 2 to 1000, and the dialog opens on what it keeps. - for (set, want) in [(json!(1), 2.0), (json!(2000), 1000.0), (json!(7), 7.0)] { - app.run("tool.setOption", json!({"tool": "ellipse", "values": {"anchors": set}})).unwrap(); + // `tool.setOption` takes it from 2 to 1000 and refuses other counts, and the dialog opens on + // what it keeps. + for (set, want) in [(json!(1), 6.0), (json!(2000), 6.0), (json!(2), 2.0), (json!(1000), 1000.0), (json!(7), 7.0)] { + let r = app.run("tool.setOption", json!({"tool": "ellipse", "values": {"anchors": set}})); + assert_eq!(r.is_ok(), set.as_u64().is_some_and(|n| (2..=1000).contains(&n)), "{set}: {r:?}"); super::super::open_tool_dialog(&mut app, "ellipse", json!({"x": 10.0, "y": 150.0})); assert_eq!(app.ui.dialog.as_ref().unwrap().f64("anchors", 0.0), want, "{set}"); app.ui.dialog = None; From 30b37b7e31af41cd9b1f6c025772bc35fd13e051 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Mon, 16 Nov 2026 13:47:42 +0700 Subject: [PATCH 058/176] i18n: French tangent messages take a no-break space before the colon The French spacing rule (be414ae5) and three new tangent message rows landed in the same batch; the rows used an ordinary space before ':', so french_catalog_uses_nonbreaking_prose_punctuation fails on main. --- crates/ui-egui/src/i18n/fr.tsv | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 8af602785b..1cff1c8ad0 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -7464,9 +7464,9 @@ breakText Glyphs Glyphes @msg a selected path has no area un tracé sélectionné n’a pas de surface @msg a selected path has more than 10000 segments un tracé sélectionné a plus de 10000 segments @msg the two paths have the same outline les deux tracés ont le même contour -@msg One path lies inside the other, so they have no common tangents Un tracé se trouve à l’intérieur de l’autre : ils n’ont donc aucune tangente commune -@msg The paths overlap, so they have no internal tangents Les tracés se chevauchent : ils n’ont donc aucune tangente interne -@msg One path lies inside the other, so they have no internal tangents Un tracé se trouve à l’intérieur de l’autre : ils n’ont donc aucune tangente interne +@msg One path lies inside the other, so they have no common tangents Un tracé se trouve à l’intérieur de l’autre : ils n’ont donc aucune tangente commune +@msg The paths overlap, so they have no internal tangents Les tracés se chevauchent : ils n’ont donc aucune tangente interne +@msg One path lies inside the other, so they have no internal tangents Un tracé se trouve à l’intérieur de l’autre : ils n’ont donc aucune tangente interne # Path Precision Tools add-on: Expand Dashes into Paths. Expand Dashes into Paths Décomposer les tirets en tracés @msg select paths with dashed strokes to expand sélectionnez des tracés à contour pointillé à décomposer From d62cc8af278c89449837a939585704b29afd7e6a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 15 Nov 2026 23:49:48 -0800 Subject: [PATCH 059/176] Tools: option check treats the Polygonal Lasso's meshPoints as read-only like the Lasso's The Polygonal Lasso reports the Lasso's picked mesh points under meshPoints and, like the Lasso, does not take it back through tool.setOption, so the test lists it with the other read-only meshPoints tools. --- crates/tools/src/option_check.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/tools/src/option_check.rs b/crates/tools/src/option_check.rs index e84c316261..dd26fa28f0 100644 --- a/crates/tools/src/option_check.rs +++ b/crates/tools/src/option_check.rs @@ -167,7 +167,7 @@ mod tests { fn every_tool_takes_the_options_it_reports() { const TYPE: &[&str] = &["type", "areaType", "typeOnPath", "verticalType", "verticalAreaType", "verticalTypeOnPath"]; const READ_ONLY: &[(&[&str], &[&str])] = &[ - (&["directSelection", "groupSelection", "lasso", "mesh", "magicWand"], &["meshPoints"]), + (&["directSelection", "groupSelection", "lasso", "polygonalLasso", "mesh", "magicWand"], &["meshPoints"]), (TYPE, &["editing"]), (&["puppetWarp"], &["pins", "selected"]), // With nothing queued, `current` (0) is no file's index either. From 9d722b834264b3801f6b95afd14d42b77d686f23 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 00:01:31 -0800 Subject: [PATCH 060/176] Layers: a Shift-click in the selection column adds or removes a layer's art in one pass layer.selectAll {id, add: true} checked each of the row's K objects with a scan of the S selected objects, then removed or added them one id at a time, each removal rebuilding the selection and each addition scanning it again, so a Shift-click on a large layer took O(K*S + K^2). It now checks the row's art against a set of the selected objects and calls Selection::remove_all or Selection::add_all once. The resulting selection, its order, the reply and the highlighted rows are the same as before. crates/engine/examples/layer_select_bench.rs times the old loop against the new command in one process. On a layer of 50,000 objects the whole command took a median of 733 ms before and 6.9 ms after with all of the layer's art selected, and 369 ms before and 24 ms after with every other object selected (7 runs, wall clock on Linux while other builds were running). --- crates/engine/examples/layer_select_bench.rs | 154 +++++++++++++++++++ crates/engine/src/cmd/layer.rs | 13 +- crates/engine/src/tests/layers.rs | 111 +++++++++++++ docs/target-app-parity.md | 1 + 4 files changed, 272 insertions(+), 7 deletions(-) create mode 100644 crates/engine/examples/layer_select_bench.rs diff --git a/crates/engine/examples/layer_select_bench.rs b/crates/engine/examples/layer_select_bench.rs new file mode 100644 index 0000000000..256cada3af --- /dev/null +++ b/crates/engine/examples/layer_select_bench.rs @@ -0,0 +1,154 @@ +//! `cargo run --release -p vectorcraft-engine --example layer_select_bench` prints the time of a +//! Shift-click in the Layers panel's selection column (`layer.selectAll {id, add: true}`) on a layer of +//! 2,000, 20,000 and 50,000 rectangles, with all of its art selected (the click removes it) and with +//! every other object selected (the click adds the rest). Each case is timed one id at a time (`old`, +//! the loop the command used before, copied here) and in one pass (`new`), side by side in one +//! process: first the whole command, then the selection step alone. Each case checks that both give +//! the same selection and reply before it is timed. +//! `ITERS` sets the runs per case (default 7); each row is the median wall time in ms, followed by +//! every run of `old` and of `new`. +// Example (dev tool): unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness). +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::collections::HashSet; +use std::hint::black_box; +use std::time::Instant; + +use serde_json::{Value, json}; +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::{Appearance, Document, Node, NodeId, Selection}; +use vectorcraft_engine::Session; +use vectorcraft_geom::{Anchor, PathData, Point, SubPath}; + +fn iters() -> usize { + std::env::var("ITERS").ok().and_then(|v| v.parse().ok()).unwrap_or(7).max(1) +} + +fn median(ms: &[f64]) -> f64 { + let mut ms = ms.to_vec(); + ms.sort_by(f64::total_cmp); + ms[ms.len() / 2] +} + +/// A document whose first layer holds `n` 10 pt squares in a row → (document, layer, squares). +fn squares(n: usize) -> (Document, NodeId, Vec) { + let mut doc = Document::new(1600.0, 1200.0); + let layer = doc.layers[0].id; + let ids = (0..n) + .map(|i| { + let (x, y) = ((i % 100) as f64 * 12.0, (i / 100) as f64 * 12.0); + let corners = [(x, y), (x + 10.0, y), (x + 10.0, y + 10.0), (x, y + 10.0)]; + let path = PathData::single(SubPath::new(corners.iter().map(|&(x, y)| Anchor::corner(Point::new(x, y))).collect(), true)); + let id = doc.alloc_id(); + doc.insert(Some(layer), usize::MAX, Node::path(id, path, Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 1.0))).unwrap(); + id + }) + .collect(); + (doc, layer, ids) +} + +/// `layer.selectAll {id: layer, add: true}` before the change: the layer's art checked, removed or +/// added one id at a time with [`Selection::contains`], [`Selection::remove`] and [`Selection::add`]. +fn old_command(s: &mut Session, layer: NodeId) -> Value { + let st = s.doc().unwrap(); + let ids = st.doc.node(layer).unwrap().layer_art(true); + let all_selected = !ids.is_empty() && ids.iter().all(|i| st.selection.contains(*i)); + let rows = st.layer_rows.clone(); + s.select(|_, sel| old_step(sel, &ids, all_selected)).unwrap(); + let st = s.doc_mut().unwrap(); + st.layer_rows = rows; + json!({ "selected": st.selection.objects.iter().map(|i| i.0).collect::>() }) +} + +fn old_step(sel: &mut Selection, ids: &[NodeId], all_selected: bool) { + for i in ids { + if all_selected { sel.remove(*i) } else { sel.add(*i) } + } +} + +fn new_command(s: &mut Session, layer: NodeId) -> Value { + s.execute("layer.selectAll", &json!({"id": layer.0, "add": true})).unwrap() +} + +/// Every run of `old` and of `new`, run in turn, each from `prepare`'s state. +fn time(mut prepare: impl FnMut() -> S, old: impl Fn(&mut S), new: impl Fn(&mut S)) -> (Vec, Vec) { + let run = |s: &mut S, f: &dyn Fn(&mut S)| { + let t = Instant::now(); + f(s); + t.elapsed().as_secs_f64() * 1000.0 + }; + let (mut olds, mut news) = (Vec::new(), Vec::new()); + for _ in 0..iters() { + let mut s = prepare(); + olds.push(run(&mut s, &old)); + black_box(&s); + let mut s = prepare(); + news.push(run(&mut s, &new)); + black_box(&s); + } + (olds, news) +} + +fn row(name: &str, (old, new): (Vec, Vec)) { + let (o, n) = (median(&old), median(&new)); + let list = |ms: &[f64]| ms.iter().map(|m| format!("{m:.2}")).collect::>().join(" "); + println!(" {name:<40} {o:>12.3} ms {n:>12.3} ms {:>9.1}x", o / n.max(1e-9)); + println!(" old runs: {}", list(&old)); + println!(" new runs: {}", list(&new)); +} + +fn main() { + println!(" {:<40} {:>15} {:>15} {:>10}", "case", "old", "new", "speedup"); + for n in [2_000usize, 20_000, 50_000] { + println!("{n} objects"); + let (doc, layer, ids) = squares(n); + let mut s = Session::new(); + s.add_document(doc, None); + let mut all = Selection::default(); + all.set(ids.iter().copied()); + let mut half = Selection::default(); + half.set(ids.iter().copied().step_by(2)); + for (name, start) in [("all selected (removes)", &all), ("half selected (adds)", &half)] { + let reset = |s: &mut Session| { + let st = s.doc_mut().unwrap(); + st.selection = start.clone(); + st.layer_rows.clear(); + }; + // Both ways give the same selection and reply. + reset(&mut s); + let old_reply = old_command(&mut s, layer); + let old_sel = s.doc().unwrap().selection.clone(); + reset(&mut s); + let new_reply = new_command(&mut s, layer); + assert_eq!(s.doc().unwrap().selection, old_sel, "{name}: the same selection"); + assert_eq!(new_reply, old_reply, "{name}: the same reply"); + + let (mut olds, mut news) = (Vec::new(), Vec::new()); + for _ in 0..iters() { + for (f, ms) in [(old_command as fn(&mut Session, NodeId) -> Value, &mut olds), (new_command, &mut news)] { + reset(&mut s); + let t = Instant::now(); + black_box(f(&mut s, layer)); + ms.push(t.elapsed().as_secs_f64() * 1000.0); + } + } + row(&format!("command, {name}"), (olds, news)); + // The selection step alone, on a copy of the starting selection. + let art = s.doc().unwrap().doc.node(layer).unwrap().layer_art(true); + let selected: HashSet = start.objects.iter().copied().collect(); + let all_selected = art.iter().all(|i| selected.contains(i)); + let new_step = |sel: &mut Selection| { + if all_selected { + sel.remove_all(art.iter().copied()); + } else { + sel.add_all(art.iter().copied()); + } + }; + let (mut a, mut b) = (start.clone(), start.clone()); + old_step(&mut a, &art, all_selected); + new_step(&mut b); + assert_eq!(a, b, "{name}: the same selection step"); + row(&format!("selection step, {name}"), time(|| start.clone(), |sel| old_step(sel, &art, all_selected), new_step)); + } + } +} diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 83f27cdd61..7b97a3ff92 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -722,19 +722,18 @@ fn select_art(s: &mut Session, p: &Value) -> Result { } else { vec![id] }; - let all_selected = !ids.is_empty() && ids.iter().all(|i| st.selection.contains(*i)); + let all_selected = add && !ids.is_empty() && { + let selected: HashSet = st.selection.objects.iter().copied().collect(); + ids.iter().all(|i| selected.contains(i)) + }; let rows = st.layer_rows.clone(); s.select(|_, sel| { if !add { sel.set(ids.iter().copied()); } else if all_selected { - for i in &ids { - sel.remove(*i); - } + sel.remove_all(ids.iter().copied()); } else { - for i in &ids { - sel.add(*i); - } + sel.add_all(ids.iter().copied()); } })?; let st = s.doc_mut()?; diff --git a/crates/engine/src/tests/layers.rs b/crates/engine/src/tests/layers.rs index f6b35716f6..125380943c 100644 --- a/crates/engine/src/tests/layers.rs +++ b/crates/engine/src/tests/layers.rs @@ -213,6 +213,117 @@ fn the_selection_column_selects_a_rows_art_and_shift_adds_or_removes_it() { assert_eq!(ids_sel(&run(&mut s, "layer.target", json!({"id": layer.0}))), vec![c, a, g]); } +/// The rows of [`column_start`]: [`tree`]'s, plus a rectangle `o` on a second layer and an empty +/// third layer `e`. +#[derive(Clone, Copy)] +struct Column { + layer: NodeId, + sub: NodeId, + a: NodeId, + g: NodeId, + b: NodeId, + c: NodeId, + o: NodeId, + e: NodeId, +} + +fn column_start() -> (Session, Column) { + let mut s = session(); + let (layer, sub, a, g, b, c) = tree(&mut s); + run(&mut s, "layer.setCurrent", json!({"id": layer.0})); + let other = id(&run(&mut s, "layer.new", json!({}))); + let o = rect(&mut s, 200.0); + let e = id(&run(&mut s, "layer.new", json!({}))); + run(&mut s, "select.none", json!({})); + let top: Vec = s.doc().unwrap().doc.layers.iter().map(|l| l.id).collect(); + assert!(top.contains(&other) && top.contains(&e) && parent(&s, o) == Some(other), "{top:?}"); + (s, Column { layer, sub, a, g, b, c, o, e }) +} + +type Prep = dyn Fn(&mut Session, Column); + +/// A Shift-click in the selection column of `row` (whose art is `art`) after `prep` gives the +/// same selection, reply, current layer, highlighted rows and revision as removing or adding each +/// id of `art` one at a time. Returns the session the click ran in. +fn shift_column_matches_each_id(prep: &Prep, row: impl Fn(Column) -> NodeId, art: impl Fn(Column) -> Vec) -> (Session, Column) { + let (mut new, t) = column_start(); + prep(&mut new, t); + let row = row(t); + let before = new.doc().unwrap().selection.clone(); + let reply = run(&mut new, "layer.selectAll", json!({"id": row.0, "add": true})); + let (mut old, t) = column_start(); + prep(&mut old, t); + let ids = art(t); + let st = old.doc().unwrap(); + let all_selected = !ids.is_empty() && ids.iter().all(|i| st.selection.contains(*i)); + let rows = st.layer_rows.clone(); + old.select(|_, sel| { + for i in &ids { + if all_selected { sel.remove(*i) } else { sel.add(*i) } + } + }) + .unwrap(); + old.doc_mut().unwrap().layer_rows = rows; + let (n, o) = (new.doc().unwrap(), old.doc().unwrap()); + assert_eq!(n.selection, o.selection, "row {row:?} from {before:?}"); + assert_eq!(ids_sel(&reply), o.selection.objects); + assert_eq!(n.active_layer, o.active_layer); + assert_eq!(n.highlighted_rows(), o.highlighted_rows()); + assert_eq!(n.revision, o.revision); + assert_eq!(undos(&new), undos(&old)); + (new, t) +} + +#[test] +fn a_shift_click_in_the_selection_column_matches_adding_or_removing_each_id() { + // `o` outside the layer is selected first and is the key object and the target; `a` is + // selected by one anchor, which is the key anchor. + let partly: &Prep = &|s, t| { + run(s, "layer.setCurrent", json!({"id": t.sub.0})); + let sel = &mut s.doc_mut().unwrap().selection; + sel.objects = vec![t.o, t.a]; + sel.anchors.insert(t.a, [(0, 1)].into()); + sel.key = Some(t.o); + sel.key_anchor = Some((t.a, (0, 1))); + sel.target = Some(t.o); + }; + let layer_art = |t: Column| vec![t.c, t.a, t.g]; + // Some of the layer's art is selected: the rest is added after what was selected. + let (s, t) = shift_column_matches_each_id(partly, |t| t.layer, layer_art); + let sel = &s.doc().unwrap().selection; + assert_eq!(sel.objects, vec![t.o, t.a, t.c, t.g]); + assert_eq!(sel.anchors.len(), 1, "the picked anchor stays picked"); + assert!(sel.target.is_none()); + // All of it is selected, `a` as the key object: it is removed, with its anchors, key and key + // anchor. + let all: &Prep = &|s, t| { + partly(s, t); + let sel = &mut s.doc_mut().unwrap().selection; + sel.objects.extend([t.c, t.g]); + sel.key = Some(t.a); + }; + let (s, t) = shift_column_matches_each_id(all, |t| t.layer, layer_art); + let sel = &s.doc().unwrap().selection; + assert_eq!(sel.objects, vec![t.o]); + assert!(sel.anchors.is_empty() && sel.key.is_none() && sel.key_anchor.is_none()); + // An object row, a group row and an empty layer's row. + shift_column_matches_each_id(all, |t| t.c, |t| vec![t.c]); + shift_column_matches_each_id(partly, |t| t.g, |t| vec![t.g]); + shift_column_matches_each_id(partly, |t| t.e, |_| vec![]); + // A locked sublayer's row, and rows outside and inside the isolated group. + let locked: &Prep = &|s, t| { + partly(s, t); + run(s, "layer.setProps", json!({"id": t.sub.0, "locked": true})); + }; + shift_column_matches_each_id(locked, |t| t.sub, |_| vec![]); + let isolated: &Prep = &|s, t| { + partly(s, t); + s.doc_mut().unwrap().isolation = Some(t.g); + }; + shift_column_matches_each_id(isolated, |t| t.c, |_| vec![]); + shift_column_matches_each_id(isolated, |t| t.b, |t| vec![t.b]); +} + fn ids_sel(v: &Value) -> Vec { v["selected"].as_array().unwrap().iter().map(|i| NodeId(i.as_u64().unwrap())).collect() } diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index bc1a780f99..2a930b1baa 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -674,6 +674,7 @@ since 2026-10-01. - **Cut of picked anchors (#6361):** Edit › Cut removes direct-selected anchors from their path and from a compound path's member, with the segments attached to them, as Clear does. Picked segments still lose only those segments. When a path also has a picked segment, Cut removes and copies only its picked segments and ignores its picked anchors, on every contour, as Clear does; an anchor left without a surviving segment is removed with them. Regression tests: `cut_*_anchors_*` and `cut_of_an_anchor_with_a_segment_on_another_contour_leaves_the_source_as_clear_does` in `crates/engine/tests/it/copy_direct_selection.rs`. - **Escape in Selection tool drags:** Escape during a Selection tool move or Alt-drag copy, a bounding-box scale or rotation, a marquee, or a corner widget, pie widget or bracket drag cancels it: the art returns to its state at the press, no copy is left, no undo step is added, the release does nothing, and the tool stays chosen. This is VectorCraft's own behavior. Regression tests: `escape_cancels_*` in `select/tests.rs` and `pie.rs`, and `escape_cancels_a_selection_tool_move_copy_scale_or_rotation` in `tests/selectescape.rs`. - **Large Shift-marquee selections and Select › Inverse:** `select.toggle` and `select.add` with many ids (a Shift-drag marquee sends them together) go through the selection once instead of once per id, and Select › Inverse looks each object up in a set of the selected ones. The resulting selection, its order and the reply are the same as before. With 50,000 objects the selection step of toggling every object off took 528 to 655 ms before and 2.5 to 4.6 ms after in 7 runs, wall clock on a machine that was running other builds (`cargo run --release -p vectorcraft-engine --example selection_bench`). Regression tests: `add_all_does_what_adding_each_does` and `toggle_all_does_what_toggling_each_does` in `crates/doc/src/selection/tests.rs`, and `toggle_and_add_handle_each_listed_id_in_order` in `crates/engine/tests/it/selection_commands.rs`. +- **Shift-click in the Layers panel's selection column on a large layer:** `layer.selectAll {id, add: true}` checks whether the row's art is all selected with a set of the selected objects, and removes or adds that art in one pass instead of once per object. The resulting selection, its order, the reply and the highlighted rows are the same as before. On a layer of 50,000 objects the whole command took a median of 733 ms before and 6.9 ms after when all of the layer's art was selected, and 369 ms before and 24 ms after when every other object was, in 7 runs each, wall clock on Linux while other builds were running (`cargo run --release -p vectorcraft-engine --example layer_select_bench`). Regression test: `a_shift_click_in_the_selection_column_matches_adding_or_removing_each_id` in `crates/engine/src/tests/layers.rs`. - **Selection passes through raster effects:** clicks with the Selection, Direct Selection and Group Selection tools (Group Selection's repeated click included), the Selection tool's pointer and marquee, Direct Selection's marquee, pointer and anchor highlight, and Group Selection's marquee (E for enclosed objects included) leave out the area that a drop shadow, a glow, a blur or another raster effect paints beyond an object. A click on a shadow selects the object under it, or nothing over an empty canvas, a repeated Group Selection click there adds the groups of the object under it, and a press on the shadow of a selected object does not move it ([the help page](https://helpx.adobe.com/illustrator/using/selecting-objects.html)). Over a shadow, Direct Selection highlights only the anchors of the object under it, and Group Selection keeps its own pointer and highlights no anchor, as it does everywhere (VectorCraft's own rule). No setting changes this. This covers paths, groups, type, symbol instances and images. Regression tests: `crates/engine/src/tests/select_effects.rs`. - **Symbol instances are selected where their art draws past their box:** a click or a marquee selects a symbol instance where a clipping path in its art, moved or reshaped by its live geometry effects, shows the art past the instance's box, as it selects a group of the same art; a click also selects it where a stroke in its art paints past the box ([the help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/select-objects/select-objects.html)). The rest is VectorCraft's own rule: inside the box the instance is selected as before; in Outline view and below a layer whose Preview is off only the box counts; hidden art and the area a raster effect paints are left out. This covers instances in groups, nested in other symbols' art, moved and scaled. Regression tests: `a_symbol_instance_is_hit_where_a_moved_clipping_path_in_its_art_shows_the_art` and `a_symbol_instance_is_hit_on_the_stroke_of_its_art_past_its_box` in `crates/doc/src/hit/tests.rs`. - **Selection follows geometry effects:** a click or a marquee with the selection tools selects a path or compound path where its live geometry effects (Transform, Offset Path, Roughen, Zig Zag and the other effects that reshape a path, on the object or on its fills and strokes) draw it, the copies a Transform effect makes included, and not where its own geometry no longer paints. The members of a group or layer whose own geometry effects move or reshape them are selected where they are drawn, at the depth each tool selects, and a locked member there lets the click through to what is below and is listed there in the Unlock submenu. A group's own fills and strokes are clicked where they paint its members, and a clipping path inside such a group is taken on its drawn outline before the art it clips. A compound path keeps its holes, Object Selection by Path Only takes the drawn outline and not its fill, and stacking order is kept. The selection tools select objects by clicking or by a marquee ([the help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/select-objects/select-objects.html)), and the effects leave the art they reshape editable ([the help page](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-filter-effects/apply-and-modify-effects.html)); where clicks land on the reshaped art is VectorCraft's own rule. In Outline view clicks and marquees use the plain paths, and in a layer with Preview off they take outlines only. The area a raster effect paints is still left out. Regression tests: `a_*_shifted_art_*`, `a_click_hits_a_paths_copy_and_evaluates_its_art_once_until_it_changes`, `a_groups_own_effect_moves_where_its_members_are_hit`, `a_layers_own_effect_moves_where_its_art_is_hit`, `a_preview_off_sublayer_of_an_effected_layer_is_clicked_in_outline`, `a_painted_group_around_an_effected_symbols_instance_is_hit_where_its_art_is_drawn`, `an_intertwine_group_in_a_layers_drawn_art_is_hit_in_its_woven_order`, `a_click_in_a_plain_group_evaluates_only_its_member_with_effects`, `a_clip_groups_own_effect_moves_where_its_mask_outline_is_hit`, `an_isolated_clip_group_with_its_own_effect_is_marqueed_by_its_members_own_geometry` and `a_clip_groups_art_is_hit_when_its_drawn_art_holds_only_the_clipping_path` in `crates/doc/src/hit/tests.rs`, and `a_click_and_a_marquee_select_art_where_its_transform_effect_draws_it`, `a_click_selects_a_group_where_its_own_fill_paints_a_moved_member`, `a_marquee_takes_an_inner_groups_own_fill_inside_a_painted_group` and `a_marquee_takes_a_groups_own_fill_inside_a_painted_layer` in `crates/engine/src/tests/select_effects.rs`. From c643f9f5e12ffd222d301d3b91173d491d768f5c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 16 Nov 2026 00:16:03 -0800 Subject: [PATCH 061/176] Text Import Options: Character Set offers the other documented encodings The Character Set menu of Text Import Options now lists Shift JIS, GB2312, Chinese Big 5, Cyrillic, GB18030, Greek, Turkish, Baltic and Central European beside Unicode and ANSI, and `file.place {text: {characterSet}}` takes "shiftJis", "gb2312", "chineseBig5", "cyrillic", "gb18030", "greek", "turkish", "baltic" and "centralEuropean". Each set decodes with its WHATWG Encoding Standard decoder from encoding_rs, which the workspace already locks: GB2312 reads as GBK, Cyrillic as windows-1251 (x-mac-cyrillic with platform "mac"), and Greek, Turkish, Baltic and Central European as windows-1253, 1254, 1257 and 1250 on both platforms. A byte-order mark is read as ordinary bytes and a malformed sequence as U+FFFD. Unicode and ANSI read as before. An unknown character set is an error that lists the sets, and nothing is placed. A `text` option of the wrong type (`characterSet: 3`, `removeLineReturns: "yes"`) is now an error instead of the default. The dialog remembers the last set confirmed, and Show Import Options off places with it. --- Cargo.lock | 1 + crates/engine/Cargo.toml | 3 + crates/engine/src/cmd/place.rs | 2 +- crates/engine/src/cmd/place/text.rs | 163 +++++++++++++++++++--- crates/engine/src/tests/textimport.rs | 30 ++++ crates/engine/tests/text_import_fuzz.rs | 6 +- crates/ui-egui/src/dialogs/text_import.rs | 55 +++++++- crates/ui-egui/src/i18n/bg.tsv | 6 + crates/ui-egui/src/i18n/bs.tsv | 6 + crates/ui-egui/src/i18n/ca.tsv | 7 + crates/ui-egui/src/i18n/cs.tsv | 6 + crates/ui-egui/src/i18n/da.tsv | 6 + crates/ui-egui/src/i18n/de.tsv | 6 + crates/ui-egui/src/i18n/el.tsv | 7 + crates/ui-egui/src/i18n/es.tsv | 7 + crates/ui-egui/src/i18n/fi.tsv | 7 + crates/ui-egui/src/i18n/fr.tsv | 6 + crates/ui-egui/src/i18n/gu.tsv | 5 + crates/ui-egui/src/i18n/hi.tsv | 5 + crates/ui-egui/src/i18n/hu.tsv | 6 + crates/ui-egui/src/i18n/id.tsv | 6 + crates/ui-egui/src/i18n/it.tsv | 6 + crates/ui-egui/src/i18n/ja.tsv | 6 + crates/ui-egui/src/i18n/ka.tsv | 5 + crates/ui-egui/src/i18n/ko.tsv | 6 + crates/ui-egui/src/i18n/nl.tsv | 6 + crates/ui-egui/src/i18n/pl.tsv | 6 + crates/ui-egui/src/i18n/pt-br.tsv | 6 + crates/ui-egui/src/i18n/ru.tsv | 6 + crates/ui-egui/src/i18n/sv.tsv | 5 + crates/ui-egui/src/i18n/tests.rs | 16 +++ crates/ui-egui/src/i18n/tr.tsv | 6 + crates/ui-egui/src/i18n/uk.tsv | 6 + crates/ui-egui/src/i18n/vi.tsv | 7 + crates/ui-egui/src/i18n/zh-hans.tsv | 6 + crates/ui-egui/src/i18n/zh-hant.tsv | 6 + docs/control-protocol.md | 2 +- docs/file-format-parity.md | 2 +- docs/mcp.md | 11 +- docs/target-app-parity.md | 1 + 40 files changed, 427 insertions(+), 34 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 81946466b5..1104b51217 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6672,6 +6672,7 @@ dependencies = [ "craft-proof", "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e2dc681a3)", "crc32fast", + "encoding_rs", "flate2", "hayro-jpeg2000", "heic-rs", diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index b46678804b..9e80c0ef73 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -56,6 +56,9 @@ chrono = { workspace = true } craft-xml = { workspace = true } # The compound file that holds a Word 97-2003 document placed as type (place/doc.rs). cfb = "0.15" +# The Text Import Options character sets other than Unicode and ANSI (place/text.rs). Already in +# Cargo.lock (vectorcraft-eps), so this adds no new crate. +encoding_rs = { workspace = true } kurbo = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } diff --git a/crates/engine/src/cmd/place.rs b/crates/engine/src/cmd/place.rs index 250642285d..3daa26bd6e 100644 --- a/crates/engine/src/cmd/place.rs +++ b/crates/engine/src/cmd/place.rs @@ -81,7 +81,7 @@ pub fn specs() -> Vec { "Place…", ["File"], Some("Cmd+Shift+P"), - "{path | name | dataBase64 (a file's path, or its name with its bytes), link?: true (a raster image keeps its file's path; a VectorCraft document at path becomes one locked placed document showing artboard `page`, linked to the file and read again when it changes (links.update; saving it in this app updates it at once), drawn as vectors in every output; so does a PDF/.ai page at path, showing its `crop` box, unless password or textAs: \"outlines\" is given; false: an editable copy of its art, as from dataBase64; other files are embedded), text?: {characterSet?: \"unicode\" (UTF-8, or UTF-16 with a byte-order mark, or without one by dataset.import's rule: an even length, at least half of its two-byte units holding a NUL byte, the byte order that reads a line break, valid UTF-16 with no NUL character; other bytes as the platform's 8-bit set) | \"ansi\" (the platform's 8-bit set), platform?: \"windows\" (Windows-1252) | \"mac\" (Mac Roman), removeLineReturns?: false (each block of lines becomes one paragraph; blank lines end paragraphs), removeParagraphReturns?: false (drop blank lines), replaceSpaces?: n (runs of n ≥ 2 spaces become a tab)} (a .txt file, placed as area type filling rect, the replaced object's bounds, or else the artboard less a 36 pt margin), template?: false (onto a new locked template layer below the current layer), replace?: false (swap the one selected object, keeping its stacking place and transform; no at/rect; refused while an object of a symbol instance's art is selected), at?: [x, y] centre (default: the first artboard's centre), rect?: [x, y, width, height] fit inside; aspect kept (wins over at), page?: 1 (PDF/.ai page, or a native document's artboard), crop?: \"crop\" (clipped to that page or artboard, default; an SVG, only when given: framed and clipped by its viewBox, else by its art's bounds) | \"bounding\" (the bounds of the art that shows, with its strokes and effects, as an export measures them: hidden objects and guides left out) | \"art\" | \"trim\" | \"bleed\" | \"media\" (a PDF page's boxes), password? (an encrypted PDF), layers?: false (a PSD or PSB file: true embeds its layers as one group named after the file, read as document.open reads them: an image for each layer and a group for each layer group, with the layer's name, visibility, opacity, blend mode and opacity mask, at the place its merged image would take and clipped to the canvas when layers, hidden ones included, reach past it; never linked: link is then false unless given, and link: true is refused; a file without layers is embedded as its merged image, and so are one whose layers are all left out and one whose layers can't be read, with a warning), hiddenLayers?: false (with layers: true, the hidden layers come in hidden instead of being left out; refused without it), importSlices?: bool (a PSD or PSB file: its slices become user slices, moved and scaled with the placed art, in the same undo step; default true when the file is embedded, false when it is linked, and true with link is refused; slices the file generated automatically are left out), dxf?: {…the DXF options of document.open} (a .dxf drawing: fit fills the artboard under at, else the first; fitted or uncentred art lands with its drawing's artboard on that artboard, else it is centred on at), showImportOptions?: true (in the app, a text file without text, a DXF drawing without dxf, a PSD or PSB file embedded without layers (with two layers or more, or with slices) and a PDF with several pages or a password and no page ask for those options first, and an encrypted PDF given page and no password asks for its password; false places them with the options last confirmed, a PDF on page 1 (or page), and asks only an encrypted PDF's password)} → {ids, name, format, linked, width, height, warnings, image?: the id of the image of a DCS file or PSD/PSB file placed in a clip group, which the Links commands take, slices?: [the ids of the user slices a PSD file brought in]}. A PSD or PSB file that names a clipping path places in a clip group of that path (even-odd), as does its merged image in document.open. Raster images come in at 100% of their physical size (the file's ppi, else 72); SVG, DXF, HP-GL (.plt, .hpgl, .hgl, .hpg), PDF/.ai, EMF/WMF and PICT (.pct, .pic, .pict; clipped to the picture's frame), EPS (clipped to its bounding box; as document.open reads it), a .ai saved without PDF compatibility (from its editing data, as document.open reads it: the art of the layers that show on artboard `page`, clipped to that artboard unless crop is \"bounding\") and native documents as one group, with the images, symbols, patterns, swatches and brushes they use. A DCS file (an EPS file with one program per printing plate, DCS 1.0 or 2.0) is placed only from its path with link (else an error, as are document.open and links.embed): one linked image of its plates mixed into CMYK, clipped by the clipping path its composite is drawn through, its spot plates added as spot swatches in the process equivalents the file gives (a swatch of the same name is kept, with a warning); print separations and Separations Preview show each plate on its own ink, and plate files of their own are read from its folder. One undo step; selects what it placed (unless on a template layer); never touches the clipboard. A PNG, JPEG, GIF or WebP image whose pixels can't be read (a file cut short) is an error, and nothing is placed", + "{path | name | dataBase64 (a file's path, or its name with its bytes), link?: true (a raster image keeps its file's path; a VectorCraft document at path becomes one locked placed document showing artboard `page`, linked to the file and read again when it changes (links.update; saving it in this app updates it at once), drawn as vectors in every output; so does a PDF/.ai page at path, showing its `crop` box, unless password or textAs: \"outlines\" is given; false: an editable copy of its art, as from dataBase64; other files are embedded), text?: {characterSet?: \"unicode\" (UTF-8, or UTF-16 with a byte-order mark, or without one by dataset.import's rule: an even length, at least half of its two-byte units holding a NUL byte, the byte order that reads a line break, valid UTF-16 with no NUL character; other bytes as the platform's 8-bit set) | \"ansi\" (the platform's 8-bit set) | \"shiftJis\" | \"gb2312\" (read as GBK) | \"chineseBig5\" | \"cyrillic\" (windows-1251, x-mac-cyrillic on mac) | \"gb18030\" | \"greek\" (windows-1253) | \"turkish\" (windows-1254) | \"baltic\" (windows-1257) | \"centralEuropean\" (windows-1250) (the WHATWG Encoding Standard's decoders: a byte-order mark is read as ordinary bytes, a malformed sequence as U+FFFD), platform?: \"windows\" (ANSI is Windows-1252) | \"mac\" (ANSI is Mac Roman), removeLineReturns?: false (each block of lines becomes one paragraph; blank lines end paragraphs), removeParagraphReturns?: false (drop blank lines), replaceSpaces?: n (runs of n ≥ 2 spaces become a tab)} (a .txt file, placed as area type filling rect, the replaced object's bounds, or else the artboard less a 36 pt margin), template?: false (onto a new locked template layer below the current layer), replace?: false (swap the one selected object, keeping its stacking place and transform; no at/rect; refused while an object of a symbol instance's art is selected), at?: [x, y] centre (default: the first artboard's centre), rect?: [x, y, width, height] fit inside; aspect kept (wins over at), page?: 1 (PDF/.ai page, or a native document's artboard), crop?: \"crop\" (clipped to that page or artboard, default; an SVG, only when given: framed and clipped by its viewBox, else by its art's bounds) | \"bounding\" (the bounds of the art that shows, with its strokes and effects, as an export measures them: hidden objects and guides left out) | \"art\" | \"trim\" | \"bleed\" | \"media\" (a PDF page's boxes), password? (an encrypted PDF), layers?: false (a PSD or PSB file: true embeds its layers as one group named after the file, read as document.open reads them: an image for each layer and a group for each layer group, with the layer's name, visibility, opacity, blend mode and opacity mask, at the place its merged image would take and clipped to the canvas when layers, hidden ones included, reach past it; never linked: link is then false unless given, and link: true is refused; a file without layers is embedded as its merged image, and so are one whose layers are all left out and one whose layers can't be read, with a warning), hiddenLayers?: false (with layers: true, the hidden layers come in hidden instead of being left out; refused without it), importSlices?: bool (a PSD or PSB file: its slices become user slices, moved and scaled with the placed art, in the same undo step; default true when the file is embedded, false when it is linked, and true with link is refused; slices the file generated automatically are left out), dxf?: {…the DXF options of document.open} (a .dxf drawing: fit fills the artboard under at, else the first; fitted or uncentred art lands with its drawing's artboard on that artboard, else it is centred on at), showImportOptions?: true (in the app, a text file without text, a DXF drawing without dxf, a PSD or PSB file embedded without layers (with two layers or more, or with slices) and a PDF with several pages or a password and no page ask for those options first, and an encrypted PDF given page and no password asks for its password; false places them with the options last confirmed, a PDF on page 1 (or page), and asks only an encrypted PDF's password)} → {ids, name, format, linked, width, height, warnings, image?: the id of the image of a DCS file or PSD/PSB file placed in a clip group, which the Links commands take, slices?: [the ids of the user slices a PSD file brought in]}. A PSD or PSB file that names a clipping path places in a clip group of that path (even-odd), as does its merged image in document.open. Raster images come in at 100% of their physical size (the file's ppi, else 72); SVG, DXF, HP-GL (.plt, .hpgl, .hgl, .hpg), PDF/.ai, EMF/WMF and PICT (.pct, .pic, .pict; clipped to the picture's frame), EPS (clipped to its bounding box; as document.open reads it), a .ai saved without PDF compatibility (from its editing data, as document.open reads it: the art of the layers that show on artboard `page`, clipped to that artboard unless crop is \"bounding\") and native documents as one group, with the images, symbols, patterns, swatches and brushes they use. A DCS file (an EPS file with one program per printing plate, DCS 1.0 or 2.0) is placed only from its path with link (else an error, as are document.open and links.embed): one linked image of its plates mixed into CMYK, clipped by the clipping path its composite is drawn through, its spot plates added as spot swatches in the process equivalents the file gives (a swatch of the same name is kept, with a warning); print separations and Separations Preview show each plate on its own ink, and plate files of their own are read from its folder. One undo step; selects what it placed (unless on a template layer); never touches the clipboard. A PNG, JPEG, GIF or WebP image whose pixels can't be read (a file cut short) is an error, and nothing is placed", has_doc, place ), diff --git a/crates/engine/src/cmd/place/text.rs b/crates/engine/src/cmd/place/text.rs index 7d8afc92d4..78261a8804 100644 --- a/crates/engine/src/cmd/place/text.rs +++ b/crates/engine/src/cmd/place/text.rs @@ -3,8 +3,8 @@ use serde_json::Value; -use super::super::utf16_order_without_mark; -use super::{Point, Rect, Result, bad, bool_or, fileio, shapes, str_param}; +use super::super::{text_param, utf16_order_without_mark}; +use super::{Point, Rect, Result, bad, fileio, shapes, switch_or}; /// Text files as `file.place` reports them (not a format `document.open` reads). pub(super) const FORMAT: fileio::Format = fileio::Format { @@ -22,13 +22,68 @@ pub(super) const FORMAT: fileio::Format = fileio::Format { /// document may give. pub(super) const MAX_TEXT: usize = 4 << 20; +/// A character set of Text Import Options (`text.characterSet`). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +enum CharacterSet { + /// UTF-8, or UTF-16 with or without a byte-order mark ([`decode`]). + #[default] + Unicode, + /// The platform's 8-bit character set: Windows-1252, or Mac Roman on a Mac. + Ansi, + ShiftJis, + Gb2312, + ChineseBig5, + Cyrillic, + Gb18030, + Greek, + Turkish, + Baltic, + CentralEuropean, +} + +/// Each character set by its `text.characterSet` value. +const CHARACTER_SETS: [(&str, CharacterSet); 11] = [ + ("unicode", CharacterSet::Unicode), + ("ansi", CharacterSet::Ansi), + ("shiftJis", CharacterSet::ShiftJis), + ("gb2312", CharacterSet::Gb2312), + ("chineseBig5", CharacterSet::ChineseBig5), + ("cyrillic", CharacterSet::Cyrillic), + ("gb18030", CharacterSet::Gb18030), + ("greek", CharacterSet::Greek), + ("turkish", CharacterSet::Turkish), + ("baltic", CharacterSet::Baltic), + ("centralEuropean", CharacterSet::CentralEuropean), +]; + +impl CharacterSet { + /// The Encoding Standard decoder of a set other than Unicode and ANSI, for a file from a Mac + /// when `mac`: GB2312 reads as GBK, Cyrillic as windows-1251 (x-mac-cyrillic on a Mac), and + /// Greek, Turkish, Baltic and Central European as windows-1253, 1254, 1257 and 1250 on both + /// platforms. + fn encoding(self, mac: bool) -> Option<&'static encoding_rs::Encoding> { + Some(match self { + Self::Unicode | Self::Ansi => return None, + Self::ShiftJis => encoding_rs::SHIFT_JIS, + Self::Gb2312 => encoding_rs::GBK, + Self::ChineseBig5 => encoding_rs::BIG5, + Self::Cyrillic if mac => encoding_rs::X_MAC_CYRILLIC, + Self::Cyrillic => encoding_rs::WINDOWS_1251, + Self::Gb18030 => encoding_rs::GB18030, + Self::Greek => encoding_rs::WINDOWS_1253, + Self::Turkish => encoding_rs::WINDOWS_1254, + Self::Baltic => encoding_rs::WINDOWS_1257, + Self::CentralEuropean => encoding_rs::WINDOWS_1250, + }) + } +} + /// Text Import Options (`file.place`'s `text` param). #[derive(Clone, Copy, Debug, Default, PartialEq)] pub(super) struct TextOptions { - /// Decode as the platform's 8-bit character set (Windows-1252 or Mac Roman) instead of - /// Unicode. - ansi: bool, - /// The file comes from a Mac (its 8-bit character set is Mac Roman). + /// The character set the file's bytes are decoded as. + character_set: CharacterSet, + /// The file comes from a Mac (its ANSI set is Mac Roman, its Cyrillic set x-mac-cyrillic). mac: bool, /// Join the lines of each block of text (blank lines end paragraphs). remove_line_returns: bool, @@ -45,11 +100,13 @@ impl TextOptions { if !t.is_object() { return Err(bad(cmd, "text must be {characterSet?, platform?, removeLineReturns?, removeParagraphReturns?, replaceSpaces?}")); } - let choice = |key: &str, values: [&str; 2]| match str_param(t, key) { - None => Ok(false), - Some(v) if v == values[0] => Ok(false), - Some(v) if v == values[1] => Ok(true), - Some(v) => Err(bad(cmd, format!("text.{key} `{v}`: use \"{}\" or \"{}\"", values[0], values[1]))), + // The index of `text[key]` in `values`; 0 when it is omitted or null. + let choice = |key: &str, values: &[&str]| -> Result { + let Some(v) = text_param(t, key, cmd)? else { return Ok(0) }; + values.iter().position(|x| *x == v).ok_or_else(|| { + let (last, rest) = values.split_last().map_or(("", &[][..]), |(last, rest)| (*last, rest)); + bad(cmd, format!("text.{key} `{v}`: use \"{}\" or \"{}\"", rest.join("\", \""), last)) + }) }; let spaces_to_tab = match t.get("replaceSpaces") { None | Some(Value::Null) => None, @@ -58,11 +115,12 @@ impl TextOptions { as usize, ), }; + let set = choice("characterSet", &CHARACTER_SETS.map(|(name, _)| name))?; Ok(Self { - ansi: choice("characterSet", ["unicode", "ansi"])?, - mac: choice("platform", ["windows", "mac"])?, - remove_line_returns: bool_or(t, "removeLineReturns", false), - remove_paragraph_returns: bool_or(t, "removeParagraphReturns", false), + character_set: CHARACTER_SETS.get(set).map_or(CharacterSet::Unicode, |(_, s)| *s), + mac: choice("platform", &["windows", "mac"])? == 1, + remove_line_returns: switch_or(t, "removeLineReturns", false, cmd)?, + remove_paragraph_returns: switch_or(t, "removeParagraphReturns", false, cmd)?, spaces_to_tab, }) } @@ -80,10 +138,15 @@ pub(super) fn import(bytes: &[u8], o: TextOptions, cmd: &str) -> Result /// `bytes` as text: Unicode (UTF-8, or UTF-16 with a byte-order mark, or without one when the /// file has an even length, reads as valid UTF-16 with no NUL character in the byte order /// [`utf16_order_without_mark`] gives; bytes that aren't UTF-8 are read as the platform's 8-bit -/// set), or the platform's 8-bit character set. +/// set), the platform's 8-bit character set, or another set's decoder +/// ([`CharacterSet::encoding`]), which reads a byte-order mark as ordinary bytes and a malformed +/// sequence as U+FFFD. fn decode(bytes: &[u8], o: TextOptions) -> String { + if let Some(encoding) = o.character_set.encoding(o.mac) { + return encoding.decode_without_bom_handling(bytes).0.into_owned(); + } let eight_bit = |b: &[u8]| -> String { b.iter().map(|&c| if o.mac { mac_roman(c) } else { windows_1252(c) }).collect() }; - if o.ansi { + if o.character_set == CharacterSet::Ansi { return eight_bit(bytes); } let utf16 = |rest: &[u8], le: bool| { @@ -278,22 +341,76 @@ mod tests { assert_eq!(decode(&[0xFF, 0xFE, b'h', 0, 0xE9, 0], unicode), "hé", "UTF-16 LE"); assert_eq!(decode(&[0xFE, 0xFF, 0, b'h', 0x20, 0xAC], unicode), "h€", "UTF-16 BE"); assert_eq!(decode(&[b'c', b'a', b'f', 0xE9, 0x80], unicode), "café€", "not UTF-8: Windows-1252"); - let ansi = TextOptions { ansi: true, ..TextOptions::default() }; + let ansi = TextOptions { character_set: CharacterSet::Ansi, ..TextOptions::default() }; assert_eq!(decode(&[0x93, b'q', 0x94, 0xE9], ansi), "“q”é"); - let mac = TextOptions { ansi: true, mac: true, ..TextOptions::default() }; + let mac = TextOptions { character_set: CharacterSet::Ansi, mac: true, ..TextOptions::default() }; assert_eq!(decode(&[0xD2, b'q', 0xD3, 0x8E, 0xA5, 0xDB], mac), "“q”é•€"); } + /// The other character sets decode by their Encoding Standard decoders: the platform matters + /// for Cyrillic alone, a byte-order mark is read as ordinary bytes, and a malformed sequence + /// reads as U+FFFD. + #[test] + fn decodes_the_other_character_sets() { + let cases: [(CharacterSet, &[u8], &str); 9] = [ + (CharacterSet::ShiftJis, &[0x93, 0xFA, 0x96, 0x7B], "日本"), + (CharacterSet::Gb2312, &[0xD6, 0xD0, 0xCE, 0xC4], "中文"), + (CharacterSet::ChineseBig5, &[0xA4, 0xA4, 0xA4, 0xE5], "中文"), + (CharacterSet::Cyrillic, &[0xCF, 0xF0, 0xE8, 0xE2, 0xE5, 0xF2], "Привет"), + (CharacterSet::Gb18030, &[0x95, 0x32, 0x82, 0x36], "\u{20000}"), + (CharacterSet::Greek, &[0xC5, 0xEB, 0xEB, 0xDC, 0xE4, 0xE1], "Ελλάδα"), + (CharacterSet::Turkish, &[0xDD, 0x73, 0x74], "İst"), + (CharacterSet::Baltic, &[0x52, 0xEE, 0x67, 0x61], "Rīga"), + (CharacterSet::CentralEuropean, &[0xA3, 0xF3, 0x64, 0x9F], "Łódź"), + ]; + for (set, bytes, text) in cases { + let windows = TextOptions { character_set: set, ..TextOptions::default() }; + assert_eq!(decode(bytes, windows), text, "{set:?}"); + if set != CharacterSet::Cyrillic { + assert_eq!(decode(bytes, TextOptions { mac: true, ..windows }), text, "{set:?} from a Mac"); + } + } + let mac_cyrillic = TextOptions { character_set: CharacterSet::Cyrillic, mac: true, ..TextOptions::default() }; + assert_eq!(decode(&[0x8F, 0xF0, 0xE8, 0xE2, 0xE5, 0xF2], mac_cyrillic), "Привет"); + let shift_jis = TextOptions { character_set: CharacterSet::ShiftJis, ..TextOptions::default() }; + assert_eq!(decode(&[0x82, 0x22], shift_jis), "\u{FFFD}\"", "a lead byte before ASCII"); + assert_eq!(decode(&[b'a', 0x82], shift_jis), "a\u{FFFD}", "a lead byte at the end"); + let central = TextOptions { character_set: CharacterSet::CentralEuropean, ..TextOptions::default() }; + assert_eq!(decode(&[0xEF, 0xBB, 0xBF, b'A'], central), "A", "a UTF-8 byte-order mark is read as windows-1250"); + assert_eq!(decode(&[0xFF, 0xFE, b'A', 0], shift_jis), "\u{FFFD}\u{FFFD}A\0", "a UTF-16 byte-order mark is read as Shift JIS"); + } + #[test] fn options_parse_and_reject_bad_values() { let p = serde_json::json!({"text": {"characterSet": "ansi", "platform": "mac", "removeLineReturns": true, "replaceSpaces": 4}}); let o = TextOptions::parse(&p, "file.place").unwrap(); - assert_eq!(o, TextOptions { ansi: true, mac: true, remove_line_returns: true, remove_paragraph_returns: false, spaces_to_tab: Some(4) }); + assert_eq!( + o, + TextOptions { + character_set: CharacterSet::Ansi, + mac: true, + remove_line_returns: true, + remove_paragraph_returns: false, + spaces_to_tab: Some(4) + } + ); + for (name, set) in CHARACTER_SETS { + let o = TextOptions::parse(&serde_json::json!({"text": {"characterSet": name}}), "file.place").unwrap(); + assert_eq!(o.character_set, set, "{name}"); + } assert_eq!(TextOptions::parse(&serde_json::json!({}), "file.place").unwrap(), TextOptions::default()); - for bad in - [serde_json::json!({"text": 3}), serde_json::json!({"text": {"platform": "amiga"}}), serde_json::json!({"text": {"replaceSpaces": 1}})] - { + for bad in [ + serde_json::json!({"text": 3}), + serde_json::json!({"text": {"platform": "amiga"}}), + serde_json::json!({"text": {"replaceSpaces": 1}}), + serde_json::json!({"text": {"characterSet": 3}}), + serde_json::json!({"text": {"platform": true}}), + serde_json::json!({"text": {"removeLineReturns": "yes"}}), + serde_json::json!({"text": {"removeParagraphReturns": 1}}), + ] { assert!(TextOptions::parse(&bad, "file.place").is_err(), "{bad}"); } + let null = serde_json::json!({"text": {"characterSet": null, "platform": null, "removeLineReturns": null}}); + assert_eq!(TextOptions::parse(&null, "file.place").unwrap(), TextOptions::default(), "null leaves the default"); } } diff --git a/crates/engine/src/tests/textimport.rs b/crates/engine/src/tests/textimport.rs index cc89a8261b..980682f57e 100644 --- a/crates/engine/src/tests/textimport.rs +++ b/crates/engine/src/tests/textimport.rs @@ -135,6 +135,36 @@ fn text_files_report_and_queue_with_their_options() { assert!(close(frame, Rect::new(50.0, 60.0, 130.0, 100.0)), "{frame:?}"); } +/// Text Import Options' other character sets place their text as area type, and an unknown +/// character set is refused with the list of sets and places nothing. +#[test] +fn text_files_place_in_the_other_character_sets() { + let mut s = session(); + let cases: [(&str, &str, &[u8], &str); 11] = [ + ("shiftJis", "windows", &[0x93, 0xFA, 0x96, 0x7B], "日本"), + ("gb2312", "windows", &[0xD6, 0xD0, 0xCE, 0xC4], "中文"), + ("chineseBig5", "mac", &[0xA4, 0xA4, 0xA4, 0xE5], "中文"), + ("cyrillic", "windows", &[0xCF, 0xF0, 0xE8, 0xE2, 0xE5, 0xF2], "Привет"), + ("cyrillic", "mac", &[0x8F, 0xF0, 0xE8, 0xE2, 0xE5, 0xF2], "Привет"), + ("gb18030", "windows", &[0x95, 0x32, 0x82, 0x36], "\u{20000}"), + ("greek", "windows", &[0xC5, 0xEB, 0xEB, 0xDC, 0xE4, 0xE1], "Ελλάδα"), + ("turkish", "mac", &[0xDD, 0x73, 0x74], "İst"), + ("baltic", "windows", &[0x52, 0xEE, 0x67, 0x61], "Rīga"), + ("centralEuropean", "windows", &[0xA3, 0xF3, 0x64, 0x9F, b'\r', b'\n', 0xA3], "Łódź\nŁ"), + ("shiftJis", "windows", &[0x82, 0x22], "\u{FFFD}\""), + ]; + for (set, platform, bytes, text) in cases { + let r = place_text(&mut s, bytes, json!({"text": {"characterSet": set, "platform": platform}})); + assert_eq!(placed(&s, &r).0, text, "{set} on {platform}"); + } + let undo = s.doc().unwrap().history.undo.len(); + let bad = json!({"name": "a.txt", "dataBase64": "YQ==", "text": {"characterSet": "latin9"}}); + let err = s.execute("file.place", &bad).unwrap_err().to_string(); + let list = r#""unicode", "ansi", "shiftJis", "gb2312", "chineseBig5", "cyrillic", "gb18030", "greek", "turkish", "baltic" or "centralEuropean""#; + assert!(err.contains(&format!("text.characterSet `latin9`: use {list}")), "{err}"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo, "nothing placed"); +} + /// An RTF file with a font table, a color table, a bold run, an italic run, a superscript and a /// centered, indented second paragraph. const LETTER_RTF: &str = concat!( diff --git a/crates/engine/tests/text_import_fuzz.rs b/crates/engine/tests/text_import_fuzz.rs index 1ea656a158..c8417b73fc 100644 --- a/crates/engine/tests/text_import_fuzz.rs +++ b/crates/engine/tests/text_import_fuzz.rs @@ -17,7 +17,9 @@ proptest! { fn any_bytes_place_as_text_without_panics( bytes in prop::collection::vec(prop_oneof![any::(), Just(b'\r'), Just(b'\n'), Just(b' ')], 0..400), bom in prop::sample::select(vec![&b""[..], b"\xEF\xBB\xBF", b"\xFF\xFE", b"\xFE\xFF"]), - ansi in any::(), + set in prop::sample::select(vec![ + "unicode", "ansi", "shiftJis", "gb2312", "chineseBig5", "cyrillic", "gb18030", "greek", "turkish", "baltic", "centralEuropean", + ]), mac in any::(), lines in any::(), paras in any::(), @@ -31,7 +33,7 @@ proptest! { let mut s = vectorcraft_engine::Session::new(); s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); let text = json!({ - "characterSet": if ansi { "ansi" } else { "unicode" }, + "characterSet": set, "platform": if mac { "mac" } else { "windows" }, "removeLineReturns": lines, "removeParagraphReturns": paras, diff --git a/crates/ui-egui/src/dialogs/text_import.rs b/crates/ui-egui/src/dialogs/text_import.rs index 99128cc321..f0fe62b40d 100644 --- a/crates/ui-egui/src/dialogs/text_import.rs +++ b/crates/ui-egui/src/dialogs/text_import.rs @@ -3,7 +3,7 @@ //! places it as area type (`file.place` with `text`) and remembers the options: the next text file //! starts from them, and is placed with them when Show Import Options is off. //! -//! Fields: `platform` (`windows` | `mac`), `characterSet` (`unicode` | `ansi`), +//! Fields: `platform` (`windows` | `mac`), `characterSet` (one of [`CHARACTER_SETS`]), //! `removeLineReturns`, `removeParagraphReturns`, `replaceSpaces` (on or off), `spaces` (how many //! spaces make a tab, 2–100), and `__params` (the `file.place` params naming the file). @@ -22,6 +22,21 @@ pub(super) const SPEC: DialogSpec = /// The label column of the Encoding rows. const LABEL: f32 = 104.0; +/// The Character Set choices: `file.place`'s `text.characterSet` value and the menu label. +const CHARACTER_SETS: [(&str, &str); 11] = [ + ("unicode", "Unicode"), + ("ansi", "ANSI"), + ("shiftJis", "Shift JIS"), + ("gb2312", "GB2312"), + ("chineseBig5", "Chinese Big 5"), + ("cyrillic", "Cyrillic"), + ("gb18030", "GB18030"), + ("greek", "Greek"), + ("turkish", "Turkish"), + ("baltic", "Baltic"), + ("centralEuropean", "Central European"), +]; + /// Is the file `p` names (`path` or `name`) a text file? pub fn is_text(p: &Value) -> bool { let name = p.get("path").or_else(|| p.get("name")).and_then(Value::as_str).unwrap_or_default(); @@ -41,7 +56,8 @@ pub fn open(app: &mut VectorcraftApp, params: &Value) -> Value { "__params": params, }); let last = &app.ui.text_import; - for (k, wanted) in [("platform", ["windows", "mac"]), ("characterSet", ["unicode", "ansi"])] { + let sets = CHARACTER_SETS.map(|(value, _)| value); + for (k, wanted) in [("platform", &["windows", "mac"][..]), ("characterSet", &sets[..])] { if let Some(v) = last.get(k).and_then(Value::as_str).filter(|v| wanted.contains(v)) { fields[k] = json!(v); } @@ -68,7 +84,7 @@ pub fn last_options(app: &VectorcraftApp) -> Value { fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { widgets::subheader(ui, tl!("Encoding")); form::choice(ui, d, "platform", tl!("Platform:"), (LABEL, 180.0), &[("windows", "Windows"), ("mac", "Mac")]); - form::choice(ui, d, "characterSet", tl!("Character Set:"), (LABEL, 180.0), &[("unicode", "Unicode"), ("ansi", "ANSI")]); + form::choice(ui, d, "characterSet", tl!("Character Set:"), (LABEL, 180.0), &CHARACTER_SETS); ui.add_space(10.0); widgets::subheader(ui, tl!("Line Breaks")); for (key, label) in @@ -166,6 +182,39 @@ mod tests { assert_eq!(st.history.undo.len(), 1); } + /// Every character set is a choice: one confirmed last comes back on the next text file and + /// decodes it, an unknown remembered value falls back to Unicode, and with Show Import Options + /// off the remembered set is the one the file is placed with. + #[test] + fn a_remembered_character_set_comes_back_and_places_the_file() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); + let file = json!({"name": "notes.txt", "dataBase64": vectorcraft_format::base64_encode(&[0x93, 0xFA, 0x96, 0x7B])}); + app.ui.text_import = json!({"characterSet": "shiftJis", "platform": "windows"}); + app.run("file.place", file.clone()).unwrap(); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.str("characterSet")).as_deref(), Some("shiftJis")); + assert!(frame(&mut app).contains("Shift JIS"), "the remembered set is shown"); + let r = super::super::confirm(&mut app).unwrap(); + let st = app.session.doc().unwrap(); + let n = st.doc.node(vectorcraft_engine::doc::NodeId(r["ids"][0].as_u64().unwrap())).unwrap(); + let NodeKind::Text(t) = &n.kind else { panic!("type") }; + assert_eq!(t.plain_text(), "日本"); + assert_eq!(last_options(&app)["characterSet"], "shiftJis", "remembered for Show Import Options off"); + app.ui.text_import = json!({"characterSet": "latin9"}); + app.run("file.place", file).unwrap(); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.str("characterSet")).as_deref(), Some("unicode")); + let values: Vec<&str> = CHARACTER_SETS.iter().map(|(v, _)| *v).collect(); + let labels: Vec<&str> = CHARACTER_SETS.iter().map(|(_, l)| *l).collect(); + assert_eq!( + values, + ["unicode", "ansi", "shiftJis", "gb2312", "chineseBig5", "cyrillic", "gb18030", "greek", "turkish", "baltic", "centralEuropean"] + ); + assert_eq!( + labels, + ["Unicode", "ANSI", "Shift JIS", "GB2312", "Chinese Big 5", "Cyrillic", "GB18030", "Greek", "Turkish", "Baltic", "Central European"] + ); + } + /// A text file dropped on a canvas is placed by the dialog's OK in the document it was dropped /// on, even when another document became active meanwhile. #[test] diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 71e443a399..349779992f 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -404,6 +404,12 @@ font-technology Variable Променливи Character Alignment Подравняване на знаците Character / Paragraph Знак / Абзац Character Rotation Въртене на знак + Chinese Big 5 Китайски Big 5 + Cyrillic Кирилица + Greek Гръцки + Turkish Турски + Baltic Балтийски + Central European Централноевропейски Character Set: Набор от знаци: Character Style Стил на знак Character Style Options Опции за стил на знак diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 883d6dd387..1ac0184ff6 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -3273,6 +3273,12 @@ antiAlias Sharp Oštro LF (macOS, Linux) LF (macOS, Linux) CRLF (Windows) CRLF (Windows) Text Export Options Opcije izvoza teksta + Chinese Big 5 Kineski Big 5 + Cyrillic Ćirilica + Greek Grčki + Turkish Turski + Baltic Baltički + Central European Srednjoevropski Character Set: Skup znakova: Join the lines of each paragraph Spoji redove svakog pasusa Line Breaks Prelomi reda diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index a8a63cbf55..9587278ed4 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -677,6 +677,12 @@ antiAlias Sharp Nítid Character options Opcions de caràcter Paragraph options Opcions de paràgraf Character Rotation Rotació de caràcters + Chinese Big 5 Xinès Big 5 + Cyrillic Ciríl·lic + Greek Grec + Turkish Turc + Baltic Bàltic + Central European Centreeuropeu Character Set: Joc de caràcters: Character Style Estil de caràcter Character Style Options Opcions de l’estil de caràcter @@ -7946,3 +7952,4 @@ breakText Glyphs Glifs Open a document to mark its fold lines. Obre un document per marcar-ne les línies de plegat. Remove Fold Line Role Elimina el tipus de línia @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer ha de ser "singleLine", "everyLine", "standardSingleLine" o "standardEveryLine" +@msg text.{key} `{v}`: use "{_1}" or "{_2}" text.{key} `{v}`: utilitzeu "{_1}" o "{_2}" diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 569b1347ec..f4991a3561 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -3364,6 +3364,12 @@ antiAlias Sharp Ostré LF (macOS, Linux) LF (macOS, Linux) CRLF (Windows) CRLF (Windows) Text Export Options Možnosti exportu textu + Chinese Big 5 Čínština Big 5 + Cyrillic Cyrilice + Greek Řečtina + Turkish Turečtina + Baltic Baltské jazyky + Central European Středoevropské jazyky Character Set: Znaková sada: Join the lines of each paragraph Spojit řádky každého odstavce Line Breaks Zalomení řádků diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 4578e4efc1..8e7f7d807b 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -5776,6 +5776,12 @@ antiAlias Sharp Skarp LF (macOS, Linux) LF (macOS, Linux) CRLF (Windows) CRLF (Windows) Text Export Options Indstillinger for teksteksport + Chinese Big 5 Kinesisk Big 5 + Cyrillic Kyrillisk + Greek Græsk + Turkish Tyrkisk + Baltic Baltisk + Central European Centraleuropæisk Character Set: Tegnsæt: Join the lines of each paragraph Forbind linjerne i hvert afsnit Line Breaks Linjeskift diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index c943c89dd2..486117b13f 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -392,6 +392,12 @@ font-technology Variable Variabel Character Alignment Zeichenausrichtung Character / Paragraph Zeichen / Absatz Character Rotation Zeichendrehung + Chinese Big 5 Chinesisch Big 5 + Cyrillic Kyrillisch + Greek Griechisch + Turkish Türkisch + Baltic Baltisch + Central European Mitteleuropäisch Character Set: Zeichensatz: Character Style Zeichenformat Character Style Options Zeichenformatoptionen diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 906640aa0a..2768017599 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -390,6 +390,12 @@ font-technology Variable Μεταβλητές Character Alignment Στοίχιση χαρακτήρων Character / Paragraph Χαρακτήρας / Παράγραφος Character Rotation Περιστροφή χαρακτήρων + Chinese Big 5 Κινεζικά Big 5 + Cyrillic Κυριλλικά + Greek Ελληνικά + Turkish Τουρκικά + Baltic Βαλτικά + Central European Κεντρικής Ευρώπης Character Set: Σύνολο χαρακτήρων: Character Style Στυλ χαρακτήρων Character Style Options Επιλογές στυλ χαρακτήρων @@ -7920,3 +7926,4 @@ breakText Glyphs Γλύφοι Open a document to mark its fold lines. Ανοίξτε ένα έγγραφο για να σημειώσετε τις γραμμές δίπλωσής του. Remove Fold Line Role Αφαίρεση τύπου γραμμής @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" το composer πρέπει να είναι "singleLine", "everyLine", "standardSingleLine" ή "standardEveryLine" +@msg text.{key} `{v}`: use "{_1}" or "{_2}" text.{key} `{v}`: χρησιμοποιήστε "{_1}" ή "{_2}" diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 9239c93a73..bc05249b72 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -417,6 +417,12 @@ font-technology Variable Variables Character Alignment Alineación de caracteres Character / Paragraph Carácter / Párrafo Character Rotation Rotación de caracteres + Chinese Big 5 Chino Big 5 + Cyrillic Cirílico + Greek Griego + Turkish Turco + Baltic Báltico + Central European Centroeuropeo Character Set: Juego de caracteres: Character Style Estilo de carácter Character Style Options Opciones de estilo de carácter @@ -7907,3 +7913,4 @@ breakText Glyphs Glifos Open a document to mark its fold lines. Abre un documento para marcar sus líneas de plegado. Remove Fold Line Role Quitar tipo de línea @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer debe ser "singleLine", "everyLine", "standardSingleLine" o "standardEveryLine" +@msg text.{key} `{v}`: use "{_1}" or "{_2}" text.{key} `{v}`: use "{_1}" o "{_2}" diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 423703e5c1..f7f4bfb090 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -3308,6 +3308,12 @@ antiAlias Sharp Terävä LF (macOS, Linux) LF (macOS, Linux) CRLF (Windows) CRLF (Windows) Text Export Options Tekstin vientiasetukset + Chinese Big 5 Kiina Big 5 + Cyrillic Kyrillinen + Greek Kreikka + Turkish Turkki + Baltic Balttilainen + Central European Keskieurooppalainen Character Set: Merkistö: Join the lines of each paragraph Yhdistä kunkin kappaleen rivit Line Breaks Rivinvaihdot @@ -8003,3 +8009,4 @@ breakText Glyphs Merkit Open a document to mark its fold lines. Avaa asiakirja, niin voit merkitä sen taittoviivat. Remove Fold Line Role Poista viivatyyppi @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer on oltava "singleLine", "everyLine", "standardSingleLine" tai "standardEveryLine" +@msg text.{key} `{v}`: use "{_1}" or "{_2}" text.{key} `{v}`: käytä arvoa "{_1}" tai "{_2}" diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 8af602785b..eedcaebcd5 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -418,6 +418,12 @@ font-technology Variable Variables Character Alignment Alignement des caractères Character / Paragraph Caractère / Paragraphe Character Rotation Rotation des caractères + Chinese Big 5 Chinois Big 5 + Cyrillic Cyrillique + Greek Grec + Turkish Turc + Baltic Balte + Central European Europe centrale Character Set: Jeu de caractères : Character Style Style de caractère Character Style Options Options de style de caractère diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 4eed343e3d..679cd2800d 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -532,6 +532,11 @@ Character Color અક્ષર રંગ Character Direction અક્ષર દિશા Character Rotation અક્ષર પરિભ્રમણ + Chinese Big 5 ચાઇનીઝ Big 5 + Cyrillic સિરિલિક + Greek ગ્રીક + Baltic બાલ્ટિક + Central European મધ્ય યુરોપિયન Character Set: અક્ષર સેટ: Character Style Options અક્ષર સ્ટાઇલ વિકલ્પો Character Styles અક્ષર સ્ટાઇલ diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index de33cdbd92..70e64f6264 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -793,6 +793,11 @@ antiAlias Sharp शार्प Character Direction कैरेक्टर दिशा Character options कैरेक्टर ऑप्शन्स Character Rotation कैरेक्टर रोटेशन + Chinese Big 5 चीनी Big 5 + Cyrillic सिरिलिक + Greek ग्रीक + Baltic बाल्टिक + Central European मध्य यूरोपीय Character Set: कैरेक्टर सेट: Character Style कैरेक्टर स्टाइल Character Style Options कैरेक्टर स्टाइल ऑप्शन्स diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index f869e7d07b..95c1ea102c 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -576,6 +576,12 @@ font-technology Variable Változó Character options Karakterbeállítások Paragraph options Bekezdésbeállítások Character Rotation Karakterforgatás + Chinese Big 5 Kínai Big 5 + Cyrillic Cirill + Greek Görög + Turkish Török + Baltic Balti + Central European Közép-európai Character Set: Karakterkészlet: Character Style Karakterstílus Character Style Options Karakterstílus beállításai diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index c5f865e69b..65ebee437b 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -3053,6 +3053,12 @@ antiAlias Sharp Tajam LF (macOS, Linux) LF (macOS, Linux) CRLF (Windows) CRLF (Windows) Text Export Options Opsi ekspor teks + Chinese Big 5 Tionghoa Big 5 + Cyrillic Sirilik + Greek Yunani + Turkish Turki + Baltic Baltik + Central European Eropa Tengah Character Set: Set karakter: Join the lines of each paragraph Gabungkan baris setiap paragraf Line Breaks Pemisah baris diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 08cefdbed7..e06e410f2e 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -417,6 +417,12 @@ font-technology Variable Variabili Character Alignment Allineamento caratteri Character / Paragraph Carattere / Paragrafo Character Rotation Rotazione caratteri + Chinese Big 5 Cinese Big 5 + Cyrillic Cirillico + Greek Greco + Turkish Turco + Baltic Baltico + Central European Centroeuropeo Character Set: Set di caratteri: Character Style Stile carattere Character Style Options Opzioni stile carattere diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 59c7628f40..1863e9b064 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -1232,6 +1232,12 @@ antiAlias Sharp シャープ Channel チャンネル Character / Paragraph 文字/段落 Character Rotation 文字回転 + Chinese Big 5 中国語 Big 5 + Cyrillic キリル文字 + Greek ギリシャ語 + Turkish トルコ語 + Baltic バルト言語 + Central European 中央ヨーロッパ言語 Character Set: 文字セット: Character Style Options 文字スタイルオプション Check Links リンクを確認 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 9393433cdb..feeebed197 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -5025,6 +5025,11 @@ antiAlias Sharp მკვეთრი Encoding: კოდირება: Line Endings: სტრიქონის დაბოლოებები: Text Export Options ტექსტის ექსპორტის პარამეტრები + Chinese Big 5 ჩინური Big 5 + Cyrillic კირილიცა + Greek ბერძნული + Baltic ბალტიური + Central European ცენტრალურევროპული Character Set: სიმბოლოთა ნაკრები: Join the lines of each paragraph თითოეული აბზაცის სტრიქონების შეერთება Line Breaks სტრიქონის წყვეტები diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 49d5e10dc1..ee80c7d4fc 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -1222,6 +1222,12 @@ antiAlias Sharp 날카롭게 Channel 채널 Character / Paragraph 문자 / 단락 Character Rotation 문자 회전 + Chinese Big 5 중국어 Big 5 + Cyrillic 키릴 자모 + Greek 그리스어 + Turkish 터키어 + Baltic 발트어 + Central European 중앙 유럽어 Character Set: 문자 집합: Character Style Options 문자 스타일 옵션 Check Links 링크 확인 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index f071ebd0e2..c36fb37196 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -3670,6 +3670,12 @@ antiAlias Sharp Scherp LF (macOS, Linux) LF (macOS, Linux) CRLF (Windows) CRLF (Windows) Text Export Options Opties tekstexport + Chinese Big 5 Chinees Big 5 + Cyrillic Cyrillisch + Greek Grieks + Turkish Turks + Baltic Baltisch + Central European Centraal-Europees Character Set: Tekenset: Join the lines of each paragraph De regels van elke alinea samenvoegen Line Breaks Regeleinden diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 2477c73abd..62bb45d2ce 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -3245,6 +3245,12 @@ antiAlias Sharp Ostre Encoding: Kodowanie: Line Endings: Znaki końca wiersza: Text Export Options Opcje eksportu tekstu + Chinese Big 5 Chiński Big 5 + Cyrillic Cyrylica + Greek Grecki + Turkish Turecki + Baltic Bałtycki + Central European Środkowoeuropejski Character Set: Zestaw znaków: Join the lines of each paragraph Połącz wiersze każdego akapitu Line Breaks Podziały wierszy diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 333351b9af..66747c9dd5 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -386,6 +386,12 @@ antiAlias Sharp Nítido Character Alignment Alinhamento de Caracteres Character / Paragraph Caractere / Parágrafo Character Rotation Rotação de Caractere + Chinese Big 5 Chinês Big 5 + Cyrillic Cirílico + Greek Grego + Turkish Turco + Baltic Báltico + Central European Europa Central Character Set: Conjunto de Caracteres: Character Style Options Opções de Estilo de Caractere Character Styles Estilos de Caractere diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index ae33aa0d55..b0096dae74 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -415,6 +415,12 @@ font-technology Variable Вариативные Character Alignment Выравнивание символов Character / Paragraph Символ / Абзац Character Rotation Поворот символов + Chinese Big 5 Китайская Big 5 + Cyrillic Кириллица + Greek Греческая + Turkish Турецкая + Baltic Балтийская + Central European Центральноевропейская Character Set: Набор символов: Character Style Стиль символа Character Style Options Параметры стиля символа diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 1bd4fd0692..b3f2518306 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -406,6 +406,11 @@ font-technology Variable Variabla Character Alignment Teckenjustering Character / Paragraph Tecken / stycke Character Rotation Teckenrotation + Chinese Big 5 Kinesisk Big 5 + Cyrillic Kyrillisk + Greek Grekisk + Baltic Baltisk + Central European Centraleuropeisk Character Set: Teckenuppsättning: Character Style Teckenstil Character Style Options Alternativ för teckenstil diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index d21a146585..65aed727cb 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -515,6 +515,22 @@ fn monitor_profile_labels_are_in_complete_catalogs() { } } +/// Text Import Options' Character Set choices that name a script or a region (Shift JIS, GB2312 +/// and GB18030 are names of their own), and the error for an unknown character set. +#[test] +fn text_import_character_sets_are_in_complete_catalogs() { + for lang in LANGUAGES.iter().filter(|lang| lang.complete_menus) { + for label in ["Chinese Big 5", "Cyrillic", "Greek", "Turkish", "Baltic", "Central European"] { + assert!(lang.catalog().plain(label).is_some(), "{} is missing {label}", lang.code); + } + } + let unknown = r#"text.characterSet `x`: use "unicode", "ansi", "shiftJis", "gb2312", "chineseBig5", "cyrillic", "gb18030", "greek", "turkish", "baltic" or "centralEuropean""#; + for code in COMPLETE_MESSAGES { + let lang = Lang::from_code(code).expect("registered"); + assert_ne!(message(lang, unknown), unknown, "{code}"); + } +} + /// The Control bar panel menu's items, its groups of options and the edges, and the label of the /// command that turns a group on or off. #[test] diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index a2a38c679a..e19f7108d9 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -400,6 +400,12 @@ font-technology Variable Değişken Character Alignment Karakter Hizalaması Character / Paragraph Karakter / Paragraf Character Rotation Karakter Rotasyonu + Chinese Big 5 Çince Big 5 + Cyrillic Kiril + Greek Yunanca + Turkish Türkçe + Baltic Baltık + Central European Orta Avrupa Character Set: Karakter Seti: Character Style Karakter Stili Character Style Options Karakter Stili Seçenekleri diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 17c673885d..6154afe63a 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -411,6 +411,12 @@ font-technology Variable Варіативні Character Alignment Вирівнювання символів Character / Paragraph Символ / Абзац Character Rotation Поворот символів + Chinese Big 5 Китайська Big 5 + Cyrillic Кирилиця + Greek Грецька + Turkish Турецька + Baltic Балтійська + Central European Центральноєвропейська Character Set: Набір символів: Character Style Стиль символу Character Style Options Параметри стилю символу diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index da89525314..9934010d12 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -490,6 +490,12 @@ font-technology Variable Biến thiên Character options Tùy chọn ký tự Paragraph options Tùy chọn đoạn văn Character Rotation Xoay ký tự + Chinese Big 5 Tiếng Trung Big 5 + Cyrillic Chữ Kirin + Greek Tiếng Hy Lạp + Turkish Tiếng Thổ Nhĩ Kỳ + Baltic Vùng Baltic + Central European Trung Âu Character Set: Bộ ký tự: Character Style Kiểu ký tự Character Style Options Tùy chọn kiểu ký tự @@ -7577,3 +7583,4 @@ breakText Glyphs Glyph @msg {width} × {height} pixels is too large for Targa (at most 65535 pixels a side): lower the resolution {width} × {height} điểm ảnh quá lớn cho Targa (tối đa 65535 điểm ảnh mỗi cạnh): hãy giảm độ phân giải @msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution {w} × {h} điểm ảnh quá lớn cho PSD (tối đa {MAX_SIDE} điểm ảnh mỗi cạnh): hãy giảm độ phân giải @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer phải là "singleLine", "everyLine", "standardSingleLine" hoặc "standardEveryLine" +@msg text.{key} `{v}`: use "{_1}" or "{_2}" text.{key} `{v}`: hãy dùng "{_1}" hoặc "{_2}" diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 5f612cb0d4..6c65c68298 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -364,6 +364,12 @@ antiAlias Sharp 锐利 Character Alignment 字符对齐 Character / Paragraph 字符/段落 Character Rotation 字符旋转 + Chinese Big 5 繁体中文 Big 5 + Cyrillic 西里尔文 + Greek 希腊文 + Turkish 土耳其文 + Baltic 波罗的海文 + Central European 中欧文 Character Set: 字符集: Character Style 字符样式 Character Style Options 字符样式选项 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index e0b5a13ee2..90d51f28f1 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -379,6 +379,12 @@ font-technology Variable 可變 Character / Paragraph 字元/段落 Character Alignment 字元對齊 Character Rotation 字元旋轉 + Chinese Big 5 繁體中文 Big 5 + Cyrillic 西里爾文 + Greek 希臘文 + Turkish 土耳其文 + Baltic 波羅的海文 + Central European 中歐文 Character Set: 字元集: Character Style 字元樣式 Character Style Options 字元樣式選項 diff --git a/docs/control-protocol.md b/docs/control-protocol.md index df83c6eb04..5125dc0cb9 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -723,7 +723,7 @@ folder, then opens the dialog searching it. The web shows a status line instead disabled there. Text Import Options: placing a `.txt` file through the app (`file.place` with a file and no `text` options, the Place -dialog, a drop) opens the `textImport` dialog (fields `platform`: `windows`/`mac`, `characterSet`: `unicode`/`ansi`, +dialog, a drop) opens the `textImport` dialog (fields `platform`: `windows`/`mac`, `characterSet`: a `text.characterSet` value, `removeLineReturns`, `removeParagraphReturns`, `replaceSpaces`, `spaces`). `ui.dialog.confirm` places the file as area type with those options (`file.place {text: {…}}`). diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 9c46a01f77..cdeb60cfd8 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -308,7 +308,7 @@ Names in the editing data that aren't UTF-8 (layers, objects, artboards, colors, | Pixar PXR | open, place (legacy) | yes (any set of the R, G, B and A channels in 8 or 12 bits, dumped or run-length encoded, in tiles; R alone is gray; alpha matted to black or unassociated) | no | recognized by its magic number; 12-bit samples are clamped to 0.0 to 1.0; null tiles are transparent with A and black without; the offsets aren't read, and the image takes the default resolution; a file cut short, with header values or packets the format doesn't define, or past the pixel allowance is refused with a message; tested on synthetic files only; tests in `crates/engine/src/cmd/fileio/tests_pxrread.rs` and `crates/engine/tests/import_fuzz.rs` | | FreeHand `.fh*` | open (legacy) | no | no | | | CorelDRAW `.cdr` | open | no | no | | -| Text `.txt` | place, export | place (Text Import Options) | yes | | +| Text `.txt` | place, export | place (Text Import Options) | yes | place reads Unicode and ANSI, and Shift JIS, GB2312, Chinese Big 5, Cyrillic, GB18030, Greek, Turkish, Baltic and Central European through the WHATWG Encoding Standard's decoders (VectorCraft's own mapping); `tests/textimport.rs`, `place/text.rs`; fuzzed (`text_import_fuzz.rs`) | | RTF `.rtf` | place | place (area type with fonts, size, bold, italic, underline, strikethrough, caps, superscript and subscript, color, alignment, indents and paragraph spacing) | no | `tests/textimport.rs`, `place/rtf.rs`; fuzzed (`text_import_fuzz.rs`); `\'hh` bytes read as Windows-1252 or Mac Roman only | | Word `.docx` | place | place (area type with the document's styles and its fonts, size, bold, italic, underline, strikethrough, caps, superscript and subscript, color, alignment, indents and paragraph spacing) | no | `tests/textimport.rs`, `place/docx.rs`; fuzzed (`text_import_fuzz.rs`); list numbers, pictures and text boxes are left out | | Word `.doc` | place | place (area type with the same formatting as `.docx`, from the style sheet's styles and direct formatting; Word 97 and later) | no | `tests/textimport.rs`, `place/doc.rs`; fuzzed (`text_import_fuzz.rs`); pictures, headers, footers, notes, comments and text boxes are left out with a warning; encrypted and fast-saved documents are refused | diff --git a/docs/mcp.md b/docs/mcp.md index c7aa202d3f..731944110e 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -8055,10 +8055,15 @@ the document; so does `object.expand`. ``` Placing a text file (`.txt`) sets it as area type: `file.place {path | name+dataBase64, text?: {characterSet?: -"unicode" | "ansi", platform?: "windows" | "mac", removeLineReturns?, removeParagraphReturns?, replaceSpaces?: n}}` +"unicode" | "ansi" | "shiftJis" | "gb2312" | "chineseBig5" | "cyrillic" | "gb18030" | "greek" | "turkish" | "baltic" | +"centralEuropean", platform?: "windows" | "mac", removeLineReturns?, removeParagraphReturns?, replaceSpaces?: n}}` (Text Import Options). Unicode reads UTF-8, or UTF-16 with a byte-order mark; ANSI reads Windows-1252 (Mac Roman on -`mac`). Unicode reads a file without a byte-order mark as UTF-16 by the rule `dataset.import` uses: at least half of -its two-byte units hold a NUL byte, in the byte order that reads a line break, or for a file with one line, big-endian +`mac`). The other sets use the WHATWG Encoding Standard's decoders: `shiftJis` Shift_JIS, `gb2312` GBK, `chineseBig5` +Big5, `cyrillic` windows-1251 (x-mac-cyrillic on `mac`), `gb18030` gb18030, and `greek`, `turkish`, `baltic` and +`centralEuropean` windows-1253, 1254, 1257 and 1250 on both platforms. They read a byte-order mark as ordinary bytes +and a malformed sequence as U+FFFD. An unknown set, or an option of the wrong type (`characterSet: 3`, +`removeLineReturns: "yes"`), is an error, and nothing is placed. Unicode reads a file without a byte-order mark as +UTF-16 by the rule `dataset.import` uses: at least half of its two-byte units hold a NUL byte, in the byte order that reads a line break, or for a file with one line, big-endian when more of its units start with a NUL byte than end with one, and little-endian otherwise. Any other file is read as UTF-8, else as the platform's 8-bit set: one with fewer NUL bytes, one with an odd length, one where both byte orders read a line break, and one that isn't valid UTF-16 in that order or holds a NUL character. `removeLineReturns` joins diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 0782bacab9..47e1e77af8 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1967,6 +1967,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - The place cursor keeps an encrypted PDF, `.ai` or `.ait` file, at a letter page's size (VectorCraft's own size) and without a thumbnail, and a click or drag on it asks for its password, with the Place dialog's Show Import Options on or off; such a file was left out of the cursor before (`crates/engine/src/tests/place.rs`, `crates/ui-egui/src/tests/place.rs`). - File › Place with Bounding Box (`file.place {crop: "bounding"}`) measures the art that shows, with its strokes and effects, as an export does: hidden objects, guides and template layers do not count, a group whose only part on the page or artboard is hidden is not placed, and symbol instances are measured by their art, for `at`, `rect`, the place cursor and `file.place.info` (`crates/engine/src/tests/place.rs`). - The Place dialog has a Show Import Options checkbox after Link, Template and Replace ([Place multiple files in a document](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-other-file-types/place-multiple-files-in-a-document.html)). On (VectorCraft's default, saved with the preferences), each PDF, DXF or text file asks for its import options before it is placed, also in the place cursor; off (`file.place {showImportOptions: false}`), it is placed with the options last confirmed for its format, and only an encrypted PDF asks, for its password. Text Import Options now starts from the options confirmed last (`crates/ui-egui/src/tests/place.rs`). + - Text Import Options' Character Set offers Shift JIS, GB2312, Chinese Big 5, Cyrillic, GB18030, Greek, Turkish, Baltic and Central European beside Unicode and ANSI, the plain-text encodings [the help page](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-other-file-types/import-and-export-text.html) lists for placed text. `file.place {text: {characterSet}}` decodes each with its WHATWG Encoding Standard decoder. The mapping is VectorCraft's own: GB2312 reads as GBK, Cyrillic as windows-1251 (x-mac-cyrillic with `platform: "mac"`), and Greek, Turkish, Baltic and Central European as windows-1253, 1254, 1257 and 1250 on both platforms. A byte-order mark is read as ordinary bytes, a malformed sequence as U+FFFD, and the last set confirmed is remembered (`crates/engine/src/tests/textimport.rs`, `crates/ui-egui/src/dialogs/text_import.rs`). - Separations Preview shows placed and embedded raster images on the visible plates, as it shows vector art (#4153): an RGB image's pixels are separated into process inks with the proof setup's intent, a CMYK image shows its own inks, a hidden plate's ink leaves the image, and with one plate visible the image shows that plate's ink as a grey. Raster images carry no spot ink, so a spot plate shown alone shows them as paper; a colorized image shows its color's plates. Emoji and other bitmap glyphs follow the same rule. The plate-filtered pixels and their reduced-size copies are kept apart from the image's own pixels, for each set of visible plates, proof setup and color settings, and with the preview off nothing changes. Evidence: `tests::colorize::separations_preview_shows_an_rgb_images_process_inks`, `separations_preview_shows_a_cmyk_images_own_inks`, `separations_preview_keeps_an_images_pixels_per_plate_set`. Print preview fidelity remains the open gap, so scores and hours are unchanged. - Desktop print transport uses `craft-print` for CUPS and modern Windows. Sheet composition, copies, separations and colour management remain in VectorCraft. The Print dialog's Media list also carries the Japanese papers — JIS B4 257 × 364 mm, JIS B5 182 × 257 mm and JIS B6 128 × 182 mm beside the ISO B4/B5 (250 × 353 and 176 × 250 mm, kept so settings and presets saved before them keep their paper), and はがき 100 × 148 mm, 往復はがき 148 × 200 mm, 封筒 長形3号 120 × 235 mm, 長形4号 90 × 225 mm, 角形2号 240 × 332 mm, 角形3号 216 × 277 mm and 四六判 127 × 188 mm; the JSON id or the dialog label names a paper, any case and spacing (`B5 (JIS)` or `b5jis`) (`crates/pdf/src/print/settings.rs`, `crates/pdf/src/tests/print.rs`). The print-preview and physical-device fidelity gaps remain, so print scores and hours are unchanged. - A PDF, PDF-compatible `.ai` or `.ait` opened from its pages or its editing copy opens with the File Info that its XMP packet and its document information dictionary give: the title (`dc:title`, its `x-default` item first, else Info `Title`), the author, description, keywords, copyright status, notice and URL, and the created and modified dates, the XMP packet's value where both give one (`crates/pdf/src/tests/file_info.rs`, `crates/engine/src/tests/fileinfo.rs`). An SVG opens with the title of its root ``. The title is File Info's alone (`DocMetadata::title`): the document's name stays the file's name with its extension, a file that gives no title leaves File Info with that name, and exports (PDF, SVG, PNG, EPS, `.ai`) and native saves carry it; changing the title in File Info sets the document's name as before (#3626). From c762d276de0f2a4323283a4ec7c2bed7e25da267 Mon Sep 17 00:00:00 2001 From: el-j <bluearc.in.sky@gmail.com> Date: Sun, 15 Nov 2026 15:35:25 +0100 Subject: [PATCH 062/176] Part of #6861: Save PDF says in its dialog why a save failed --- crates/ui-egui/src/dialogs/save_pdf.rs | 31 ++++++++++++++++++-- crates/ui-egui/src/dialogs/save_pdf/tests.rs | 21 +++++++++++++ 2 files changed, 49 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/dialogs/save_pdf.rs b/crates/ui-egui/src/dialogs/save_pdf.rs index 4f8bdf7667..3e303a467e 100644 --- a/crates/ui-egui/src/dialogs/save_pdf.rs +++ b/crates/ui-egui/src/dialogs/save_pdf.rs @@ -143,10 +143,31 @@ fn params(d: &Dialog) -> Value { p } -/// Save PDF: write the file (a PDF copy, or the PDF a Save As / Save a Copy asked for, `__save`); -/// the dialog stays open when that fails (bad range, cancelled save…). While Save Preset… asks for -/// a name, OK (and Enter) saves the preset instead. +/// The field that holds why the last Save PDF failed, shown in the dialog (the status bar sits +/// behind it, #6861). +const ERROR: &str = "__error"; + +/// Save PDF: write the file (see [`write`]). When that fails the dialog stays open and says why, +/// under its sections, as well as in the status bar the dialog covers. fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> { + let r = write(app, d); + if let Some(open) = app.ui.dialog.as_mut().filter(|o| o.kind == d.kind) { + match &r { + Err(e) => { + open.fields.insert(ERROR.into(), json!(e)); + } + Ok(_) => { + open.fields.remove(ERROR); + } + } + } + r +} + +/// Write the file (a PDF copy, or the PDF a Save As / Save a Copy asked for, `__save`); the +/// dialog stays open when that fails (bad range, cancelled save…). While Save Preset… asks for a +/// name, OK (and Enter) saves the preset instead. +fn write(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> { if d.fields.contains_key(SAVE_AS) { let mut d = d.clone(); let r = save_preset(app, &mut d); @@ -408,6 +429,10 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { "Summary" => summary(app, ui, d), _ => general(ui, d, editor), }); + if let Some(e) = d.fields.get(ERROR).and_then(Value::as_str) { + ui.add_space(6.0); + ui.label(egui::RichText::new(crate::i18n::message(crate::i18n::current(), e)).color(t.error)); + } }); }); false diff --git a/crates/ui-egui/src/dialogs/save_pdf/tests.rs b/crates/ui-egui/src/dialogs/save_pdf/tests.rs index dbceed5881..e530c9748b 100644 --- a/crates/ui-egui/src/dialogs/save_pdf/tests.rs +++ b/crates/ui-egui/src/dialogs/save_pdf/tests.rs @@ -92,6 +92,27 @@ fn confirm_runs_export_pdf_with_the_dialog_options() { assert!(app.ui.status.starts_with("Saved /tmp/out.pdf"), "{}", app.ui.status); } +/// A Save PDF that fails keeps the dialog open and says why inside it (#6861): the status bar is +/// behind the dialog. Saving again, once it works, clears the message. +#[test] +fn a_failed_save_says_why_in_the_dialog() { + let (mut app, written, _) = app(); + app.run("ui.savePdfDialog", json!({"path": "/tmp/out.pdf"})).unwrap(); + set_field(&mut app, "__allArtboards", json!(false)); + set_field(&mut app, "range", json!("9")); + let e = super::super::confirm(&mut app).unwrap_err(); + assert!(written.borrow().is_empty(), "nothing was written"); + let d = app.ui.dialog.as_ref().expect("the dialog stays open"); + assert_eq!(d.str(ERROR), e, "the dialog holds the reason"); + assert!(!e.is_empty()); + assert!(params(d).get(ERROR).is_none(), "the message is not an option of the export"); + frame(&mut app); + set_field(&mut app, "range", json!("1")); + super::super::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(written.borrow().len(), 1); +} + /// Opened for a page of the art's bounds (Export As with Use Artboards off), the dialog has no /// Artboards section, and OK writes one page of the art's bounds with its options, a saved preset /// and View PDF after Saving included. From edecf9bf4103faa42cbaf75d8d04d2e4d5237803 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Mon, 16 Nov 2026 04:39:54 -0800 Subject: [PATCH 063/176] Shape Builder: the status bar says why a click or drag built nothing A Shape Builder gesture that builds nothing now says why when it is released: "select paths or compound paths" when nothing usable is selected, "select all paths you want to merge" when the pointer is over a path or compound path outside the selection, and "no region under the pointer" otherwise. The message changes nothing in the document, the selection or the undo history, and the next gesture that builds something clears it. A gesture made while a large selection's map is being built gives its message once, when it is replayed. Tools get Action::Status, which the session passes to the status bar; the new message has a row in every complete-message catalog. --- crates/engine/src/tests/build.rs | 33 +++++++++ crates/engine/src/tooling.rs | 1 + crates/tools/src/builder.rs | 64 ++++++++++++++-- crates/tools/src/builder/tests.rs | 111 ++++++++++++++++++++++++++-- crates/tools/src/input.rs | 4 + crates/ui-egui/src/i18n/ca.tsv | 1 + crates/ui-egui/src/i18n/cs.tsv | 1 + crates/ui-egui/src/i18n/da.tsv | 1 + crates/ui-egui/src/i18n/de.tsv | 1 + crates/ui-egui/src/i18n/el.tsv | 1 + crates/ui-egui/src/i18n/es.tsv | 1 + crates/ui-egui/src/i18n/fi.tsv | 1 + crates/ui-egui/src/i18n/fr.tsv | 1 + crates/ui-egui/src/i18n/hi.tsv | 1 + crates/ui-egui/src/i18n/hu.tsv | 1 + crates/ui-egui/src/i18n/it.tsv | 1 + crates/ui-egui/src/i18n/ja.tsv | 1 + crates/ui-egui/src/i18n/ka.tsv | 1 + crates/ui-egui/src/i18n/ko.tsv | 1 + crates/ui-egui/src/i18n/nl.tsv | 1 + crates/ui-egui/src/i18n/pl.tsv | 1 + crates/ui-egui/src/i18n/pt-br.tsv | 1 + crates/ui-egui/src/i18n/ru.tsv | 1 + crates/ui-egui/src/i18n/sv.tsv | 1 + crates/ui-egui/src/i18n/tests.rs | 15 ++++ crates/ui-egui/src/i18n/tr.tsv | 1 + crates/ui-egui/src/i18n/uk.tsv | 1 + crates/ui-egui/src/i18n/vi.tsv | 1 + crates/ui-egui/src/i18n/zh-hans.tsv | 1 + crates/ui-egui/src/i18n/zh-hant.tsv | 1 + docs/target-app-parity.md | 1 + 31 files changed, 241 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/tests/build.rs b/crates/engine/src/tests/build.rs index cf56247042..75c11d7d80 100644 --- a/crates/engine/src/tests/build.rs +++ b/crates/engine/src/tests/build.rs @@ -582,6 +582,39 @@ fn shape_builder_tool_drives_the_command() { assert_eq!(layer_children(&s), 1); } +/// A Shape Builder click that builds nothing puts the reason in the status bar and leaves the +/// document, its undo history and the selection as they were; a click that merges shows no status. +#[test] +fn shape_builder_click_that_builds_nothing_shows_why() { + use vectorcraft_tools::builder::{NO_REGION, SELECT_ALL_PATHS, SELECT_PATHS}; + let mut s = session(); + let (a, _) = two(&mut s); + let v = ViewInfo::default(); + s.select_tool("shapeBuilder", v).unwrap(); + let click = |s: &mut Session, x: f64, y: f64| { + s.pointer(&PointerEvent::new(PointerKind::Down, x, y), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, x, y), v).unwrap() + }; + let state = |s: &Session| { + let st = s.doc().unwrap(); + (st.revision, st.history.undo.len(), st.history.redo.len(), st.selection.objects.clone(), st.is_dirty()) + }; + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + let before = state(&s); + assert_eq!(click(&mut s, 125.0, 50.0), vec![UiRequest::Status(SELECT_ALL_PATHS.into())]); + assert_eq!(click(&mut s, 400.0, 400.0), vec![UiRequest::Status(NO_REGION.into())]); + assert_eq!(state(&s), before, "nothing changed"); + s.execute("select.none", &json!({})).unwrap(); + let before = state(&s); + assert_eq!(click(&mut s, 75.0, 50.0), vec![UiRequest::Status(SELECT_PATHS.into())]); + assert_eq!(state(&s), before, "nothing changed"); + s.execute("select.set", &json!({"ids": [a.0]})).unwrap(); + assert_eq!(click(&mut s, 75.0, 50.0), vec![UiRequest::Status(String::new())], "a click that merges clears the status"); + assert_eq!(s.journal.last().unwrap().0, "shapeBuilder.merge"); + assert!(click(&mut s, 25.0, 50.0).is_empty(), "the next merge shows no status"); + assert_eq!(s.journal.last().unwrap().0, "shapeBuilder.merge"); +} + /// A click of the Shape Builder merges over the map the tool built for the hover, as does the /// command over the same inputs with the same gap; another gap needs a map of its own. #[test] diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index 9250cf8030..542ee871d3 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -1530,6 +1530,7 @@ impl Session { } Action::Dialog(k, p) => ui.push(UiRequest::Dialog(k, p)), Action::SwitchTool(t) => ui.push(UiRequest::SwitchTool(t)), + Action::Status(msg) => ui.push(UiRequest::Status(msg)), Action::Notify(what) => { let view = self.last_view; self.with_tool_cx(view, |t, cx| t.notify(cx, &what)); diff --git a/crates/tools/src/builder.rs b/crates/tools/src/builder.rs index 51617935f5..18825cdfe5 100644 --- a/crates/tools/src/builder.rs +++ b/crates/tools/src/builder.rs @@ -211,8 +211,26 @@ pub struct ShapeBuilderTool { prepared: Option<Arc<PreparedMerge>>, /// A gesture made while the map of a large selection is being built on another thread. deferred: Option<Deferred>, + /// The button went down with nothing selected: the release says what to select. + empty_press: bool, + /// The last gesture put one of [`SHAPE_BUILDER_STATUS`] in the status bar: the next gesture that + /// builds something clears it. + diagnosed: bool, } +/// The status a Shape Builder gesture gives when the selection holds no path or compound path. +pub const SELECT_PATHS: &str = "Shape Builder: select paths or compound paths"; + +/// The status a Shape Builder gesture that touched nothing gives when it ends over a path or +/// compound path that is not selected. +pub const SELECT_ALL_PATHS: &str = "Shape Builder: select all paths you want to merge"; + +/// The status a Shape Builder gesture that touched nothing gives anywhere else. +pub const NO_REGION: &str = "Shape Builder: no region under the pointer"; + +/// The status messages the Shape Builder tool gives. +pub const SHAPE_BUILDER_STATUS: [&str; 3] = [SELECT_PATHS, SELECT_ALL_PATHS, NO_REGION]; + /// A Shape Builder gesture made while the map of the selection was being built on another /// thread: the map key and the inputs it was made over, its pointer events, which [`Tool::poll`] /// replays once the map is there, and whether the release has come. @@ -455,6 +473,26 @@ impl ShapeBuilderTool { } } + /// Why a gesture released at `p` that touched nothing built nothing: the selection gives no path + /// or compound path ([`SELECT_PATHS`]); the pointer is over a path or compound path that a click + /// can pick and that is neither selected nor inside a selected object ([`SELECT_ALL_PATHS`]); or + /// neither ([`NO_REGION`]). + fn nothing_built(&mut self, cx: &ToolContext, p: Point) -> Action { + self.diagnosed = true; + if self.cache.get(cx, self.opts.open_filled_as_closed).shapes.is_empty() { + return Action::Status(SELECT_PATHS.into()); + } + let unselected = vectorcraft_doc::hit::hit_test(cx.doc, p, cx.hit_options()).is_some_and(|h| { + let chain: Vec<NodeId> = h.ancestry.iter().copied().chain([h.leaf]).collect(); + let path = chain + .iter() + .filter_map(|id| cx.doc.node(*id)) + .any(|n| matches!(n.kind, NodeKind::Path { guide: false, clipping: false, .. } | NodeKind::Compound { .. })); + path && !chain.iter().any(|id| cx.selection.contains(*id)) + }); + Action::Status(if unselected { SELECT_ALL_PATHS } else { NO_REGION }.into()) + } + /// The cursor swatch preview: the swatch before the current fill, the current fill (ringed) /// and the swatch after it, side by side above the pointer. fn swatch_chips(&self, cx: &ToolContext) -> Vec<Overlay> { @@ -479,7 +517,9 @@ impl Tool for ShapeBuilderTool { vec![] } PointerKind::Down => { - // While a merge is being computed, a press starts no gesture. + // While a merge is being computed, a press starts no gesture. With nothing + // selected, the release says what to select. + self.empty_press = cx.selection.is_empty() && !self.editing(); if cx.selection.is_empty() || self.editing() { return vec![]; } @@ -564,7 +604,7 @@ impl Tool for ShapeBuilderTool { let press = points.first().copied().filter(|s| marquee.is_none() && !self.far && s.distance(p) <= cx.tol(CLICK_TOL_PX)); let split = press.filter(|q| self.stroke_at(cx, *q, erase).is_some()); if std::mem::take(&mut self.touched).is_empty() && split.is_none() { - return vec![]; + return vec![self.nothing_built(cx, p)]; } self.stroke = None; let roots = sorted_roots(cx.doc, &cx.selection.objects); @@ -590,11 +630,17 @@ impl Tool for ShapeBuilderTool { if self.opts.swatches { params["pickColorFrom"] = json!("swatches"); } + // The gesture builds something: the reason the last one built nothing goes. + let mut acts: Vec<Action> = std::mem::take(&mut self.diagnosed).then(|| Action::Status(String::new())).into_iter().collect(); // A large selection's merge is computed on another thread; `poll` applies it. - if self.start_merge(cx, ¶ms) { - return vec![]; + if !self.start_merge(cx, ¶ms) { + acts.push(Action::Exec("shapeBuilder.merge".into(), params)); } - vec![Action::Exec("shapeBuilder.merge".into(), params)] + acts + } + PointerKind::Up if std::mem::take(&mut self.empty_press) => { + self.diagnosed = true; + vec![Action::Status(SELECT_PATHS.into())] } _ => vec![], } @@ -693,6 +739,7 @@ impl Tool for ShapeBuilderTool { /// Choosing another tool or another document applies the merge being computed first. fn deactivate(&mut self, cx: &ToolContext) -> Vec<Action> { + self.empty_press = false; self.finish_edit(cx) } @@ -735,9 +782,11 @@ impl Tool for ShapeBuilderTool { /// With Pick Color From Color Swatches, the Left and Right arrow keys pick the color swatch /// before or after the current fill. Escape during a drag cancels it: the release after it - /// merges and deletes nothing. + /// merges and deletes nothing, and Escape while a press with nothing selected is held keeps its + /// release from showing a status. fn claims_key(&self, _cx: &ToolContext, key: ToolKey) -> bool { - (self.opts.swatches && !self.dragging && matches!(key, ToolKey::Left | ToolKey::Right)) || (self.dragging && key == ToolKey::Escape) + (self.opts.swatches && !self.dragging && matches!(key, ToolKey::Left | ToolKey::Right)) + || ((self.dragging || self.empty_press) && key == ToolKey::Escape) } /// The arrows pick swatches only without modifiers; Shift, Alt and Cmd/Ctrl arrows keep their @@ -753,6 +802,7 @@ impl Tool for ShapeBuilderTool { } if key == ToolKey::Escape { self.dragging = false; + self.empty_press = false; self.points.clear(); self.touched = Touched::default(); // A gesture recorded while the map is being built is canceled with it. diff --git a/crates/tools/src/builder/tests.rs b/crates/tools/src/builder/tests.rs index a88c14308b..84e686ccee 100644 --- a/crates/tools/src/builder/tests.rs +++ b/crates/tools/src/builder/tests.rs @@ -471,6 +471,106 @@ fn shape_builder_hover_builds_a_small_map_at_once() { assert_eq!((t.cache.builds, t.cache.background), (1, 0)); } +fn status(msg: &str) -> Vec<Action> { + vec![Action::Status(msg.into())] +} + +/// A click or drag with nothing selected shows what to select when it is released, and Escape +/// during the press keeps the release quiet. +#[test] +fn shape_builder_with_nothing_selected_says_what_to_select() { + let (d, _, _) = two_rects(); + let s = Selection::default(); + let p = paint(); + let cx = cx(&d, &s, &p); + let mut t = ShapeBuilderTool::default(); + assert!(t.pointer(&cx, &ev(PointerKind::Down, 75.0, 50.0)).is_empty()); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, 75.0, 50.0)), status(SELECT_PATHS), "a click"); + assert!(t.pointer(&cx, &ev(PointerKind::Down, 25.0, 50.0)).is_empty()); + assert!(t.pointer(&cx, &ev(PointerKind::Drag, 125.0, 50.0)).is_empty()); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, 125.0, 50.0)), status(SELECT_PATHS), "a drag"); + assert!(t.pointer(&cx, &ev(PointerKind::Up, 125.0, 50.0)).is_empty(), "a release without a press"); + t.pointer(&cx, &ev(PointerKind::Down, 75.0, 50.0)); + assert!(t.claims_key(&cx, ToolKey::Escape)); + assert!(t.key(&cx, ToolKey::Escape, Mods::default()).is_empty()); + assert!(t.pointer(&cx, &ev(PointerKind::Up, 75.0, 50.0)).is_empty(), "a canceled press"); + assert!(!t.claims_key(&cx, ToolKey::Escape)); +} + +/// With A of the overlapping squares A and B selected, a click on the part of B outside A builds +/// nothing and says to select every path to merge; a click on empty canvas says there is no +/// region; a click inside A still merges A alone and clears that status, and the click after it +/// gives the merge alone. +#[test] +fn shape_builder_names_the_unselected_path_under_a_release_that_built_nothing() { + let (d, a, _) = two_rects(); + let mut s = Selection::default(); + s.set([a]); + let p = paint(); + let cx = cx(&d, &s, &p); + let mut t = ShapeBuilderTool::default(); + t.pointer(&cx, &ev(PointerKind::Down, 125.0, 50.0)); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, 125.0, 50.0)), status(SELECT_ALL_PATHS)); + t.pointer(&cx, &ev(PointerKind::Down, 300.0, 300.0)); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, 300.0, 300.0)), status(NO_REGION)); + t.pointer(&cx, &ev(PointerKind::Down, 75.0, 50.0)); + let acts = t.pointer(&cx, &ev(PointerKind::Up, 75.0, 50.0)); + assert!( + matches!(acts.as_slice(), [Action::Status(m), Action::Exec(id, v)] if m.is_empty() && id == "shapeBuilder.merge" && v["ids"] == json!([a.0])), + "{acts:?}" + ); + t.pointer(&cx, &ev(PointerKind::Down, 75.0, 50.0)); + let acts = t.pointer(&cx, &ev(PointerKind::Up, 75.0, 50.0)); + assert!(matches!(acts.as_slice(), [Action::Exec(id, _)] if id == "shapeBuilder.merge"), "{acts:?}"); + // A locked or hidden B cannot be picked, so the release says there is no region. + for hide in [false, true] { + let (mut d, a, b) = two_rects(); + let n = d.node_mut(b).unwrap(); + if hide { + n.visible = false; + } else { + n.locked = true; + } + let mut s = Selection::default(); + s.set([a]); + let cx = crate::testutil::cx(&d, &s, &p); + let mut t = ShapeBuilderTool::default(); + t.pointer(&cx, &ev(PointerKind::Down, 125.0, 50.0)); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, 125.0, 50.0)), status(NO_REGION), "hidden: {hide}"); + } +} + +/// A selection that holds no path or compound path says to select one. +#[test] +fn shape_builder_with_no_path_selected_says_to_select_paths() { + let (mut d, a, _) = two_rects(); + d.node_mut(a).unwrap().locked = true; + let mut s = Selection::default(); + s.set([a]); + let p = paint(); + let cx = cx(&d, &s, &p); + let mut t = ShapeBuilderTool::default(); + t.pointer(&cx, &ev(PointerKind::Down, 75.0, 50.0)); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, 75.0, 50.0)), status(SELECT_PATHS)); +} + +/// A gesture made while the map of a large selection is being built and released over nothing +/// gives its status once, when it is replayed. +#[test] +fn shape_builder_replayed_gesture_over_nothing_gives_its_status_once() { + let (d, s) = square_row(200); + let p = paint(); + let cx = cx(&d, &s, &p); + let mut t = ShapeBuilderTool::default(); + t.pointer(&cx, &ev(PointerKind::Move, 15.0, 10.0)); + assert!(t.pointer(&cx, &ev(PointerKind::Down, 450.0, 450.0)).is_empty()); + assert_eq!(t.cache.builds, 0, "the gesture did not wait for the map"); + assert!(t.pointer(&cx, &ev(PointerKind::Up, 450.0, 450.0)).is_empty(), "the gesture waits for the map"); + assert!(t.editing()); + assert_eq!(t.finish_edit(&cx), status(NO_REGION)); + assert!(t.finish_edit(&cx).is_empty() && !t.editing()); +} + #[test] fn shape_builder_alt_drag_erases_and_empty_drag_does_nothing() { let (d, a, b) = two_rects(); @@ -485,7 +585,7 @@ fn shape_builder_alt_drag_erases_and_empty_drag_does_nothing() { let Action::Exec(_, v) = &acts[0] else { panic!() }; assert_eq!(v["erase"], true); t.pointer(&cx, &ev(PointerKind::Down, 300.0, 300.0)); - assert!(t.pointer(&cx, &ev(PointerKind::Up, 300.0, 300.0)).is_empty()); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, 300.0, 300.0)), status(NO_REGION), "the release edits nothing and says why"); } /// Squares A (0..100) and B (50..150 both ways), overlapping at a corner, selected. @@ -998,9 +1098,9 @@ fn shape_builder_stroke_options_round_trip_and_pick_the_side_under_the_pointer() let acts = t.pointer(&cx, &ev(PointerKind::Up, 0.5, 27.0)); let [Action::Exec(_, v)] = acts.as_slice() else { panic!("{acts:?}") }; assert_eq!((&v["splitStroke"], &v["points"]), (&json!(true), &json!([[-1.0, 25.0]]))); - // A release farther away is a drag, which splits nothing. + // A release farther away is a drag, which splits nothing and says it touched no region. t.pointer(&cx, &ev(PointerKind::Down, -1.0, 25.0)); - assert!(t.pointer(&cx, &ev(PointerKind::Up, -1.0, 30.0)).is_empty()); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, -1.0, 30.0)), status(NO_REGION)); // So is a Straight Line drag that goes away and ends back near the press. t.set_option("selection", &json!("straightLine")); t.pointer(&cx, &ev(PointerKind::Down, -1.0, 25.0)); @@ -1008,11 +1108,12 @@ fn shape_builder_stroke_options_round_trip_and_pick_the_side_under_the_pointer() let acts = t.pointer(&cx, &ev(PointerKind::Up, -0.5, 25.5)); assert!(!acts.iter().any(|a| matches!(a, Action::Exec(_, v) if v.get("splitStroke").is_some())), "{acts:?}"); t.set_option("selection", &json!("freeform")); - // A drag merges as before and sends no switch. + // A drag merges as before and sends no switch; it clears the status the drag before it gave. t.pointer(&cx, &ev(PointerKind::Down, 25.0, 25.0)); t.pointer(&cx, &ev(PointerKind::Drag, 75.0, 75.0)); let acts = t.pointer(&cx, &ev(PointerKind::Up, 75.0, 75.0)); - let [Action::Exec(_, v)] = acts.as_slice() else { panic!("{acts:?}") }; + let [Action::Status(m), Action::Exec(_, v)] = acts.as_slice() else { panic!("{acts:?}") }; + assert!(m.is_empty(), "{m}"); assert!(v.get("splitStroke").is_none(), "{v}"); } diff --git a/crates/tools/src/input.rs b/crates/tools/src/input.rs index 5362147b97..629970b066 100644 --- a/crates/tools/src/input.rs +++ b/crates/tools/src/input.rs @@ -218,4 +218,8 @@ pub enum Action { SwitchTool(String), /// Call the tool's `notify` after the preceding actions ran (e.g. to pick up a created object). Notify(String), + /// Show this English message in the status bar (e.g. why a Shape Builder gesture built + /// nothing); an empty message clears the status bar. It changes nothing in the document and + /// records no undo step. + Status(String), } diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index a8a63cbf55..2a70892ce6 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -6392,6 +6392,7 @@ liquify-list-end {0}, {1} {0} i {1} @msg shadings of more than 4096 patches or triangles were left out els ombrejats de més de 4096 pedaços o triangles s’han omès @msg shadings whose functions are of an unknown type are filled with their middle colour els ombrejats les funcions dels quals són d’un tipus desconegut s’omplen amb el seu color central @msg Shape Builder: no region under the pointer Constructor de formes: no hi ha cap regió sota el punter +@msg Shape Builder: select all paths you want to merge Constructor de formes: selecciona tots els traçats que vulguis combinar @msg Shape Builder: select paths or compound paths Constructor de formes: selecciona traçats o traçats compostos @msg shortcut for `{k}` must be a string la drecera de `{k}` ha de ser una cadena @msg Show All Hidden Attributes: nothing is hidden Mostra tots els atributs ocults: no hi ha res d’ocult diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 569b1347ec..bf55ba52ee 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -4972,6 +4972,7 @@ liquify-list-end {0}, {1} {0} a {1} @msg Saved {path} Uloženo: {path} @msg Select text or click into text with the Type tool to insert glyphs Glyfy vložíte, když vyberete text nebo do něj kliknete nástrojem Text @msg Shape Builder: no region under the pointer Tvorba tvarů: pod ukazatelem není žádná oblast +@msg Shape Builder: select all paths you want to merge Tvorba tvarů: vyberte všechny cesty, které chcete sloučit @msg Shape Builder: select paths or compound paths Tvorba tvarů: vyberte cesty nebo složené cesty @msg Show All Hidden Attributes: nothing is hidden Zobrazit všechny skryté atributy: nic není skryto @msg Split Into Grid: select paths large enough for the grid Rozdělit do mřížky: vyberte cesty dost velké pro mřížku diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 4578e4efc1..06d6b5b42c 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -7181,6 +7181,7 @@ imageTrace Outline Kontur @msg Saved {path} Gemte {path} @msg Select text or click into text with the Type tool to insert glyphs Markér tekst, eller klik i tekst med tekstværktøjet, for at indsætte glyffer @msg Shape Builder: no region under the pointer Figurbygger: intet område under markøren +@msg Shape Builder: select all paths you want to merge Figurbygger: markér alle kurver, du vil flette @msg Shape Builder: select paths or compound paths Figurbygger: markér kurver eller sammensatte kurver @msg Show All Hidden Attributes: nothing is hidden Vis alle skjulte attributter: intet er skjult @msg Split Into Grid: select paths large enough for the grid Opdel i gitter: markér kurver, der er store nok til gitteret diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index c943c89dd2..9e5a5a12a9 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -4570,6 +4570,7 @@ liquify-list-end {0}, {1} {0} und {1} @msg Saved {path} {path} gespeichert @msg Select text or click into text with the Type tool to insert glyphs Wählen Sie Text aus oder klicken Sie mit dem Text-Werkzeug in einen Text, um Glyphen einzufügen @msg Shape Builder: no region under the pointer Formerstellung: kein Bereich unter dem Zeiger +@msg Shape Builder: select all paths you want to merge Formerstellung: Wählen Sie alle Pfade aus, die Sie zusammenfügen möchten @msg Shape Builder: select paths or compound paths Formerstellung: Wählen Sie Pfade oder zusammengesetzte Pfade aus @msg Show All Hidden Attributes: nothing is hidden Alle ausgeblendeten Attribute einblenden: Es ist nichts ausgeblendet @msg Split Into Grid: select paths large enough for the grid In Raster teilen: Wählen Sie Pfade aus, die groß genug für das Raster sind diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 906640aa0a..7f0d2c21ca 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -2667,6 +2667,7 @@ liquify-list-end {0}, {1} {0} και {1} @msg Saved {path} Αποθηκεύτηκε το {path} @msg Select text or click into text with the Type tool to insert glyphs Επιλέξτε κείμενο ή κάντε κλικ μέσα σε κείμενο με το εργαλείο κειμένου για εισαγωγή γλύφων @msg Shape Builder: no region under the pointer Δημιουργία σχημάτων: δεν υπάρχει περιοχή κάτω από τον δείκτη +@msg Shape Builder: select all paths you want to merge Δημιουργία σχημάτων: επιλέξτε όλες τις διαδρομές που θέλετε να συγχωνεύσετε @msg Shape Builder: select paths or compound paths Δημιουργία σχημάτων: επιλέξτε διαδρομές ή σύνθετες διαδρομές @msg Show All Hidden Attributes: nothing is hidden Εμφάνιση όλων των κρυφών χαρακτηριστικών: δεν υπάρχουν κρυφά χαρακτηριστικά @msg Split Into Grid: select paths large enough for the grid Διαίρεση σε πλέγμα: επιλέξτε αρκετά μεγάλες διαδρομές για το πλέγμα diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 9239c93a73..d03ab51f1f 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -4676,6 +4676,7 @@ liquify-list-end {0}, {1} {0}, {1} @msg Saved {path} Se guardó {path} @msg Select text or click into text with the Type tool to insert glyphs Selecciona texto o haz clic dentro del texto con la herramienta Texto para insertar glifos @msg Shape Builder: no region under the pointer Generador de formas: no hay ninguna región bajo el puntero +@msg Shape Builder: select all paths you want to merge Generador de formas: selecciona todos los trazados que quieras combinar @msg Shape Builder: select paths or compound paths Generador de formas: selecciona trazados o trazados compuestos @msg Show All Hidden Attributes: nothing is hidden Mostrar todos los atributos ocultos: no hay nada oculto @msg Split Into Grid: select paths large enough for the grid Dividir en cuadrícula: selecciona trazados lo bastante grandes para la cuadrícula diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 423703e5c1..1b04d476f6 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -4909,6 +4909,7 @@ liquify-list-end {0}, {1} {0} ja {1} @msg Saved {path} Tallennettiin {path} @msg Select text or click into text with the Type tool to insert glyphs Valitse tekstiä tai napsauta tekstiin tekstityökalulla, niin voit lisätä merkkejä @msg Shape Builder: no region under the pointer Muodonmuodostin: osoittimen alla ei ole aluetta +@msg Shape Builder: select all paths you want to merge Muodonmuodostin: valitse kaikki polut, jotka haluat yhdistää @msg Shape Builder: select paths or compound paths Muodonmuodostin: valitse polkuja tai yhdistelmäpolkuja @msg Show All Hidden Attributes: nothing is hidden Näytä kaikki piilotetut attribuutit: mitään ei ole piilotettu @msg Split Into Grid: select paths large enough for the grid Jaa ruudukoksi: valitse ruudukolle riittävän suuret polut diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 1cff1c8ad0..a76032a6d2 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -4638,6 +4638,7 @@ liquify-list-end {0}, {1} {0} et {1} @msg Saved {path} {path} enregistré @msg Select text or click into text with the Type tool to insert glyphs Sélectionnez du texte ou cliquez dans un texte avec l’outil Texte pour insérer des glyphes @msg Shape Builder: no region under the pointer Concepteur de forme : aucune zone sous le pointeur +@msg Shape Builder: select all paths you want to merge Concepteur de forme : sélectionnez tous les tracés à fusionner @msg Shape Builder: select paths or compound paths Concepteur de forme : sélectionnez des tracés ou des tracés transparents @msg Show All Hidden Attributes: nothing is hidden Afficher tous les attributs masqués : rien n’est masqué @msg Split Into Grid: select paths large enough for the grid Découper en grille : sélectionnez des tracés assez grands pour la grille diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index de33cdbd92..b5dd19aed6 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -8221,6 +8221,7 @@ liquify-list-end {0}, {1} {0} और {1} @msg shadings of more than 4096 patches or triangles were left out 4096 से अधिक पैच या त्रिकोणों के छायांकन को छोड़ दिया गया था @msg shadings whose functions are of an unknown type are filled with their middle colour छायांकन जिसका कार्य अज्ञात प्रकार के होते हैं, उनके मध्य रंग से भरे होते हैं @msg Shape Builder: no region under the pointer आकृति बिल्डर: सूचक के तहत कोई क्षेत्र नहीं +@msg Shape Builder: select all paths you want to merge आकृति बिल्डर: वे सभी पाथ सिलेक्ट करें जिन्हें आप मर्ज करना चाहते हैं @msg Shape Builder: select paths or compound paths आकृति बिल्डर: पाथ या मिश्रित पाथ सिलेक्ट करें @msg Shaper needs 1–64 source paths शेपर के लिए 1–64 स्रोत पाथ चाहिए @msg shortcut for `{k}` must be a string `{k}` के लिए शॉर्टकट एक स्ट्रिंग होना चाहिए diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index f869e7d07b..a1eedeb72e 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -5904,6 +5904,7 @@ liquify-list-end {0}, {1} {0} és {1} @msg shadings of more than 4096 patches or triangles were left out kimaradtak a 4096-nál több foltból vagy háromszögből álló árnyalások @msg shadings whose functions are of an unknown type are filled with their middle colour az ismeretlen típusú függvényt használó árnyalások a középső színükkel kitöltve jelennek meg @msg Shape Builder: no region under the pointer Alakzatépítő: a mutató alatt nincs terület +@msg Shape Builder: select all paths you want to merge Alakzatépítő: jelöld ki az összes egyesítendő útvonalat @msg Shape Builder: select paths or compound paths Alakzatépítő: jelölj ki útvonalakat vagy összetett útvonalakat @msg shortcut for `{k}` must be a string `{k}` billentyűparancsa csak szöveg lehet @msg Show All Hidden Attributes: nothing is hidden Összes rejtett attribútum megjelenítése: nincs rejtett elem diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 08cefdbed7..e5cb65be6f 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -4704,6 +4704,7 @@ liquify-list-end {0}, {1} {0} e {1} @msg Saved {path} Salvato {path} @msg Select text or click into text with the Type tool to insert glyphs Seleziona del testo o fai clic nel testo con lo strumento Testo per inserire glifi @msg Shape Builder: no region under the pointer Generatore forme: nessuna regione sotto il puntatore +@msg Shape Builder: select all paths you want to merge Generatore forme: seleziona tutti i tracciati da unire @msg Shape Builder: select paths or compound paths Generatore forme: seleziona tracciati o tracciati composti @msg Show All Hidden Attributes: nothing is hidden Mostra tutti gli attributi nascosti: non c'è nulla di nascosto @msg Split Into Grid: select paths large enough for the grid Dividi in griglia: seleziona tracciati abbastanza grandi per la griglia diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 59c7628f40..2efb701c91 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -4570,6 +4570,7 @@ swatch Bright Violet ビビッドバイオレット @msg Live Paint: select paths or compound paths ライブペイント: パスまたは複合パスを選択してください @msg Live Paint: these paths are too degenerate to paint ライブペイント: これらのパスは形状がつぶれすぎていてペイントできません @msg Shape Builder: no region under the pointer シェイプ形成ツール: ポインターの下に領域がありません +@msg Shape Builder: select all paths you want to merge シェイプ形成ツール: 結合するパスをすべて選択してください @msg Shape Builder: select paths or compound paths シェイプ形成ツール: パスまたは複合パスを選択してください @msg image data `{_1}` is missing 画像データ `{_1}` が見つかりません @msg no Live Paint edge near that point その位置の近くにライブペイントのエッジがありません diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 9393433cdb..840c2d9d55 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -6392,6 +6392,7 @@ font-technology Variable ცვლადი @msg Saved {path} შენახულია: {path} @msg Select text or click into text with the Type tool to insert glyphs გლიფების ჩასასმელად მონიშნეთ ტექსტი ან ტექსტის ხელსაწყოთი დაწკაპეთ ტექსტში @msg Shape Builder: no region under the pointer ფიგურების კონსტრუქტორი: მაჩვენებლის ქვეშ არე არ არის +@msg Shape Builder: select all paths you want to merge ფიგურების კონსტრუქტორი: მონიშნეთ ყველა ტრაექტორია, რომლის გაერთიანებაც გსურთ @msg Shape Builder: select paths or compound paths ფიგურების კონსტრუქტორი: მონიშნეთ ტრაექტორიები ან შედგენილი ტრაექტორიები @msg Show All Hidden Attributes: nothing is hidden ყველა დამალული ატრიბუტის ჩვენება: დამალული არაფერია @msg Split Into Grid: select paths large enough for the grid ბადედ გაყოფა: მონიშნეთ ბადისთვის საკმარისად დიდი ტრაექტორიები diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 49d5e10dc1..1ff2189c69 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -4497,6 +4497,7 @@ theme Appearance 외관 @msg Live Paint: select paths or compound paths 라이브 페인트: 패스 또는 컴파운드 패스를 선택하세요 @msg Live Paint: these paths are too degenerate to paint 라이브 페인트: 이 패스는 퇴화되어 칠할 수 없습니다 @msg Shape Builder: no region under the pointer 모양 빌더: 포인터 아래에 영역이 없습니다 +@msg Shape Builder: select all paths you want to merge 모양 빌더: 병합할 패스를 모두 선택하세요 @msg Shape Builder: select paths or compound paths 모양 빌더: 패스 또는 컴파운드 패스를 선택하세요 @msg image data `{_1}` is missing 이미지 데이터 `{_1}`이(가) 없습니다 @msg no Live Paint edge near that point 그 지점 근처에 라이브 페인트 가장자리가 없습니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index f071ebd0e2..8d7a07ef4b 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -5076,6 +5076,7 @@ imageTrace Outline Contour @msg Saved {path} {path} opgeslagen @msg Select text or click into text with the Type tool to insert glyphs Selecteer tekst of klik met het tekstgereedschap in tekst om glyphs in te voegen @msg Shape Builder: no region under the pointer Vormbouwer: geen gebied onder de aanwijzer +@msg Shape Builder: select all paths you want to merge Vormbouwer: selecteer alle paden die je wilt samenvoegen @msg Shape Builder: select paths or compound paths Vormbouwer: selecteer paden of samengestelde paden @msg Show All Hidden Attributes: nothing is hidden Alle verborgen kenmerken tonen: er is niets verborgen @msg Split Into Grid: select paths large enough for the grid In raster verdelen: selecteer paden die groot genoeg zijn voor het raster diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 2477c73abd..27a3e7a0e4 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -4795,6 +4795,7 @@ liquify-list-end {0}, {1} {0} i {1} @msg Saved {path} Zapisano {path} @msg Select text or click into text with the Type tool to insert glyphs Zaznacz tekst lub kliknij w tekst narzędziem Tekst, aby wstawić glify @msg Shape Builder: no region under the pointer Kreator kształtów: brak obszaru pod wskaźnikiem +@msg Shape Builder: select all paths you want to merge Kreator kształtów: zaznacz wszystkie ścieżki, które chcesz scalić @msg Shape Builder: select paths or compound paths Kreator kształtów: zaznacz ścieżki lub ścieżki złożone @msg Show All Hidden Attributes: nothing is hidden Pokaż wszystkie ukryte atrybuty: nic nie jest ukryte @msg Split Into Grid: select paths large enough for the grid Podziel na siatkę: zaznacz ścieżki wystarczająco duże dla siatki diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 333351b9af..b21daa38e2 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -3991,6 +3991,7 @@ axis Both Ambos @msg Saved {path} {path} salvo @msg Select text or click into text with the Type tool to insert glyphs Selecione texto ou clique em um texto com a ferramenta Texto para inserir glifos @msg Shape Builder: no region under the pointer Criador de formas: nenhuma região sob o ponteiro +@msg Shape Builder: select all paths you want to merge Criador de formas: selecione todos os traçados que deseja mesclar @msg Shape Builder: select paths or compound paths Criador de formas: selecione traçados ou traçados compostos @msg Show All Hidden Attributes: nothing is hidden Mostrar todos os atributos ocultos: nada está oculto @msg Split Into Grid: select paths large enough for the grid Dividir em grade: selecione traçados grandes o bastante para a grade diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index ae33aa0d55..7b03b0cb13 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -4700,6 +4700,7 @@ liquify-list-end {0}, {1} {0} и {1} @msg Saved {path} Сохранено: {path} @msg Select text or click into text with the Type tool to insert glyphs Выделите текст или щёлкните внутри текста инструментом «Текст», чтобы вставить глифы @msg Shape Builder: no region under the pointer Создание фигур: под указателем нет области +@msg Shape Builder: select all paths you want to merge Создание фигур: выделите все контуры, которые нужно объединить @msg Shape Builder: select paths or compound paths Создание фигур: выделите контуры или составные контуры @msg Show All Hidden Attributes: nothing is hidden Показать все скрытые атрибуты: ничего не скрыто @msg Split Into Grid: select paths large enough for the grid Разделение на сетку: выделите контуры, достаточно большие для сетки diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 1bd4fd0692..a30113b183 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -4582,6 +4582,7 @@ liquify-list-end {0}, {1} {0} och {1} @msg Saved {path} Sparade {path} @msg Select text or click into text with the Type tool to insert glyphs Markera text eller klicka i text med textverktyget för att infoga glyfer @msg Shape Builder: no region under the pointer Formbyggare: inget område under pekaren +@msg Shape Builder: select all paths you want to merge Formbyggare: markera alla banor du vill sammanfoga @msg Shape Builder: select paths or compound paths Formbyggare: markera banor eller sammansatta banor @msg Show All Hidden Attributes: nothing is hidden Visa alla dolda attribut: ingenting är dolt @msg Split Into Grid: select paths large enough for the grid Dela upp i rutnät: markera banor som är tillräckligt stora för rutnätet diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 0daefad24a..99bac818f5 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -451,6 +451,21 @@ fn objects_on_path_detach_strings_are_in_complete_catalogs() { } } +/// The status messages the Shape Builder tool gives when a gesture builds nothing come from the +/// tools crate, which [`message_literals`] does not scan, so every complete catalog is checked for +/// them here. +#[test] +fn shape_builder_status_messages_are_in_complete_catalogs() { + use vectorcraft_tools::builder::SHAPE_BUILDER_STATUS; + for code in COMPLETE_MESSAGES { + let lang = Lang::from_code(code).expect("registered"); + for s in SHAPE_BUILDER_STATUS { + assert_ne!(message(lang, s), s, "{code}: {s}"); + } + } + assert_eq!(message(de(), SHAPE_BUILDER_STATUS[1]), "Formerstellung: Wählen Sie alle Pfade aus, die Sie zusammenfügen möchten"); +} + /// The Window › Brush Libraries menu, built from the built-in library table, names each library. #[test] fn built_in_brush_library_names_are_in_complete_catalogs() { diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index a2a38c679a..70e6670c99 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -4413,6 +4413,7 @@ liquify-list-end {0}, {1} {0} ve {1} @msg Saved {path} {path} kaydedildi @msg Select text or click into text with the Type tool to insert glyphs Glif eklemek için metni seçin veya Yazım aracıyla metne tıklayın @msg Shape Builder: no region under the pointer Şekil Oluşturucu: işaretçinin altında bölge yok +@msg Shape Builder: select all paths you want to merge Şekil Oluşturucu: birleştirmek istediğiniz tüm yolları seçin @msg Shape Builder: select paths or compound paths Şekil Oluşturucu: yolları veya bileşik yolları seçin @msg Show All Hidden Attributes: nothing is hidden Tüm Gizli Özellikleri Göster: hiçbir şey gizli değildir @msg Split Into Grid: select paths large enough for the grid Izgaraya Böl: ızgara için yeterince büyük yollar seçin diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 17c673885d..0045f02543 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -4688,6 +4688,7 @@ liquify-list-end {0}, {1} {0} і {1} @msg Saved {path} Збережено: {path} @msg Select text or click into text with the Type tool to insert glyphs Виділіть текст або клацніть всередині тексту інструментом «Текст», щоб вставити гліфи @msg Shape Builder: no region under the pointer Створення фігур: під вказівником немає області +@msg Shape Builder: select all paths you want to merge Створення фігур: виділіть усі контури, які потрібно об’єднати @msg Shape Builder: select paths or compound paths Створення фігур: виділіть контури або складені контури @msg Show All Hidden Attributes: nothing is hidden Показати всі приховані атрибути: нічого не приховано @msg Split Into Grid: select paths large enough for the grid Поділ на сітку: виділіть контури, досить великі для сітки diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index da89525314..35c8793bbc 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -5592,6 +5592,7 @@ liquify-list-end {0}, {1} {0} và {1} @msg shadings of more than 4096 patches or triangles were left out các vùng tô có hơn 4096 mảnh hoặc tam giác đã bị bỏ qua @msg shadings whose functions are of an unknown type are filled with their middle colour các vùng tô có hàm loại không xác định được tô bằng màu giữa @msg Shape Builder: no region under the pointer Xây dựng hình dạng: không có vùng nào dưới con trỏ +@msg Shape Builder: select all paths you want to merge Xây dựng hình dạng: chọn tất cả đường dẫn bạn muốn hợp nhất @msg Shape Builder: select paths or compound paths Xây dựng hình dạng: chọn đường dẫn hoặc đường dẫn phức @msg shortcut for `{k}` must be a string phím tắt cho `{k}` phải là chuỗi @msg Show All Hidden Attributes: nothing is hidden Hiện tất cả thuộc tính ẩn: không có gì bị ẩn diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 5f612cb0d4..932d8a96a1 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -4284,6 +4284,7 @@ imageTrace Outline 轮廓 @msg Live Paint: select paths or compound paths 实时上色:请选择路径或复合路径 @msg Live Paint: these paths are too degenerate to paint 实时上色:这些路径过于退化,无法上色 @msg Shape Builder: no region under the pointer 形状生成器:指针下方没有区域 +@msg Shape Builder: select all paths you want to merge 形状生成器:请选择要合并的所有路径 @msg Shape Builder: select paths or compound paths 形状生成器:请选择路径或复合路径 @msg image data `{_1}` is missing 缺少图像数据 `{_1}` @msg no Live Paint edge near that point 该点附近没有实时上色边缘 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index e0b5a13ee2..24e3f3e4b2 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -1915,6 +1915,7 @@ file-filter Templates 範本 @msg Live Paint: select paths or compound paths 即時上色:請選取路徑或複合路徑 @msg Live Paint: these paths are too degenerate to paint 即時上色:這些路徑過度退化,無法上色 @msg Shape Builder: no region under the pointer 形狀建立:指標下方沒有區域 +@msg Shape Builder: select all paths you want to merge 形狀建立:請選取要合併的所有路徑 @msg Shape Builder: select paths or compound paths 形狀建立:請選取路徑或複合路徑 @msg image data `{_1}` is missing 找不到影像資料 `{_1}` @msg no Live Paint edge near that point 該點附近沒有即時上色邊緣 diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 0782bacab9..58b230f0cb 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1295,6 +1295,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur As VectorCraft's own rule, OK in Shape Builder Tool Options gives an error for a highlight Color with an alpha part (`#rrggbbaa` or `#rgba`) and changes nothing. Regression test: `dialogs::shape_builder_options::tests::a_highlight_color_with_an_alpha_part_is_refused`. With Pick Color From Artwork, a merged shape takes the appearance, opacity and blending mode of the object where the drag starts, else of the object where it ends, else of the front-most selected object, as the [Shape Builder combine page](https://web.archive.org/web/20251006211643/https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/combine-shapes-with-shape-builder-tool.html) describes. A click in an area that no selected object covers, such as a hole other shapes enclose, takes the front-most selected object's look (`shapeBuilder.merge` `points`: the first point is where the drag starts, and the last point is where it ends). A Shift-drag with the Shape Builder tool draws a rectangular marquee for merging many paths at once, as [Combine shapes with the Shape Builder tool](https://web.archive.org/web/20251006211643/https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/combine-shapes-with-shape-builder-tool.html) describes: the regions it reaches are shaded while it is drawn and merge into one shape on release, or with Alt they are deleted. The marquee reaches each region whose outline crosses it or has an anchor inside it, and the region that holds the whole marquee; this rule is VectorCraft's own. For Pick Color From Artwork, the marquee's starting corner is where the drag starts and the opposite corner is where it ends (`shapeBuilder.merge` `rect`). + The Shape Builder works on the selected paths, as [Combine shapes with the Shape Builder tool](https://web.archive.org/web/20251006211643/https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/combine-shapes-with-shape-builder-tool.html) describes. As VectorCraft's own rule, a click or drag that builds nothing says why in the status bar when it is released: "Shape Builder: select paths or compound paths" when nothing is selected or the selection holds no unlocked, visible path; "Shape Builder: select all paths you want to merge" when the release is over a path or compound path that is not selected; and "Shape Builder: no region under the pointer" otherwise. The document, the selection and the undo history stay as they were, and the next gesture that builds something clears the message. Regression tests: `shape_builder_with_nothing_selected_says_what_to_select`, `shape_builder_names_the_unselected_path_under_a_release_that_built_nothing` and `shape_builder_replayed_gesture_over_nothing_gives_its_status_once` in `builder/tests.rs`, and `tests::build::shape_builder_click_that_builds_nothing_shows_why`. Shape Builder pieces on dense hatches (lines at exact 0.25 or 0.5 pt steps across another line) come back one per stretch between crossings, with no speck where the sweep cut a line's two passes a rounding error apart: the planar map contracts the stub between such cuts into one vertex, bounded by each cluster's extent so a run of tiny level segments keeps its length (`crates/pathops/src/planar.rs` tests `a_dense_hatch_at_exact_binary_steps_cuts_each_line_once_per_crossing`, `a_run_of_tiny_level_segments_is_not_contracted_as_stubs`, `a_line_crossed_where_its_two_passes_part_is_cut_once`). The planar map's edge-source grid stays linear in memory on any input: a segment is filed once per cell it crosses, and the grid holds at most a budget of cell references (a few dozen per item plus a few rows' worth), past which the remaining items go to a short scanned list and are still found, so thousands of coincident segments cannot make the index quadratic (`crates/pathops/src/planar.rs` test `rect_index_holds_a_bounded_number_of_references`). The Blob Brush Tool Options have Keep selected and Merge only with selection, both off by default: while Keep selected is off, the blob a stroke draws or merges into is not selected afterwards, and while Merge only with selection is on, a stroke merges only with selected blobs of its color that it touches (`path.blob` `keepSelected` and `mergeOnlySelection`). From 24e528abcf9296cc147df6cf4116930423f7ff00 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Mon, 16 Nov 2026 07:40:47 -0800 Subject: [PATCH 064/176] Type: Area Type Options First Baseline offers Em Box Height First Baseline gains Em Box Height (`text.areaOptions {firstBaseline: "emBoxHeight"}`, and the Area Type Options dropdown). The top of the first line's ideographic em box, the largest on a line of several sizes, touches the top of the type area inside the inset, in each row/column cell and in vertical type. It is the em box that Top-to-Top leading uses. Min is the least distance, as with the other kinds. Native files save it as `emBoxHeight`. The .ai reader reads editing-data kind 5 as Em Box Height and the writer writes it back; Legacy (6) and unknown kinds keep today's fallback. The dropdown's Ascent and x Height labels, and Fixed in Gujarati, get the catalog rows nine languages were missing, beside the new label in every catalog. Help page: https://helpx.adobe.com/illustrator/desktop/design-with-text/add-manage-text/add-margins-to-text-and-adjust-the-first-baseline.html --- crates/doc/src/text/para_style.rs | 2 + crates/doc/src/text/tests.rs | 14 +++++++ crates/engine/src/cmd/typecmd.rs | 2 +- crates/engine/src/cmd/typecmd/area_tests.rs | 38 ++++++++++++++++++ crates/eps/src/ai_editing/tests.rs | 31 +++++++++++++++ crates/eps/src/ai_editing/writer/texts.rs | 1 + crates/eps/src/import/ate.rs | 12 +++--- crates/text/src/layout/breaking.rs | 1 + crates/text/src/tests/typo.rs | 44 ++++++++++++++++++++- crates/text/src/tests/vertical.rs | 26 ++++++++++++ crates/text/src/tests/warichu.rs | 2 +- crates/ui-egui/src/dialogs/command.rs | 39 +++++++++++++++++- crates/ui-egui/src/i18n/bg.tsv | 1 + crates/ui-egui/src/i18n/bs.tsv | 1 + crates/ui-egui/src/i18n/ca.tsv | 1 + crates/ui-egui/src/i18n/cs.tsv | 1 + crates/ui-egui/src/i18n/da.tsv | 1 + crates/ui-egui/src/i18n/de.tsv | 3 ++ crates/ui-egui/src/i18n/el.tsv | 1 + crates/ui-egui/src/i18n/es.tsv | 1 + crates/ui-egui/src/i18n/fi.tsv | 1 + crates/ui-egui/src/i18n/fr.tsv | 1 + crates/ui-egui/src/i18n/gu.tsv | 4 ++ crates/ui-egui/src/i18n/hi.tsv | 1 + crates/ui-egui/src/i18n/hu.tsv | 1 + crates/ui-egui/src/i18n/id.tsv | 1 + crates/ui-egui/src/i18n/it.tsv | 3 ++ crates/ui-egui/src/i18n/ja.tsv | 3 ++ crates/ui-egui/src/i18n/ka.tsv | 1 + crates/ui-egui/src/i18n/ko.tsv | 3 ++ crates/ui-egui/src/i18n/nl.tsv | 1 + crates/ui-egui/src/i18n/pl.tsv | 1 + crates/ui-egui/src/i18n/pt-br.tsv | 1 + crates/ui-egui/src/i18n/ru.tsv | 1 + crates/ui-egui/src/i18n/sv.tsv | 1 + crates/ui-egui/src/i18n/tests.rs | 15 +++++++ crates/ui-egui/src/i18n/tr.tsv | 1 + crates/ui-egui/src/i18n/uk.tsv | 3 ++ crates/ui-egui/src/i18n/vi.tsv | 3 ++ crates/ui-egui/src/i18n/zh-hans.tsv | 3 ++ crates/ui-egui/src/i18n/zh-hant.tsv | 3 ++ docs/mcp.md | 17 ++++++++ docs/target-app-parity.md | 1 + 43 files changed, 281 insertions(+), 11 deletions(-) diff --git a/crates/doc/src/text/para_style.rs b/crates/doc/src/text/para_style.rs index 62c6b8dd33..17325d071c 100644 --- a/crates/doc/src/text/para_style.rs +++ b/crates/doc/src/text/para_style.rs @@ -631,6 +631,8 @@ pub enum FirstBaseline { XHeight, /// The first line's leading. Leading, + /// The top of the first line's ideographic em box touches the frame top. + EmBoxHeight, /// Exactly `first_baseline_min` below the top. Fixed, } diff --git a/crates/doc/src/text/tests.rs b/crates/doc/src/text/tests.rs index a5230d5d86..2a7237eda5 100644 --- a/crates/doc/src/text/tests.rs +++ b/crates/doc/src/text/tests.rs @@ -554,6 +554,20 @@ fn text_flow_is_saved_only_when_by_rows() { assert!(serde_json::from_value::<AreaOptions>(serde_json::json!({"flow": "diagonal"})).is_err()); } +/// First Baseline Em Box Height saves as `emBoxHeight` with its minimum and reads back; files from +/// before it read their own first baseline as they did, Ascent when they have none. +#[test] +fn em_box_height_first_baseline_is_saved_and_read_back() { + let set = AreaOptions { first_baseline: FirstBaseline::EmBoxHeight, first_baseline_min: 9.0, ..AreaOptions::default() }; + let saved = serde_json::to_value(&set).unwrap(); + assert_eq!((saved["firstBaseline"].as_str(), saved["firstBaselineMin"].as_f64()), (Some("emBoxHeight"), Some(9.0))); + assert_eq!(serde_json::from_value::<AreaOptions>(saved).unwrap(), set); + let old = serde_json::json!({"firstBaseline": "leading", "firstBaselineMin": 3.0}); + assert_eq!(serde_json::from_value::<AreaOptions>(old).unwrap().first_baseline, FirstBaseline::Leading); + assert_eq!(serde_json::from_value::<AreaOptions>(serde_json::json!({})).unwrap().first_baseline, FirstBaseline::Ascent); + assert!(serde_json::from_value::<AreaOptions>(serde_json::json!({"firstBaseline": "emBox"})).is_err()); +} + /// 120 × 40 area type at (40, 40), its text drawn at twice its size. fn area_type() -> TextObject { let mut t = TextObject::point(Point::ZERO, "Some text", CharStyle::default()); diff --git a/crates/engine/src/cmd/typecmd.rs b/crates/engine/src/cmd/typecmd.rs index c239cf040e..f50a2c7364 100644 --- a/crates/engine/src/cmd/typecmd.rs +++ b/crates/engine/src/cmd/typecmd.rs @@ -95,7 +95,7 @@ pub fn specs() -> Vec<CommandSpec> { "Area Type Options…", ["Type"], None, - "{ids?|id?, width?: pt, height?: pt, rows?, columns?, gutter?: pt (between rows and columns), rowGutter?: pt|null (between rows when it differs from gutter, which is then between columns; gutter given alone sets both; the reply gives the rows' gutter either way), inset?: pt, firstBaseline?: ascent|capHeight|xHeight|leading|fixed, firstBaselineMin?: pt, verticalAlign?: top|center|bottom|justify, flow?: columns|rows (Text Flow: down each column's rows, then across, the default; or across each row's columns, then down), fit?: none|autoHeight|shrinkText|block, fitMinPercent?: 10..100, wordGap?: % 0..1000, lineGap?: pt -1296..1296, …the keys of its own reply (it can be passed back; the values it only reports are ignored)} set the selected area type's options (each frame takes the options given over its own and keeps the rest; fit resolves against each frame's own; options that change nothing add no undo step); width and height size the type area from its top-left corner, along the type's own axes, and the text reflows at its size (with fit autoHeight, Auto Size, the frame's height follows the text after every edit and height is ignored; setting the height by hand turns it off); fit shrinkText scales overflowing text down (size, leading, baseline shift) by the largest factor down to fitMinPercent % (default 50) that makes it fit; fit block is Dynamic Text's Block, as type.dynamicText sets it (in place of Auto Size and Shrink Text to Fit; threaded frames are refused; another fit turns it off, keeping the sizes it wrote), and wordGap and lineGap set its gaps (kept while Block is off; out of range is an error) (none given: query) → the first object's options, plus wordGap and lineGap, overflow (the text doesn't fit its frame) and fitScale (Shrink Text's factor, 1 unshrunk)", + "{ids?|id?, width?: pt, height?: pt, rows?, columns?, gutter?: pt (between rows and columns), rowGutter?: pt|null (between rows when it differs from gutter, which is then between columns; gutter given alone sets both; the reply gives the rows' gutter either way), inset?: pt, firstBaseline?: ascent|capHeight|xHeight|leading|emBoxHeight|fixed (emBoxHeight: the top of the first line's ideographic em box, the largest on the line, touches the top of the type area inside the inset), firstBaselineMin?: pt (the least distance from that top to the first baseline; with fixed, the distance), verticalAlign?: top|center|bottom|justify, flow?: columns|rows (Text Flow: down each column's rows, then across, the default; or across each row's columns, then down), fit?: none|autoHeight|shrinkText|block, fitMinPercent?: 10..100, wordGap?: % 0..1000, lineGap?: pt -1296..1296, …the keys of its own reply (it can be passed back; the values it only reports are ignored)} set the selected area type's options (each frame takes the options given over its own and keeps the rest; fit resolves against each frame's own; options that change nothing add no undo step); width and height size the type area from its top-left corner, along the type's own axes, and the text reflows at its size (with fit autoHeight, Auto Size, the frame's height follows the text after every edit and height is ignored; setting the height by hand turns it off); fit shrinkText scales overflowing text down (size, leading, baseline shift) by the largest factor down to fitMinPercent % (default 50) that makes it fit; fit block is Dynamic Text's Block, as type.dynamicText sets it (in place of Auto Size and Shrink Text to Fit; threaded frames are refused; another fit turns it off, keeping the sizes it wrote), and wordGap and lineGap set its gaps (kept while Block is off; out of range is an error) (none given: query) → the first object's options, plus wordGap and lineGap, overflow (the text doesn't fit its frame) and fitScale (Shrink Text's factor, 1 unshrunk)", has_selection, area_options ), diff --git a/crates/engine/src/cmd/typecmd/area_tests.rs b/crates/engine/src/cmd/typecmd/area_tests.rs index aa6b75032d..a8aecac1d1 100644 --- a/crates/engine/src/cmd/typecmd/area_tests.rs +++ b/crates/engine/src/cmd/typecmd/area_tests.rs @@ -2613,6 +2613,44 @@ fn area_options_columns_change_layout() { assert!(s.execute("text.areaOptions", &json!({"firstBaseline": "nope"})).is_err()); } +/// First Baseline Em Box Height: set, reported and undone like the other kinds, with Min as the +/// least distance; setting it again adds no undo step, and the refusal of an unknown kind lists it. +#[test] +fn area_options_set_the_em_box_height_first_baseline() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + let id = s.execute("text.create", &json!({"x": 10, "y": 10, "text": "word ".repeat(20), "area": {"width": 300, "height": 120}})).unwrap()["id"] + .as_u64() + .unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + let first = |s: &Session| match &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind { + NodeKind::Text(t) => vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t).lines[0].first_baseline, + _ => panic!("area type"), + }; + let ascent = first(&s); + let r = s.execute("text.areaOptions", &json!({"firstBaseline": "emBoxHeight"})).unwrap(); + assert_eq!((r["firstBaseline"].as_str(), r["firstBaselineMin"].as_f64()), (Some("emBoxHeight"), Some(0.0))); + let em_box = first(&s); + assert!(em_box > 0.0 && (em_box - ascent).abs() > 0.1, "{em_box} {ascent}"); + let steps = s.doc().unwrap().history.undo.len(); + s.execute("text.areaOptions", &json!({"firstBaseline": "emBoxHeight"})).unwrap(); + assert_eq!(s.doc().unwrap().history.undo.len(), steps, "no change, no undo step"); + // A Min nearer the top keeps the em box; one further down is the distance. + s.execute("text.areaOptions", &json!({"firstBaselineMin": em_box / 2.0})).unwrap(); + assert!((first(&s) - em_box).abs() < 1e-9); + let r = s.execute("text.areaOptions", &json!({"firstBaselineMin": 30})).unwrap(); + assert_eq!((r["firstBaseline"].as_str(), r["firstBaselineMin"].as_f64()), (Some("emBoxHeight"), Some(30.0))); + assert!((first(&s) - 30.0).abs() < 1e-9); + for _ in 0..3 { + s.execute("edit.undo", &json!({})).unwrap(); + } + assert_eq!(s.execute("text.areaOptions", &json!({})).unwrap()["firstBaseline"], "ascent"); + assert!((first(&s) - ascent).abs() < 1e-9); + let e = s.execute("text.areaOptions", &json!({"firstBaseline": "emBox"})).unwrap_err().to_string(); + assert!(e.contains("emBoxHeight"), "{e}"); + assert_eq!(s.execute("text.areaOptions", &json!({})).unwrap()["firstBaseline"], "ascent"); +} + /// `rowGutter` sets a gutter between rows of its own, the reply passes it back, and a gutter /// given alone is the rows' and the columns' again. #[test] diff --git a/crates/eps/src/ai_editing/tests.rs b/crates/eps/src/ai_editing/tests.rs index f8e39a4048..476a6b0356 100644 --- a/crates/eps/src/ai_editing/tests.rs +++ b/crates/eps/src/ai_editing/tests.rs @@ -5397,6 +5397,37 @@ fn an_empty_last_frame_keeps_the_style_of_the_last_paragraph() { assert_eq!(justify, [Justify::Left, Justify::Right]); } +/// Each First Baseline kind the text document holds, Em Box Height included, comes back with its +/// minimum, without a warning. +#[test] +fn every_first_baseline_kind_comes_back_with_its_minimum() { + use vectorcraft_doc::{FirstBaseline, TextKind, TextObject}; + for (kind, min) in [ + (FirstBaseline::Ascent, 0.0), + (FirstBaseline::CapHeight, 6.0), + (FirstBaseline::XHeight, 0.0), + (FirstBaseline::Leading, 4.0), + (FirstBaseline::EmBoxHeight, 0.0), + (FirstBaseline::EmBoxHeight, 18.5), + (FirstBaseline::Fixed, 40.0), + ] { + let mut d = Document::new(300.0, 200.0); + let layer = d.layers[0].id; + let mut area = TextObject::point(vectorcraft_geom::Point::ZERO, "Area", style(12.0, Color::BLACK)); + area.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(20.0, 20.0, 140.0, 160.0)) }; + area.xf = Affine::IDENTITY; + area.area.first_baseline = kind; + area.area.first_baseline_min = min; + let n = text_node(&mut d, area); + d.insert(Some(layer), usize::MAX, n).unwrap(); + let warnings = export_ai_editing(&d, &opts()).unwrap().warnings; + assert!(warnings.is_empty(), "{kind:?}: {warnings:?}"); + let back = read_back(&d); + let NodeKind::Text(t) = &back.layers[0].children().unwrap()[0].kind else { panic!("type") }; + assert_eq!((t.area.first_baseline, t.area.first_baseline_min), (kind, min), "{kind:?}"); + } +} + /// A minimum first baseline with the Ascent first baseline is reported, and kept with the others. /// An end bracket of an open path that the reader would read as none is reported, and one further /// from the path's end comes back. diff --git a/crates/eps/src/ai_editing/writer/texts.rs b/crates/eps/src/ai_editing/writer/texts.rs index 506d13d9fc..d3c2c2e493 100644 --- a/crates/eps/src/ai_editing/writer/texts.rs +++ b/crates/eps/src/ai_editing/writer/texts.rs @@ -1002,6 +1002,7 @@ impl TextDoc { FirstBaseline::CapHeight => Some(2), FirstBaseline::Leading => Some(3), FirstBaseline::XHeight => Some(4), + FirstBaseline::EmBoxHeight => Some(5), }; if let Some(k) = kind { data.push((10, dict(vec![(0, V::Int(k)), (1, real(o.first_baseline_min / scale))]))); diff --git a/crates/eps/src/import/ate.rs b/crates/eps/src/import/ate.rs index 0c73b65092..160310dd4e 100644 --- a/crates/eps/src/import/ate.rs +++ b/crates/eps/src/import/ate.rs @@ -345,8 +345,9 @@ impl AreaFrame { 2 => F::CapHeight, 3 => F::Leading, 4 => F::XHeight, - // Em Box Height (5) and Legacy (6) have no first baseline of their own here: the - // first baseline stays as it was. + 5 => F::EmBoxHeight, + // Legacy (6) has no first baseline of its own here: the first baseline stays as it + // was. _ => return None, }; Some((kind, length(b.get("1")).unwrap_or(0.0))) @@ -2936,12 +2937,12 @@ mod tests { #[test] fn area_frame_first_baseline_kinds_and_minimum_are_read() { use vectorcraft_doc::FirstBaseline as F; - for (code, kind) in [(0, F::Fixed), (2, F::CapHeight), (3, F::Leading), (4, F::XHeight)] { + for (code, kind) in [(0, F::Fixed), (2, F::CapHeight), (3, F::Leading), (4, F::XHeight), (5, F::EmBoxHeight)] { let a = area_of(vec![area_frame(&format!("/10 << /0 {code} /1 30 >>"))], 0, 2.0); assert_eq!((a.first_baseline, a.first_baseline_min), (kind, 60.0), "code {code}"); } // A kind without its own first baseline here, or none known, leaves Ascent. - for code in ["1", "5", "6", "7", "-1", "2.5", "(x)"] { + for code in ["1", "6", "7", "-1", "2.5", "(x)"] { let a = area_of(vec![area_frame(&format!("/10 << /0 {code} /1 30 >>"))], 0, 1.0); assert_eq!((a.first_baseline, a.first_baseline_min), (F::Ascent, 0.0), "code {code}"); } @@ -2972,9 +2973,10 @@ mod tests { }; let placed = |options: &str| placed_in(&[options]); assert_eq!(placed("/10 << /0 2 /1 0 >>"), (false, vectorcraft_doc::FirstBaseline::CapHeight)); + assert_eq!(placed("/10 << /0 5 /1 0 >>"), (false, vectorcraft_doc::FirstBaseline::EmBoxHeight)); // Without one (Ascent), or with one that isn't read, the line goes where the file has it. assert_eq!(placed(""), (true, vectorcraft_doc::FirstBaseline::Fixed)); - assert_eq!(placed("/10 << /0 5 /1 0 >>"), (true, vectorcraft_doc::FirstBaseline::Fixed)); + assert_eq!(placed("/10 << /0 6 /1 0 >>"), (true, vectorcraft_doc::FirstBaseline::Fixed)); // Another frame of the thread keeping one doesn't count for the first. assert_eq!(placed_in(&["", "/10 << /0 2 /1 0 >>"]), (true, vectorcraft_doc::FirstBaseline::Fixed)); } diff --git a/crates/text/src/layout/breaking.rs b/crates/text/src/layout/breaking.rs index ef62fa2bcc..375bc343a2 100644 --- a/crates/text/src/layout/breaking.rs +++ b/crates/text/src/layout/breaking.rs @@ -47,6 +47,7 @@ impl Metrics { FirstBaseline::CapHeight => self.cap, FirstBaseline::XHeight => self.xh, FirstBaseline::Leading => self.lead, + FirstBaseline::EmBoxHeight => self.top, FirstBaseline::Fixed => 0.0, }; v.max(min) diff --git a/crates/text/src/tests/typo.rs b/crates/text/src/tests/typo.rs index 351c698451..be0b36124f 100644 --- a/crates/text/src/tests/typo.rs +++ b/crates/text/src/tests/typo.rs @@ -1329,6 +1329,40 @@ fn inset_and_first_baseline_options() { assert!(cap.lines[0].baseline < base.lines[0].baseline && cap.lines[0].baseline > 5.0); } +/// First Baseline Em Box Height: the top of the first line's ideographic em box (the one leading +/// measured from em box top to top uses) touches the top of the type area inside the inset. On a +/// line of several sizes the largest em box decides, and a Min further down sets the baseline. +#[test] +fn em_box_height_puts_the_first_lines_em_box_top_at_the_type_area_top() { + let frame = Rect::new(0.0, 0.0, 300.0, 300.0); + let em_box = |t: &TextObject, inset: f64, min: f64| { + let opts = LayoutOptions { first_baseline: FirstBaseline::EmBoxHeight, first_baseline_min: min, inset, ..Default::default() }; + layout_with(db(), t, &opts).lines[0].baseline + }; + // The em box top the EmBoxTop leading model sets a frame's first line at. + let em_top = |t: &TextObject| { + let mut t = t.clone(); + t.para.leading_model = vectorcraft_doc::LeadingModel::EmBoxTop; + layout(db(), &t).lines[0].baseline + }; + let t = area(COPY, style(12.0), frame, Justify::Left); + let top = em_top(&t); + assert!(top > 5.0 && top < 12.0, "{top}"); + let ascent = layout(db(), &t).lines[0].baseline; + assert!((top - ascent).abs() > 0.1, "not the ascent: {top} {ascent}"); + assert!((em_box(&t, 0.0, 0.0) - top).abs() < 1e-9); + assert!((em_box(&t, 10.0, 0.0) - (10.0 + top)).abs() < 1e-9, "measured from the inset"); + // A Min nearer the top than the em box changes nothing; one further down is the baseline. + assert!((em_box(&t, 10.0, top / 2.0) - (10.0 + top)).abs() < 1e-9); + assert!((em_box(&t, 10.0, 30.0) - 40.0).abs() < 1e-9); + // 10 pt and 20 pt on the first line: the 20 pt em box top is at the top. + let mut mixed = area("small Large", style(10.0), frame, Justify::Left); + mixed.runs = vec![run("small ", 10.0), run("Large", 20.0)]; + let large = area("Large", style(20.0), frame, Justify::Left); + assert!((em_box(&mixed, 0.0, 0.0) - em_box(&large, 0.0, 0.0)).abs() < 1e-9); + assert!((em_box(&large, 0.0, 0.0) - 2.0 * top * 10.0 / 12.0).abs() < 1e-6); +} + /// `LineInfo::first_baseline`: each line that starts a column has its baseline that far below the /// column's top inside the inset, for every first baseline option, with and without a minimum and /// an inset, in both leading models, and for lines of several sizes (each line in one size). @@ -1343,8 +1377,14 @@ fn lines_starting_a_column_sit_at_their_first_baseline() { let text: String = runs.iter().map(|r| r.text.as_str()).collect(); let mut other_sizes = 0; for model in [vectorcraft_doc::LeadingModel::RomanBaseline, vectorcraft_doc::LeadingModel::EmBoxTop] { - for first_baseline in [FirstBaseline::Ascent, FirstBaseline::CapHeight, FirstBaseline::XHeight, FirstBaseline::Leading, FirstBaseline::Fixed] - { + for first_baseline in [ + FirstBaseline::Ascent, + FirstBaseline::CapHeight, + FirstBaseline::XHeight, + FirstBaseline::Leading, + FirstBaseline::EmBoxHeight, + FirstBaseline::Fixed, + ] { for (first_baseline_min, inset) in [(0.0, 0.0), (18.0, 6.0)] { for height in [100.0, 120.0, 140.0] { let mut t = area(&text, style(12.0), Rect::new(0.0, 0.0, 420.0, height), Justify::Left); diff --git a/crates/text/src/tests/vertical.rs b/crates/text/src/tests/vertical.rs index dd12804e91..40c8076b2d 100644 --- a/crates/text/src/tests/vertical.rs +++ b/crates/text/src/tests/vertical.rs @@ -142,6 +142,32 @@ fn fit_first_line_widens_a_vertical_frame_from_its_right_edge() { assert_eq!(layout(FontDb::global(), &t).lines.len(), 1); } +/// First Baseline Em Box Height in vertical area type: the first column's em box edge touches the +/// frame's right edge inside the inset, as far in as leading measured from em box top to top sets +/// it. +#[test] +fn em_box_height_sets_a_vertical_frames_first_column_at_its_em_box() { + use vectorcraft_doc::{FirstBaseline, LeadingModel}; + let first = |fb: FirstBaseline, model: LeadingModel| { + let mut t = vertical("§§"); + t.kind = TextKind::Area { frame: PathData::from_bezpath(&Rect::new(0.0, 0.0, 100.0, 105.0).to_path(0.1)) }; + t.area.first_baseline = fb; + t.area.inset = 5.0; + t.para.leading_model = model; + let l = layout(FontDb::global(), &t); + (l.lines[0].baseline, l.lines[0].first_baseline) + }; + let (baseline, distance) = first(FirstBaseline::EmBoxHeight, LeadingModel::RomanBaseline); + let (em_top, _) = first(FirstBaseline::Ascent, LeadingModel::EmBoxTop); + let (ascent, ascent_distance) = first(FirstBaseline::Ascent, LeadingModel::RomanBaseline); + assert!((baseline - em_top).abs() < 1e-9, "{baseline} {em_top}"); + // Measured from the edge inside the inset, where a Fixed first baseline of 0 sits. + let (edge, _) = first(FirstBaseline::Fixed, LeadingModel::RomanBaseline); + assert!((baseline - distance - edge).abs() < 1e-9, "{baseline} {distance} {edge}"); + assert!((ascent - ascent_distance - edge).abs() < 1e-9, "{ascent} {ascent_distance} {edge}"); + assert!((baseline - ascent).abs() > 0.1, "not the ascent: {baseline} {ascent}"); +} + /// `baselines`: one per line that holds characters, along it for horizontal type and down the /// column's centre line for vertical type (where point type's anchor is); none on a path. #[test] diff --git a/crates/text/src/tests/warichu.rs b/crates/text/src/tests/warichu.rs index cbefb86bb5..7434e43db2 100644 --- a/crates/text/src/tests/warichu.rs +++ b/crates/text/src/tests/warichu.rs @@ -231,7 +231,7 @@ fn a_warichu_line_keeps_the_auto_leading_of_its_own_size() { #[test] fn the_first_baseline_measures_a_block_at_its_own_size() { use vectorcraft_doc::FirstBaseline; - for first in [FirstBaseline::Ascent, FirstBaseline::CapHeight, FirstBaseline::XHeight, FirstBaseline::Leading] { + for first in [FirstBaseline::Ascent, FirstBaseline::CapHeight, FirstBaseline::XHeight, FirstBaseline::Leading, FirstBaseline::EmBoxHeight] { let baseline = |inside: CharStyle| { let mut t = area("", style(20.0), Rect::new(0.0, 0.0, 300.0, 300.0), Justify::Left); t.area.first_baseline = first; diff --git a/crates/ui-egui/src/dialogs/command.rs b/crates/ui-egui/src/dialogs/command.rs index f5215092e8..bd0484c4d1 100644 --- a/crates/ui-egui/src/dialogs/command.rs +++ b/crates/ui-egui/src/dialogs/command.rs @@ -208,8 +208,14 @@ const PATH_ALIGN: form::Choices = &[("Ascender", "ascender"), ("Descender", "des const AREA_FIT: form::Choices = &[("None", "none"), ("Auto Size", "autoHeight"), ("Shrink Text to Fit", "shrinkText"), ("Block", "block")]; /// Area Type Options › First Baseline. -const FIRST_BASELINE: form::Choices = - &[("Ascent", "ascent"), ("Cap Height", "capHeight"), ("x Height", "xHeight"), ("Leading", "leading"), ("Fixed", "fixed")]; +const FIRST_BASELINE: form::Choices = &[ + ("Ascent", "ascent"), + ("Cap Height", "capHeight"), + ("x Height", "xHeight"), + ("Leading", "leading"), + ("Em Box Height", "emBoxHeight"), + ("Fixed", "fixed"), +]; /// Area Type Options › Align (vertical alignment of the lines in each row/column). const VERTICAL_ALIGN: form::Choices = &[("Top", "top"), ("Center", "center"), ("Bottom", "bottom"), ("Justify", "justify")]; @@ -271,6 +277,35 @@ mod tests { assert_eq!(t.area.vertical_align, VerticalAlign::Center); } + /// Area Type Options › First Baseline offers Em Box Height: OK sets it with its Min, and the + /// dialog opens again with it chosen. + #[test] + fn area_type_options_dialog_sets_the_em_box_height_first_baseline() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + let id = app.run("text.create", json!({"x": 20, "y": 20, "text": "Hello", "area": {"width": 200, "height": 200}})).unwrap()["id"] + .as_u64() + .unwrap(); + app.run("select.set", json!({"ids": [id]})).unwrap(); + // The labels `i18n::tests::first_baseline_choices_are_in_complete_catalogs` checks. + let labels: Vec<&str> = choices("text.areaOptions", "firstBaseline").unwrap().iter().map(|(l, _)| *l).collect(); + assert_eq!(labels, ["Ascent", "Cap Height", "x Height", "Leading", "Em Box Height", "Fixed"]); + crate::menus::invoke(&mut app, "text.areaOptions", json!({})); + assert_eq!(app.ui.dialog.as_ref().unwrap().str("firstBaseline"), "ascent"); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| crate::dialogs::show(&mut app, ui.ctx())); + out.textures_delta.clear(); + let fields = &mut app.ui.dialog.as_mut().unwrap().fields; + fields.insert("firstBaseline".into(), json!("emBoxHeight")); + fields.insert("firstBaselineMin".into(), json!(4.0)); + crate::dialogs::confirm(&mut app).unwrap(); + let NodeKind::Text(t) = &app.session.doc().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().kind else { panic!("text") }; + assert_eq!((t.area.first_baseline, t.area.first_baseline_min), (vectorcraft_doc::FirstBaseline::EmBoxHeight, 4.0)); + crate::menus::invoke(&mut app, "text.areaOptions", json!({})); + assert_eq!(app.ui.dialog.as_ref().unwrap().str("firstBaseline"), "emBoxHeight"); + } + /// Area Type Options shows the gutter between rows beside the gutter, and OK sets a gutter /// between rows of its own. #[test] diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 71e443a399..d739d4989a 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -5756,6 +5756,7 @@ lighting Light Светлина of от sRGB IEC61966-2.1 sRGB IEC61966-2.1 x Height Височина на x + Em Box Height Височина на квадратната касетка ▾ Default Actions ▾ Действия по подразбиране ⚠ {chord} was already used by {names} — it has been removed there. Внимание: Комбинацията {chord} вече се използва от {names} — премахната е там. @id file.close file.close diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 883d6dd387..d65970cbfe 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -5703,6 +5703,7 @@ imageTrace Outline Obris Ascent Uspon Cap Height Visina velikih slova x Height Visina malog slova x + Em Box Height Visina em okvira Justify Poravnaj obostrano First Baseline Prva osnovna linija Vertical Align Okomito poravnanje diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index a8a63cbf55..ea2d9c4868 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -5322,6 +5322,7 @@ digits Malayalam Malaiàlam Write Layers Escriu les capes Writes, moves or deletes files Escriu, mou o suprimeix fitxers x Height Alçada de la x + Em Box Height Alçada de la caixa em X11 (XWayland) X11 (XWayland) X11 (XWayland) When a Pen Is Attached X11 (XWayland) quan hi ha un llapis connectat X: X: diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 569b1347ec..d302279e32 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -6026,6 +6026,7 @@ liquify-list-end {0}, {1} {0} a {1} Ascent Výška nad účařím Cap Height Výška verzálek x Height Výška x + Em Box Height Výška čtverčíku Justify Do bloku First Baseline První účaří Vertical Align Svislé zarovnání diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 4578e4efc1..7448ae0314 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -8097,6 +8097,7 @@ imageTrace Outline Kontur Ascent Overhøjde Cap Height Versalhøjde x Height x-højde + Em Box Height Em-felthøjde Justify Justér First Baseline Første basislinje Vertical Align Lodret justering diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index c943c89dd2..f551b9a339 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -5366,6 +5366,9 @@ liquify-list-end {0}, {1} {0} und {1} Cap Height Versalhöhe x-Height x-Höhe ICF Box ICF-Rahmen + Ascent Oberlänge + x Height x-Höhe + Em Box Height Gevierthöhe Show Sample Muster einblenden Hide Sample Muster ausblenden Max Ascent/Descent Max. Höhe/Tiefe diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 906640aa0a..e6a38c3f8b 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -5941,6 +5941,7 @@ digits Malayalam Μαλαγιάλαμ [VectorCraft Default] [Προεπιλογή VectorCraft] of από x Height Ύψος x + Em Box Height Ύψος τετραγώνου em ▾ Default Actions ▾ Προεπιλεγμένες ενέργειες ⚠ {chord} was already used by {names} — it has been removed there. Προσοχή: το {chord} χρησιμοποιούνταν ήδη από {names} — αφαιρέθηκε από εκεί. @msg give corners of the path: anchors between two straight sides ορίστε τις γωνίες της διαδρομής: σημεία αγκύρωσης μεταξύ δύο ευθύγραμμων πλευρών diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 9239c93a73..574c1c50d8 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -5964,6 +5964,7 @@ effect Regular Regular Ascent Ascendente Cap Height Altura de mayúsculas x Height Altura de la x + Em Box Height Altura del cuadro eme Justify Justificar First Baseline Primera línea de base Vertical Align Alineación vertical diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 423703e5c1..4c674feafc 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -5942,6 +5942,7 @@ liquify-list-end {0}, {1} {0} ja {1} Ascent Nousu Cap Height Versaalikorkeus x Height x-korkeus + Em Box Height Em-laatikon korkeus Justify Tasaa molemmat reunat First Baseline Ensimmäinen perusviiva Vertical Align Pystytasaus diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 1cff1c8ad0..7b55bccb02 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -6237,6 +6237,7 @@ lighting Light Lumière of sur sRGB IEC61966-2.1 sRGB IEC61966-2.1 x Height Hauteur d’x + Em Box Height Hauteur du cadratin ▾ Default Actions ▾ Scripts par défaut ⚠ {chord} was already used by {names} — it has been removed there. Attention : {chord} était déjà utilisé par {names} ; il en a été retiré. @id file.close Fermer diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 4eed343e3d..e6e32ac6ac 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -4352,6 +4352,10 @@ tile {number} ટાઇલ {number} to થી x-Height x-ઊંચાઈ + Ascent એસેન્ટ + x Height x ઊંચાઈ + Fixed નિશ્ચિત + Em Box Height Em બૉક્સ ઊંચાઈ {count} of {total} artboards {total} માંથી {count} આર્ટબોર્ડ {effect} is already applied {effect} પહેલેથી લાગુ છે {file}, line {line} {file}, લાઇન {line} diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index de33cdbd92..25f4a34397 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -5738,6 +5738,7 @@ antiAlias Sharp शार्प Write Layers लेयर लिखें Writes, moves or deletes files फ़ाइलों को राइट्स, मूव या डिलीट करता है x Height x ऊँचाई + Em Box Height एम बॉक्स ऊँचाई X Position X स्थिति x-height x-ऊँचाई x-Height x-ऊँचाई diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index f869e7d07b..d13751bd22 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -4943,6 +4943,7 @@ mark-style Japanese Japán Wrinkle Tool Gyűrés Write Layers Rétegek írása x Height x-magasság + Em Box Height Kvirtmező magassága X11 (XWayland) When a Pen Is Attached X11 (XWayland), ha toll csatlakozik If a drawing tablet's pen doesn't draw, choose an X11 (XWayland) option. Ha a grafikus tábla tolla nem rajzol, válassz egy X11 (XWayland) beállítást. X11 (XWayland) X11 (XWayland) diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index c5f865e69b..ac89a615bc 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -5369,6 +5369,7 @@ imageTrace Outline Kontur Ascent Ascent Cap Height Tinggi kapital x Height Tinggi x + Em Box Height Tinggi Em Box Justify Ratakan First Baseline Baseline pertama Vertical Align Perataan vertikal diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 08cefdbed7..04f9889508 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -1045,6 +1045,9 @@ font-technology Variable Variabili Cap Height Altezza maiuscole x-Height Altezza x ICF Box Riquadro ICF + Ascent Ascendente + x Height Altezza x + Em Box Height Altezza riquadro em Show Sample Mostra campione Hide Sample Nascondi campione Max Ascent/Descent Altezza/profondità max diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 59c7628f40..c6757d1b02 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -49,6 +49,9 @@ font-technology Variable バリアブル Cap Height キャップハイト x-Height x ハイト ICF Box 平均字面 + Ascent アセント + x Height x ハイト + Em Box Height 仮想ボディの高さ Show Sample サンプルを表示 Hide Sample サンプルを隠す Max Ascent/Descent 最大アセント/ディセント diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 9393433cdb..d6a613507c 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -7359,6 +7359,7 @@ font-technology Variable ცვლადი Ascent ზედა გამონაშვერი Cap Height მთავრული ასოს სიმაღლე x Height x-სიმაღლე + Em Box Height Em-ბლოკის სიმაღლე Justify ორმხრივი სწორება First Baseline პირველი საბაზისო ხაზი Vertical Align ვერტიკალური სწორება diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 49d5e10dc1..1635c51fbb 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -43,6 +43,9 @@ font-technology Variable 가변 Cap Height 대문자 높이 x-Height x 높이 ICF Box ICF 박스 + Ascent 어센트 + x Height x 높이 + Em Box Height 엠 박스 높이 Show Sample 샘플 표시 Hide Sample 샘플 숨기기 Max Ascent/Descent 최대 어센트/디센트 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index f071ebd0e2..05a9d1b6ef 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -7817,6 +7817,7 @@ imageTrace Outline Contour Ascent Stijghoogte Cap Height Kaphoogte x Height x-hoogte + Em Box Height Em-vakhoogte Justify Uitvullen First Baseline Eerste basislijn Vertical Align Verticaal uitlijnen diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 2477c73abd..873104f5fc 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -5874,6 +5874,7 @@ liquify-list-end {0}, {1} {0} i {1} Ascent Wydłużenie górne Cap Height Wysokość wersalików x Height Wysokość x + Em Box Height Wysokość ramki firetowej Justify Justuj First Baseline Pierwsza linia bazowa Vertical Align Wyrównanie pionowe diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 333351b9af..9be13009ce 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -5953,6 +5953,7 @@ effect Regular Regular Ascent Ascensão Cap Height Altura das Maiúsculas x Height Altura do x + Em Box Height Altura da Caixa Eme Justify Justificar First Baseline Primeira Linha de Base Vertical Align Alinhamento Vertical diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index ae33aa0d55..e32f6022e2 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -6995,6 +6995,7 @@ axis Y Axis Ось Y [Press Quality] [Типографское качество] of из x Height Высота строчных + Em Box Height Высота кегельной площадки ▾ Default Actions ▾ Стандартные действия ⚠ {chord} was already used by {names} — it has been removed there. ⚠ {chord} уже было назначено: {names}; там оно удалено. @plural {n} shortcut is assigned more than once|{n} shortcuts are assigned more than once {n} сочетание клавиш назначено несколько раз|{n} сочетания клавиш назначены несколько раз|{n} сочетаний клавиш назначены несколько раз diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 1bd4fd0692..542e9222ec 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -6158,6 +6158,7 @@ lighting Light Ljus of av sRGB IEC61966-2.1 sRGB IEC61966-2.1 x Height x-höjd + Em Box Height Em-rutans höjd ▾ Default Actions ▾ Standardåtgärder ⚠ {chord} was already used by {names} — it has been removed there. Obs! {chord} användes redan av {names} – det har tagits bort där. @id file.close Stäng diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 0daefad24a..c465bb5328 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -434,6 +434,21 @@ fn font_height_reference_labels_are_in_complete_catalogs() { } } +/// Area Type Options › First Baseline's choices (the dropdown reads them in the "effect" context, +/// falling back to the plain row). +#[test] +fn first_baseline_choices_are_in_complete_catalogs() { + let mut missing = vec![]; + for lang in LANGUAGES.iter().filter(|lang| lang.complete_menus) { + for label in ["Ascent", "Cap Height", "x Height", "Leading", "Em Box Height", "Fixed"] { + if lang.catalog().plain(label).is_none() && lang.catalog().contextual("effect", label).is_none() { + missing.push(format!("{} {label}", lang.code)); + } + } + } + assert!(missing.is_empty(), "{missing:?}"); +} + /// The Objects on Path Options section's Detach button, its undo step and the message for a /// Detach with no object chosen. #[test] diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index a2a38c679a..b4beca188a 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -6014,6 +6014,7 @@ lighting Light Işık of arasında sRGB IEC61966-2.1 sRGB IEC61966-2.1 x Height x Yükseklik + Em Box Height Em Kutusu Yüksekliği ▾ Default Actions ▾ Varsayılan Eylemler ⚠ {chord} was already used by {names} — it has been removed there. ⚠ {chord} zaten {names} tarafından kullanılmıştı — oradan kaldırıldı. @id file.close Kapat diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 17c673885d..9692df3189 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -1039,6 +1039,9 @@ font-technology Variable Варіативні Cap Height Висота великих літер x-Height Висота малих літер ICF Box Рамка ICF + Ascent Підйом + x Height Висота малих літер + Em Box Height Висота кегельного майданчика Show Sample Показати зразок Hide Sample Приховати зразок Max Ascent/Descent Макс. висота/глибина diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index da89525314..08315ad0aa 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -2014,6 +2014,9 @@ digits Hindi Hindi Cap Height Chiều cao chữ hoa x-Height Chiều cao chữ x ICF Box Ô ICF + Ascent Độ cao nét trên + x Height Chiều cao chữ x + Em Box Height Chiều cao ô em Show Sample Hiện mẫu Hide Sample Ẩn mẫu Max Ascent/Descent Độ cao/sâu tối đa diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 5f612cb0d4..a24077a4ac 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -976,6 +976,9 @@ antiAlias Sharp 锐利 Cap Height 大写字母高度 x-Height x 字高 ICF Box ICF 框 + Ascent 上缘 + x Height x 字高 + Em Box Height 全角字框高度 Show Sample 显示样本 Hide Sample 隐藏样本 Max Ascent/Descent 最大上升/下降 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index e0b5a13ee2..cbfa7bbb62 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -1007,6 +1007,9 @@ font-technology Variable 可變 Cap Height 大寫字母高度 x-Height x 字高 ICF Box ICF 框 + Ascent 上緣 + x Height x 字高 + Em Box Height 全形字框高度 Show Sample 顯示樣本 Hide Sample 隱藏樣本 Max Ascent/Descent 最大上升/下降 diff --git a/docs/mcp.md b/docs/mcp.md index c7aa202d3f..5fbc7b9d5c 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -9365,6 +9365,23 @@ Native files save it only when it is `rows`, so files from before it open by col {"name":"run_command","arguments":{"command":"text.areaOptions","params":{"rows":2,"columns":3,"flow":"rows"}}} ``` +### First baseline + +`text.areaOptions {firstBaseline: ascent|capHeight|xHeight|leading|emBoxHeight|fixed, firstBaselineMin?: pt}` (Area +Type Options › First Baseline and Min) sets how far below the top of the type area, inside the inset, the first line +of each row/column cell sits. `emBoxHeight` (Em Box Height) puts the top of the line's ideographic em box at that +top; on a line of several sizes the largest em box is used, and vertical type measures it from the frame's right +edge. The em box is the one leading measured from em box top to top uses: an ideograph's cell in the font's +vertical metrics, or 0.88 em above the baseline when the font has none (VectorCraft's own rule). With every kind but +`fixed`, `firstBaselineMin` is the least distance from the top to the first baseline; with `fixed` it is the +distance. Each threaded frame keeps its own setting. Native files and `.ai` files save `emBoxHeight` and open it again; other values are refused. The help +page describes the option: +https://helpx.adobe.com/illustrator/desktop/design-with-text/add-manage-text/add-margins-to-text-and-adjust-the-first-baseline.html + +```json +{"name":"run_command","arguments":{"command":"text.areaOptions","params":{"firstBaseline":"emBoxHeight","firstBaselineMin":6}}} +``` + ## Fitting area type: Auto Size, Shrink Text to Fit, overflow `text.areaOptions` (and `text.create`'s `area`, `text.createInPath` in area mode) take a `fit`: diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 0782bacab9..1be6cfce83 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1468,6 +1468,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur For Auto Size area type in columns, the bisection for the frame's height runs on the lines of the one-column layout, and its result is checked with at most two layouts of the columns. When the text wraps around objects or does not fit the one-column layout, or when the check fails, the columns are laid out at every step of the bisection, as before. Typing at the start of a story of 50,000 characters in 2 columns took 1,670 ms a keystroke and now takes 292 ms (release build, `auto_height_in_columns_typing_timing`). Exports to PDF, EPS, SVG, EMF, WMF and the raster formats warn about the area type and type on a path that they draw without the text that doesn't fit, and give their ids, as Print and Print Preview do. On a shaped area type frame, Inset Spacing keeps text that far from the frame's edge, holes included, measured from the edge itself rather than along the line; the archived help treats the inset as the space an area type object leaves between its text and the path that bounds it (<https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=317>, <https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=325>). A rectangular frame keeps its inset from each side as before, and a column's inner edges keep it once. An edge that two contours of the frame share lies inside the frame, so text runs across it with no inset on either side, and a negative text wrap offset does not shrink a wrap object beside such an edge. Tests: `layout::region::inset_on_a_shaped_frame_is_measured_from_its_sloped_edge`, `inset_keeps_text_clear_of_a_hole_s_sloped_edges`, `inset_applies_once_at_a_column_s_edge_and_at_the_frame_s_edge`, `inset_is_not_kept_beside_an_edge_two_contours_share`, `negative_wrap_offset_does_not_shrink_beside_an_edge_two_contours_share`. + Area Type Options › First Baseline offers Em Box Height (`text.areaOptions {firstBaseline: "emBoxHeight"}`), which the help page describes as using the font's em box height (<https://helpx.adobe.com/illustrator/desktop/design-with-text/add-manage-text/add-margins-to-text-and-adjust-the-first-baseline.html>): the top of the first line's ideographic em box, the largest on a line of several sizes, touches the top of the type area inside the inset, in each row/column cell and in vertical type from the frame's right edge. The em box is the one Top-to-Top leading uses (VectorCraft's own measure: an ideograph's cell in the font's vertical metrics, else 0.88 em above the baseline), and Min is the least distance, as with the other kinds. Native files and `.ai` files save and open it; a `.ai` First Baseline kind VectorCraft does not read keeps today's fallback. Tests: `em_box_height_puts_the_first_lines_em_box_top_at_the_type_area_top`, `em_box_height_sets_a_vertical_frames_first_column_at_its_em_box`, `area_options_set_the_em_box_height_first_baseline`, `every_first_baseline_kind_comes_back_with_its_minimum`. An edit copies a thread's story only when it changes one of the thread's frames: with a story of 50,000 characters threaded through 8 frames with a style change at every word, moving another object took 7.8 ms and now takes 0.013 ms, and a frame of a drag took 7.2 ms and now takes 0.012 ms (release build, `threaded_story_edit_timing`). When a story flows through threaded area type, each frame is measured with the whole paragraphs of the story that it needs and a few more, not with the whole rest of the story, and it keeps the same text as before. A story of 1,500 one-line paragraphs (55,892 bytes) through 40 frames was laid out over 2,126,762 bytes of text while the frames were measured, and is now laid out over 21,035 (`thread::tests::many_frames_measure_about_the_text_they_take`). Area type with its lines aligned to the center, the bottom or justified vertically, and type on a path whose first paragraph is aligned Left, Justify Left, Justify All or Auto, are measured the same way: the same story through 40 area frames aligned to the center was laid out over 2,126,762 bytes and is now laid out over 21,035, through 40 paths aligned Left over 2,135,202 bytes and now over 20,583, and through 40 paths aligned Justify All over 2,135,202 bytes and now over 20,583 (same test). Shrink Text to Fit, Dynamic Text, Optical Margin Alignment and Roman Hanging Punctuation on a path, a path aligned to the center or the right, horizontal type on a path whose first paragraph is set right to left or with right-to-left text in the rest of the story, and a frame whose share ends in the story's last paragraph are still measured with the whole rest. A paragraph that continues from one threaded frame into the next has its first-line indent and bullet or number in the frame where it starts; in the next frame its first line starts where its wrapped lines start. In frames that are no longer threaded, copies of a frame and point type converted from one, the first paragraph has its indent and bullet or number again. From be4d00c615944ef66c9d1d32e94a65789b60ad63 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Mon, 16 Nov 2026 09:04:44 -0800 Subject: [PATCH 065/176] Symbols: a symbol dragged from another document places that document's symbol A symbol dragged from the Symbols panel carries the document it came from. Dropped on the canvas after another document became active, it no longer places a same-named symbol of the active document: symbol.placeFromDocument adds the dragged symbol, with the symbols and resources its art uses, and places it in one undo step. A symbol with the same name, art and Symbol Options is reused; one with the same name but other art or options is added under a free name. The pointer chip shows the dragged symbol, and a symbol whose document was closed places nothing. --- crates/engine/src/cmd/plugin_call.rs | 1 + crates/engine/src/cmd/symbollib.rs | 51 +++++++++- crates/engine/src/tests/symbollib.rs | 66 +++++++++++++ crates/ui-egui/src/canvas/context.rs | 9 +- crates/ui-egui/src/canvas/tests.rs | 103 +++++++++++++++++++- crates/ui-egui/src/panels/graphic_styles.rs | 2 +- crates/ui-egui/src/panels/swatches/dnd.rs | 3 +- crates/ui-egui/src/panels/symbols.rs | 11 ++- crates/ui-egui/src/widgets/drag.rs | 7 +- crates/ui-egui/src/widgets/look_tests.rs | 2 +- docs/mcp.md | 6 +- docs/target-app-parity.md | 1 + 12 files changed, 244 insertions(+), 18 deletions(-) diff --git a/crates/engine/src/cmd/plugin_call.rs b/crates/engine/src/cmd/plugin_call.rs index 6c23161a9d..867c1f2ff0 100644 --- a/crates/engine/src/cmd/plugin_call.rs +++ b/crates/engine/src/cmd/plugin_call.rs @@ -64,6 +64,7 @@ const DENIED_PREFIXES: &[&str] = &[ "edit.newDocument", "edit.colorSettings", "edit.dropSelection", + "symbol.placeFromDocument", "artboard.copy", "artboard.cut", "text.rescanFonts", diff --git a/crates/engine/src/cmd/symbollib.rs b/crates/engine/src/cmd/symbollib.rs index b82be77f43..3e4774a370 100644 --- a/crates/engine/src/cmd/symbollib.rs +++ b/crates/engine/src/cmd/symbollib.rs @@ -20,7 +20,7 @@ use super::clipboard::Clipboard; use super::clipboard::resources::SwatchChoices; use super::swatch::str_list; use super::swatchlib::{FileData, LibraryFile, LibraryInfo, concealed_library_id, concealed_library_ids, shown_id, shown_library_id, stem}; -use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, has_doc, number_or, str_param}; +use super::{CommandSpec, Result, Session, always, bad, bool_or, cmd, has_doc, number_or, str_param, u64_req}; /// The extension of saved symbol libraries: native documents. pub const SYMBOLS_EXT: &str = vectorcraft_format::EXTENSION; @@ -54,6 +54,15 @@ pub fn specs() -> Vec<CommandSpec> { has_doc, add ), + cmd!( + "symbol.placeFromDocument", + "Place Symbol Instance", + [], + None, + "{sourceDocument: uid, name: a symbol of that document, x?, y?} place an instance of a symbol of another open document so its registration point is at (x, y) (default: the first artboard's center), as a symbol dragged from that document's Symbols panel onto the canvas is placed. The symbol, the symbols it nests and the resources they use are added as a drop of art from that document adds them, in the same undo step as the instance: a symbol the active document already has with the same name, art and Symbol Options is used, and one with the same name but other art or Symbol Options gets a number (\"Leaf 2\"); each symbol added takes its Symbol Options along. When sourceDocument is the active document, its own symbol is placed, as symbol.place places it. An error, with no edit, when that document is no longer open or has no symbol `name` → {id, name: the symbol's name in the active document}", + has_doc, + place_from_document + ), cmd!( "symbol.saveLibrary", "Save Symbol Library…", @@ -630,6 +639,46 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> { Ok(out) } +/// `symbol.placeFromDocument`: an instance of symbol `name` of the open document `sourceDocument` +/// placed in the active document, with the symbol and the resources it uses added as a drop of +/// art from that document adds them, in one undo step. The source document is not changed. +fn place_from_document(s: &mut Session, p: &Value) -> Result<Value> { + const C: &str = "symbol.placeFromDocument"; + let uid = u64_req(p, "sourceDocument", C)?; + let name = str_param(p, "name").ok_or_else(|| bad(C, "missing `name`"))?; + let st = s.doc()?; + let centre = st.doc.artboards.first().map(|a| a.rect.center()).unwrap_or(Point::ZERO); + let at = Point::new(number_or(p, "x", centre.x, C)?, number_or(p, "y", centre.y, C)?); + let parent = st.target_parent()?; + let same = uid == st.uid; + let src = s.documents().iter().find(|d| d.uid == uid).map(|d| Arc::clone(&d.doc)); + let src = src.ok_or_else(|| bad(C, "the document the symbol came from is no longer open"))?; + if !src.symbols.iter().any(|sym| sym.name == name) { + return Err(bad(C, format!("no symbol named `{name}` in the document it came from"))); + } + // A symbol of the active document itself is placed as it is. + let clip = (!same).then(|| Clipboard::gather(&src, vec![instance(name)])); + // The source's colors are kept even where the active document has swatches of the same names. + let choices = SwatchChoices::parse(C, &json!({"swatchConflict": "add"}))?; + let (id, placed) = s.edit("Place Symbol Instance", |d, sel| { + let placed = match &clip { + // Each symbol added takes its Symbol Options along. + Some(clip) => { + let imported = clip.import_into(d, &choices, false)?; + let renamed = imported.renamed.iter().find(|r| r["kind"] == "symbol" && r["from"] == name).and_then(|r| r["to"].as_str()); + renamed.unwrap_or(name).to_string() + } + None => name.to_string(), + }; + let xf = place_xf(at, natural_size(d, &placed), d.symbol_registration(&placed)); + let id = d.alloc_id(); + d.insert(parent, usize::MAX, Node::new(id, NodeKind::SymbolInstance { symbol: placed.clone(), xf }))?; + sel.set([id]); + Ok((id, placed)) + })?; + Ok(json!({ "id": id.0, "name": placed })) +} + fn save(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "symbol.saveLibrary"; let st = s.doc()?; diff --git a/crates/engine/src/tests/symbollib.rs b/crates/engine/src/tests/symbollib.rs index c5d32e822a..02e45a7153 100644 --- a/crates/engine/src/tests/symbollib.rs +++ b/crates/engine/src/tests/symbollib.rs @@ -375,3 +375,69 @@ fn other_documents_symbols_load_and_unreadable_files_are_errors() { let bytes = vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap(); assert_eq!(vectorcraft_format::load(&bytes).unwrap().symbols.len(), 1); } + +/// `symbol.placeFromDocument` places another open document's symbol in the active document as +/// one undo step, with the symbol it nests, the pattern its art uses and its Symbol Options. A +/// second placement uses what the first added; the source document is left as it was; a symbol +/// of the active document itself is placed as it is; a closed document, a name the document does +/// not have and bad params are errors that change nothing. +#[test] +fn another_documents_symbol_is_added_and_placed_in_one_step() { + let mut s = kit(); + let source = s.doc().unwrap().uid; + let source_doc = s.doc().unwrap().doc.clone(); + run(&mut s, "file.new", json!({"width": 100, "height": 100})); + let before = undo_len(&s); + let r = run(&mut s, "symbol.placeFromDocument", json!({"sourceDocument": source, "name": "Badge", "x": 30, "y": 40})); + assert_eq!(undo_len(&s), before + 1, "added and placed in one step"); + assert_eq!(r["name"], "Badge"); + let mut names = symbols(&s); + names.sort(); + assert_eq!(names, ["Badge", "Star"], "the nested Star came along"); + assert_eq!(doc(&s).symbol_registration("Badge"), SymbolRegistration(0)); + let placed = NodeId(r["id"].as_u64().unwrap()); + assert_eq!(s.doc().unwrap().selection.objects, [placed]); + let NodeKind::SymbolInstance { symbol, .. } = &doc(&s).node(placed).unwrap().kind else { panic!("not an instance") }; + assert_eq!(symbol, "Badge"); + let size = |d: &vectorcraft_doc::Document| d.unknown.get("symbolSizes").and_then(|m| m.get("Badge")).cloned(); + assert!(size(doc(&s)).is_some()); + assert_eq!(size(doc(&s)), size(&source_doc)); + // The Dots symbol brings its pattern and swatch. + run(&mut s, "symbol.placeFromDocument", json!({"sourceDocument": source, "name": "Dots"})); + assert!(doc(&s).pattern("Dots").is_some() && doc(&s).swatch("Dots").is_some()); + // Placed again, Badge is the one already added. + let count = doc(&s).symbols.len(); + let r = run(&mut s, "symbol.placeFromDocument", json!({"sourceDocument": source, "name": "Badge"})); + assert_eq!((r["name"].as_str(), doc(&s).symbols.len()), (Some("Badge"), count)); + run(&mut s, "edit.undo", json!({})); + run(&mut s, "edit.undo", json!({})); + run(&mut s, "edit.undo", json!({})); + assert!(symbols(&s).is_empty() && doc(&s).pattern("Dots").is_none()); + // The active document's own symbol, by its uid: placed, nothing added. + run(&mut s, "shape.rectangle", json!({"x": 0, "y": 0, "width": 10, "height": 10})); + run(&mut s, "symbol.new", json!({"name": "Star"})); + let own = s.doc().unwrap().uid; + let before = undo_len(&s); + let r = run(&mut s, "symbol.placeFromDocument", json!({"sourceDocument": own, "name": "Star", "x": 70, "y": 70})); + assert_eq!((undo_len(&s), r["name"].as_str(), symbols(&s)), (before + 1, Some("Star"), vec!["Star".to_string()])); + // Errors change nothing. + let before = (undo_len(&s), doc(&s).clone()); + for p in [ + json!({"sourceDocument": source, "name": "Nope"}), + json!({"sourceDocument": source}), + json!({"name": "Star"}), + json!({"sourceDocument": -1, "name": "Star"}), + json!({"sourceDocument": "1", "name": "Star"}), + json!({"sourceDocument": source, "name": "Star", "x": "10"}), + json!({"sourceDocument": u64::MAX, "name": "Star"}), + ] { + assert!(s.execute("symbol.placeFromDocument", &p).is_err(), "{p}"); + assert_eq!((undo_len(&s), doc(&s)), (before.0, &before.1), "{p}"); + } + // The source document is left as it was, and once it is closed its symbols are gone with it. + assert!(s.set_active(0)); + assert_eq!(*s.doc().unwrap().doc, *source_doc); + run(&mut s, "file.close", json!({"index": 0})); + let e = s.execute("symbol.placeFromDocument", &json!({"sourceDocument": source, "name": "Star"})).unwrap_err(); + assert!(e.to_string().contains("no longer open"), "{e}"); +} diff --git a/crates/ui-egui/src/canvas/context.rs b/crates/ui-egui/src/canvas/context.rs index cd98a214b7..8830416a28 100644 --- a/crates/ui-egui/src/canvas/context.rs +++ b/crates/ui-egui/src/canvas/context.rs @@ -73,10 +73,11 @@ pub(super) fn panel_drop(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Respons } return; } - // A symbol from the Symbols panel: an instance centred where it is dropped, on art or not. - if let widgets::PanelDrag::Symbol(name) = &*d { + // A symbol from the Symbols panel: an instance centred where it is dropped, on art or not. A + // symbol of another document is added to this one first. + if let widgets::PanelDrag::Symbol { document, name } = &*d { let at = xf.to_doc(pos); - if let Err(e) = app.run("symbol.place", json!({"name": name, "x": at.x, "y": at.y})) { + if let Err(e) = app.run("symbol.placeFromDocument", json!({"sourceDocument": document, "name": name, "x": at.x, "y": at.y})) { app.status(e); } return; @@ -138,7 +139,7 @@ pub(super) fn panel_drop(app: &mut VectorcraftApp, ui: &Ui, resp: &egui::Respons // Art dragged back onto the canvas: its move was already dropped. (A symbol was placed // above.) widgets::PanelDrag::Art(_) - | widgets::PanelDrag::Symbol(_) + | widgets::PanelDrag::Symbol { .. } | widgets::PanelDrag::LibrarySymbol { .. } | widgets::PanelDrag::LibraryGraphic { .. } => return, // A Libraries panel style or group only moves within that panel. diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 885ba3dcc6..112ef02d11 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -8812,7 +8812,8 @@ fn a_symbol_dropped_on_the_canvas_is_placed_there() { let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); // Released over empty canvas: an instance centred there. let at = xf.to_screen(Point::new(250.0, 180.0)); - egui::DragAndDrop::set_payload(&ctx, widgets::PanelDrag::Symbol(name.clone())); + let document = app.session.active().unwrap().uid; + egui::DragAndDrop::set_payload(&ctx, widgets::PanelDrag::Symbol { document, name: name.clone() }); let up = egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() }; frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at), up]); let st = app.session.active().unwrap(); @@ -8823,6 +8824,106 @@ fn a_symbol_dropped_on_the_canvas_is_placed_there() { assert!((c - xf.to_doc(at)).hypot() < 1e-6, "{c:?}"); } +/// A new active document with a symbol `name` made from a `w` by `h` rectangle and no art; → its +/// uid. +fn document_with_symbol(app: &mut VectorcraftApp, name: &str, w: f64, h: f64) -> u64 { + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + app.session.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": w, "height": h})).unwrap(); + app.session.execute("symbol.new", &json!({"name": name})).unwrap(); + app.session.execute("edit.clear", &json!({})).unwrap(); + app.session.active().unwrap().uid +} + +/// The natural size the active document records for symbol `name`. +fn symbol_size(app: &VectorcraftApp, name: &str) -> (f64, f64) { + let st = app.session.active().unwrap(); + let size = st.doc.unknown.get(vectorcraft_doc::SYMBOL_SIZES).and_then(|m| m.get(name)).cloned().unwrap(); + (size[0].as_f64().unwrap(), size[1].as_f64().unwrap()) +} + +/// A symbol dragged from one document's Symbols panel and released on the canvas after another +/// document with a different symbol of the same name became active places the dragged symbol: it +/// is added under a free name, the other document's symbol is left as it was, the source document +/// is not changed, and one Undo takes back both the symbol and the instance. +#[test] +fn a_symbol_dragged_from_another_document_places_that_documents_symbol() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let source = document_with_symbol(&mut app, "Leaf", 40.0, 20.0); + let ctx = egui::Context::default(); + // While Leaf is held, a document with a Leaf of its own becomes active. + egui::DragAndDrop::set_payload(&ctx, widgets::PanelDrag::Symbol { document: source, name: "Leaf".into() }); + document_with_symbol(&mut app, "Leaf", 10.0, 70.0); + frame(&mut app, &ctx, vec![]); + let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); + let undo = app.session.active().unwrap().history.undo.len(); + let at = xf.to_screen(Point::new(250.0, 180.0)); + let up = egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() }; + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at), up]); + let st = app.session.active().unwrap(); + assert_eq!(st.doc.symbols.iter().map(|s| s.name.as_str()).collect::<Vec<_>>(), ["Leaf", "Leaf 2"]); + assert_eq!(st.history.undo.len(), undo + 1, "added and placed as one undo step"); + let placed = st.selection.objects.first().copied().expect("the placed instance is selected"); + let n = st.doc.node(placed).unwrap(); + assert!(matches!(&n.kind, NodeKind::SymbolInstance { symbol, .. } if symbol == "Leaf 2"), "{:?}", n.kind); + let b = n.geometric_bounds().unwrap(); + assert!((b.width() - 40.0).abs() < 1e-6 && (b.height() - 20.0).abs() < 1e-6, "the dragged symbol's size: {b:?}"); + assert!((b.center() - xf.to_doc(at)).hypot() < 1e-6, "{b:?}"); + assert_eq!(symbol_size(&app, "Leaf"), (10.0, 70.0), "this document's Leaf is unchanged"); + app.run("edit.undo", json!({})).unwrap(); + let st = app.session.active().unwrap(); + assert_eq!(st.doc.symbols.iter().map(|s| s.name.as_str()).collect::<Vec<_>>(), ["Leaf"]); + assert!(st.doc.node(placed).is_none()); + assert!(app.session.set_active(0)); + assert_eq!(app.session.active().unwrap().uid, source); + assert_eq!(app.session.active().unwrap().doc.symbols.len(), 1, "the source document is unchanged"); + assert_eq!(symbol_size(&app, "Leaf"), (40.0, 20.0)); +} + +/// A symbol dragged from a document that was closed before the release places nothing, even +/// where the active document has a symbol of the same name. +#[test] +fn a_symbol_whose_document_closed_places_nothing() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let source = document_with_symbol(&mut app, "Leaf", 40.0, 20.0); + document_with_symbol(&mut app, "Leaf", 10.0, 70.0); + app.session.execute("file.close", &json!({"index": 0})).unwrap(); + assert!(app.session.documents().iter().all(|d| d.uid != source)); + let ctx = egui::Context::default(); + egui::DragAndDrop::set_payload(&ctx, widgets::PanelDrag::Symbol { document: source, name: "Leaf".into() }); + frame(&mut app, &ctx, vec![]); + let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()); + let undo = app.session.active().unwrap().history.undo.len(); + let at = xf.to_screen(Point::new(250.0, 180.0)); + let up = egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers: Default::default() }; + frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at), up]); + let st = app.session.active().unwrap(); + assert_eq!(st.history.undo.len(), undo, "no edit"); + assert!(st.selection.objects.is_empty(), "nothing placed"); +} + +/// The chip at the pointer shows the dragged symbol from the document it was dragged from after +/// another document, without a symbol of that name, became active. +#[test] +fn the_pointer_chip_of_a_dragged_symbol_shows_its_own_documents_symbol() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + let source = document_with_symbol(&mut app, "Leaf", 40.0, 20.0); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let ctx = egui::Context::default(); + egui::DragAndDrop::set_payload(&ctx, widgets::PanelDrag::Symbol { document: source, name: "Leaf".into() }); + let screen_rect = Some(egui::Rect::from_min_size(Pos2::ZERO, vec2(400.0, 300.0))); + let run = |events| { + let mut out = + ctx.run_ui(egui::RawInput { screen_rect, events, ..Default::default() }, |ui| crate::panels::swatches::drag_preview(&app, ui.ctx())); + out.textures_delta.clear(); + out + }; + // The chip's area is drawn from its second frame. + run(vec![egui::Event::PointerMoved(pos2(200.0, 150.0))]); + let out = run(vec![]); + let thumbnail = out.shapes.iter().any(|c| matches!(&c.shape, Shape::Mesh(m) if m.texture_id != egui::TextureId::default())); + assert!(thumbnail, "the chip draws the source document's thumbnail of Leaf"); +} + #[test] fn a_library_symbol_dropped_on_the_canvas_is_added_and_placed_there_in_one_step() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); diff --git a/crates/ui-egui/src/panels/graphic_styles.rs b/crates/ui-egui/src/panels/graphic_styles.rs index b99f9ec25b..cd7aa055b6 100644 --- a/crates/ui-egui/src/panels/graphic_styles.rs +++ b/crates/ui-egui/src/panels/graphic_styles.rs @@ -431,7 +431,7 @@ fn zone_input(ui: &Ui, zone: &Response, d: &Document, ev: &mut Events) { PanelDrag::Art(ids) => (None, ids.first().copied()), PanelDrag::Appearance(id) => (None, Some(*id)), PanelDrag::Paint { .. } - | PanelDrag::Symbol(_) + | PanelDrag::Symbol { .. } | PanelDrag::LibrarySymbol { .. } | PanelDrag::Brush { .. } | PanelDrag::LibraryBrush { .. } diff --git a/crates/ui-egui/src/panels/swatches/dnd.rs b/crates/ui-egui/src/panels/swatches/dnd.rs index 2adff72887..a7883f0031 100644 --- a/crates/ui-egui/src/panels/swatches/dnd.rs +++ b/crates/ui-egui/src/panels/swatches/dnd.rs @@ -302,7 +302,8 @@ pub(crate) fn drag_preview(app: &VectorcraftApp, ctx: &egui::Context) { None => return, }, PanelDrag::GraphicStyle(name) => return pointer_chip(ctx, |ui, r| crate::panels::graphic_styles::paint_style(app, ui, r, name)), - PanelDrag::Symbol(name) => match app.session.active() { + // Drawn from the document it was dragged from, whichever document is active now. + PanelDrag::Symbol { document, name } => match app.session.documents().iter().find(|st| st.uid == *document) { Some(st) => { return pointer_chip(ctx, |ui, r| crate::panels::symbols::chip(ui, &st.doc, &crate::panels::symbols::document_symbols(st), r, name)); } diff --git a/crates/ui-egui/src/panels/symbols.rs b/crates/ui-egui/src/panels/symbols.rs index a8392cdf50..c7a0c42639 100644 --- a/crates/ui-egui/src/panels/symbols.rs +++ b/crates/ui-egui/src/panels/symbols.rs @@ -296,7 +296,7 @@ pub(crate) fn control_bar(app: &mut VectorcraftApp, ui: &mut Ui, reserve: f32) { pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let t = Tokens::get(ui.ctx()); - let Some((doc, keys)) = app.session.active().map(|d| (d.doc.clone(), document_symbols(d))) else { return }; + let Some((doc, keys, document)) = app.session.active().map(|d| (d.doc.clone(), document_symbols(d), d.uid)) else { return }; let names: Vec<String> = doc.symbols.iter().map(|s| s.name.clone()).collect(); let view = app.ui.symbols_view; let sel = current(app); @@ -316,7 +316,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { for n in &names { let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), h), Sense::click_and_drag()); // Dragged onto the canvas, the symbol is placed there. - widgets::drag_source(ui, &resp, || PanelDrag::Symbol(n.clone())); + widgets::drag_source(ui, &resp, || PanelDrag::Symbol { document, name: n.clone() }); if on(n) { ui.painter().rect_filled(r, 0.0, t.row_selected); } else if resp.hovered() { @@ -342,7 +342,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { ui.horizontal_wrapped(|ui| { for n in &names { let (r, resp) = ui.allocate_exact_size(vec2(44.0, 44.0), Sense::click_and_drag()); - widgets::drag_source(ui, &resp, || PanelDrag::Symbol(n.clone())); + widgets::drag_source(ui, &resp, || PanelDrag::Symbol { document, name: n.clone() }); chip(ui, &doc, &keys, r.shrink(2.0), n); let on = on(n); ui.painter().rect_stroke( @@ -771,13 +771,14 @@ mod tests { let doc = &app.session.active().unwrap().doc; let first = doc.layers[0].children().unwrap().first().unwrap(); assert!(matches!(first.kind, NodeKind::SymbolInstance { .. }), "the art became an instance"); - // Dragging the symbol's tile out of the panel carries the symbol. + // Dragging the symbol's tile out of the panel carries the symbol and its document. frame(&ctx, &mut app, vec![]); let tile = pos2(26.0, 26.0); frame(&ctx, &mut app, vec![egui::Event::PointerMoved(tile), button(tile, true)]); frame(&ctx, &mut app, vec![egui::Event::PointerMoved(tile + vec2(40.0, 40.0))]); frame(&ctx, &mut app, vec![egui::Event::PointerMoved(tile + vec2(80.0, 80.0))]); - assert_eq!(egui::DragAndDrop::payload::<PanelDrag>(&ctx).as_deref(), Some(&PanelDrag::Symbol(names[0].clone()))); + let document = app.session.active().unwrap().uid; + assert_eq!(egui::DragAndDrop::payload::<PanelDrag>(&ctx).as_deref(), Some(&PanelDrag::Symbol { document, name: names[0].clone() })); } /// One headless frame of the panel menu; returns its painted labels. diff --git a/crates/ui-egui/src/widgets/drag.rs b/crates/ui-egui/src/widgets/drag.rs index 1a9c280f81..ed28c31e30 100644 --- a/crates/ui-egui/src/widgets/drag.rs +++ b/crates/ui-egui/src/widgets/drag.rs @@ -23,9 +23,10 @@ pub enum PanelDrag { /// (`symbol.new`), the Swatches panel a pattern swatch of a copy (`object.pattern.make`) and the /// Brushes panel an Art brush (`brush.new`). Art(Vec<vectorcraft_doc::NodeId>), - /// A Symbols panel symbol: the canvas places an instance of it centred where it is dropped - /// (`symbol.place`). - Symbol(String), + /// A Symbols panel symbol (`document`: the uid of the document whose panel it was dragged + /// from): the canvas places an instance of it centered where it is dropped, adding the symbol + /// first when another document is active by then (`symbol.placeFromDocument`). + Symbol { document: u64, name: String }, /// A symbol of a symbol library panel (`name`: its name in `library`): the canvas adds it to the /// document's Symbols and places an instance where it is dropped (`symbol.addFromLibrary` with /// `place`). diff --git a/crates/ui-egui/src/widgets/look_tests.rs b/crates/ui-egui/src/widgets/look_tests.rs index 274861386b..c6c241e504 100644 --- a/crates/ui-egui/src/widgets/look_tests.rs +++ b/crates/ui-egui/src/widgets/look_tests.rs @@ -421,7 +421,7 @@ fn a_popover_stays_open_for_a_click_on_its_anchor_or_during_a_panel_drag() { shown.get() }; let far = Some(pos2(500.0, 350.0)); - let panel_drag = || Some(PanelDrag::Symbol("s".into())); + let panel_drag = || Some(PanelDrag::Symbol { document: 1, name: "s".into() }); // Whether it is open after: a click elsewhere; a click on its anchor that doesn't toggle it; // a panel drag released elsewhere. let open = [open_after_click(far, None), open_after_click(None, None), open_after_click(far, panel_drag())]; diff --git a/docs/mcp.md b/docs/mcp.md index 7c45340f2b..cbe369556f 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3414,7 +3414,11 @@ already walks Image Trace. Short agent entry points: art, where it is, snaps the art again after it is edited, and does not count instances in `select.object.notAlignedToPixelGrid`; `alignToPixelGrid` alone with the value the symbol already has adds no undo step), - `symbol.place {name?, x?, y?}`, `symbol.breakLink {ids?}` (the art keeps the instance's opacity mask and its bounding box, square after + `symbol.place {name?, x?, y?}`, `symbol.placeFromDocument {sourceDocument, name, x?, y?}` (an instance of a symbol + of another open document, as a symbol dragged from that document's Symbols panel onto the canvas places it: the + symbol, the symbols it nests and the resources they use are added as `edit.dropSelection` adds them, in the same + undo step, and a symbol with the same name but other art or Symbol Options is added under a free name; an error + when that document is no longer open; plug-ins cannot call it), `symbol.breakLink {ids?}` (the art keeps the instance's opacity mask and its bounding box, square after `object.resetBoundingBox`; a hidden or locked instance's art stays hidden or locked and is not selected), `symbol.replace`, `symbol.edit {id?, ids?, name?, x?, y?, artboard?, viewCenter?}` (symbol editing mode: the symbol's art on a temporary diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index ea070aeba0..daa5de4e5a 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1281,6 +1281,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur As VectorCraft's own rule, a zoom marquee that Cmd+Space starts while the Type tool edits text keeps the marquee's Space rules after Cmd is let go: Space held since the press sizes it, Space pressed again moves it ([the help page](https://helpx.adobe.com/illustrator/using/viewing-artwork.html) describes holding the spacebar to move the marquee), and that Space types no space, nor does it during an animated zoom drag. With no zoom drag, Space types a space. Test: `canvas::tests::space_moves_a_text_edit_zoom_marquee_after_cmd_is_let_go`. - **Swatches panel clicks:** Ctrl/Cmd-clicking New Swatch makes a spot color, and Ctrl/Cmd+Shift-clicking it makes a global process color. - **Panel drag and drop:** art dragged off the canvas onto the Symbols panel becomes a symbol, art dragged onto the Swatches panel becomes a pattern swatch, and art dropped on the Brushes panel opens New Brush for that art; a symbol dragged onto the canvas places an instance where it is dropped, and a brush dragged onto a path is applied to it. + A symbol dragged from one document's Symbols panel and dropped on the canvas after another document became active places the dragged symbol, not a symbol of the same name in the active document (`symbol.placeFromDocument`). VectorCraft's own rules: the symbol, the symbols it nests and the resources they use are added to the active document as a drop of art from the other document adds them, in the same undo step as the instance; a symbol the document already has with the same art and Symbol Options is used, and one with the same name but other art or options is added under a free name ("Leaf 2"); the chip at the pointer shows the dragged symbol; a symbol whose document was closed before the drop places nothing and the status bar shows the error. Tests: `canvas::tests::a_symbol_dragged_from_another_document_places_that_documents_symbol`, `a_symbol_whose_document_closed_places_nothing`, `the_pointer_chip_of_a_dragged_symbol_shows_its_own_documents_symbol`, `tests::symbollib::another_documents_symbol_is_added_and_placed_in_one_step`. New Brush asks for the type of brush first, as the [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page (archived copy) describes. The Brushes panel's New Brush button, its menu's New Brush… and art dropped on the panel open the New Brush dialog, where Scatter Brush, Art Brush and Pattern Brush need selected or dropped art. OK opens that type's Brush Options for the new brush, and their OK makes the brush with the name and options set; Cancel in either dialog adds no brush (`ui.newBrush`). The menu's New Calligraphic Brush, New Bristle Brush and New Art, Scatter and Pattern Brush from Selection items still make a brush at once. - **Panel drag and drop:** art dragged off the canvas onto the Symbols panel becomes a symbol, onto the Swatches panel a pattern swatch and onto the Brushes panel an Art brush; a symbol dragged onto the canvas places an instance where it is dropped, and a brush dragged onto a path is applied to it. In the Brushes panel, a brush dragged onto another brush of its type goes before or after it, by the half of the tile or row the pointer is over, and a bar marks the slot while the brush is held there (`brush.move`); the move is one undo step. Brushes move only within their type, as the [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page states: a brush dropped on a brush of another type stays where it is, and the status bar shows "brushes move only within their type". From 4911e102b1870d038360ded256a701970731b547 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Mon, 16 Nov 2026 07:54:26 -0800 Subject: [PATCH 066/176] Packaging Tools: Fold Preview folds the blank in 3D with the printed art on its panels MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fold Preview (Object › Plug-ins › Packaging Tools, and the Fold Lines panel's button) shows the document's blank folded about its largest panel, or the panel double-clicked. Creases and perforations fold 90° away from the printed side and partial cuts 90° toward it. Each panel samples a raster of the print, with the fold lines and non-printing layers left out, through its projective map, with a depth buffer; the back shows the board's inside color. The window has a Fold slider, seven view presets, orbit, zoom, pan and perspective, and its status line reports a joint that does not close and panels that pass through each other. - addon.packaging.fold returns each panel's frame, the hinges with their angle and gap, and the collisions. A closing hinge's gap is measured with every hinge folded all the way. - ui.foldPreview sets the window and rejects values of the wrong kind or out of range; saved settings out of range are brought into range. - The print renders off the UI thread where a worker exists and once per document revision. The fold and the view image are worked out again only when the document, the settings or the window's size change. --- ROADMAP.md | 1 + crates/engine/src/cmd.rs | 2 + crates/engine/src/cmd/addons.rs | 1 + crates/engine/src/cmd/addons/packaging.rs | 3 + .../engine/src/cmd/addons/packaging/check.rs | 85 ++- .../engine/src/cmd/addons/packaging/fold.rs | 110 +++ .../src/cmd/addons/packaging/fold/tests.rs | 143 ++++ crates/engine/src/cmd/plugin_call/reviewed.rs | 1 + crates/three-d/src/fold.rs | 35 +- crates/three-d/src/fold/pose.rs | 407 ++++++++++ crates/three-d/src/fold/raster.rs | 474 ++++++++++++ crates/three-d/src/fold/raster/tests.rs | 179 +++++ crates/three-d/src/fold/tests.rs | 319 ++++++++ crates/ui-egui/src/addons/packaging.rs | 14 +- .../ui-egui/src/addons/packaging/preview.rs | 702 ++++++++++++++++++ .../src/addons/packaging/preview/tests.rs | 489 ++++++++++++ crates/ui-egui/src/i18n/bg.tsv | 10 + crates/ui-egui/src/i18n/bs.tsv | 10 + crates/ui-egui/src/i18n/ca.tsv | 10 + crates/ui-egui/src/i18n/cs.tsv | 10 + crates/ui-egui/src/i18n/da.tsv | 10 + crates/ui-egui/src/i18n/de.tsv | 10 + crates/ui-egui/src/i18n/el.tsv | 10 + crates/ui-egui/src/i18n/es.tsv | 10 + crates/ui-egui/src/i18n/fi.tsv | 10 + crates/ui-egui/src/i18n/fr.tsv | 10 + crates/ui-egui/src/i18n/gu.tsv | 10 + crates/ui-egui/src/i18n/hi.tsv | 10 + crates/ui-egui/src/i18n/hu.tsv | 10 + crates/ui-egui/src/i18n/id.tsv | 10 + crates/ui-egui/src/i18n/it.tsv | 10 + crates/ui-egui/src/i18n/ja.tsv | 10 + crates/ui-egui/src/i18n/ka.tsv | 10 + crates/ui-egui/src/i18n/ko.tsv | 10 + crates/ui-egui/src/i18n/nl.tsv | 10 + crates/ui-egui/src/i18n/pl.tsv | 10 + crates/ui-egui/src/i18n/pt-br.tsv | 10 + crates/ui-egui/src/i18n/ru.tsv | 10 + crates/ui-egui/src/i18n/sv.tsv | 10 + crates/ui-egui/src/i18n/tr.tsv | 10 + crates/ui-egui/src/i18n/uk.tsv | 10 + crates/ui-egui/src/i18n/vi.tsv | 10 + crates/ui-egui/src/i18n/zh-hans.tsv | 10 + crates/ui-egui/src/i18n/zh-hant.tsv | 10 + crates/ui-egui/src/menus/run.rs | 1 + crates/ui-egui/src/menus/ui_commands.rs | 6 + crates/ui-egui/src/panel_docking.rs | 1 + crates/ui-egui/src/panels.rs | 1 + crates/ui-egui/src/state.rs | 6 + docs/mcp.md | 56 +- 50 files changed, 3285 insertions(+), 31 deletions(-) create mode 100644 crates/engine/src/cmd/addons/packaging/fold.rs create mode 100644 crates/engine/src/cmd/addons/packaging/fold/tests.rs create mode 100644 crates/three-d/src/fold/pose.rs create mode 100644 crates/three-d/src/fold/raster.rs create mode 100644 crates/three-d/src/fold/raster/tests.rs create mode 100644 crates/ui-egui/src/addons/packaging/preview.rs create mode 100644 crates/ui-egui/src/addons/packaging/preview/tests.rs diff --git a/ROADMAP.md b/ROADMAP.md index f658cccb58..3b0ae56576 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -136,6 +136,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 2026-11-04: New Document: the units chosen in Preset Details now belong to the chosen document, as the pane's options are listed for the selected preset; the chosen card shows them, every other Recent and Saved card keeps the units its document or preset was made in, and the built-in tabs still follow the chosen units, so switching between inches and millimetres no longer restyles every recent template. Scores and estimates unchanged. - 2026-11-14: Packaging Tools add-on (Object › Plug-ins › Packaging Tools): fold line roles for dielines (Cut, Crease, Partial Cut, Perforation), each carried by the swatch on a path's top stroke through a per-document role table that native files keep; PDF prints a role line on its swatch's separation when that swatch is a spot color, as the default role swatches are, and SVG, DXF and HP-GL keep the stroke's color. Make Cut Line, Make Crease Line, Make Partial Cut Line and Make Perforation Line give the selected paths a role, overprinting by default, and make a missing role swatch; the Fold Lines panel counts each role in the selection or the document, and its Role Swatches… picks another swatch for a role (`addon.packaging.setRole`, `addon.packaging.roles`, `addon.packaging.setRoleSwatch`). A VectorCraft addition: headline numbers unchanged. - 2026-11-16: Check Fold Lines in the Packaging Tools add-on (Object › Plug-ins › Packaging Tools, and the Fold Lines panel's Check button): the fold lines of the selection or the document are split into blanks, panels and hinges (cut lines bound the material, and creases, partial cuts and perforations divide it into panels), and 15 kinds of issue are listed, errors and warnings, each naming its lines: cut lines that enclose nothing or end loose, gaps closed within a tolerance, a cut on top of a crease, duplicate lines, creases that end inside a panel, divide nothing, lie outside the blank or are not straight, gaps too narrow to map, fold lines in a hole, panels joined by no crease, and fold lines on a non-printing layer. The panel lists the issues in the interface language; clicking one selects its lines (`addon.packaging.check`). A VectorCraft addition: headline numbers unchanged. +- 2026-11-16: Fold Preview in the Packaging Tools add-on (Object › Plug-ins › Packaging Tools, and the Fold Lines panel's Fold Preview button): a window that folds the document's blank into its 3D shape about its largest panel, or the panel double-clicked, with the printed art on the outside of each panel (fold lines and non-printing layers left out, unless Show Fold Lines is on) and the board's inside color on the back. Creases and perforations fold 90° away from the print and partial cuts 90° toward it; a Fold slider goes from flat to folded, and the view turns by dragging and the arrow keys, zooms, moves and takes a perspective and seven view presets. The status line says when a joint does not close or two panels pass through each other (`addon.packaging.fold`, `ui.foldPreview`). A VectorCraft addition: headline numbers unchanged. - 2026-11-02: Mouse wheel over a closed font-family field in Character, Properties or Control changes selected text through the family list using saved font filters (excluding search text), one undo step per notch, stopping at the ends (#5253). Scores and estimates unchanged. - 2026-10-31: Pattern libraries: Window › Swatch Libraries › Patterns and the Swatches panel's library menu open Geometric Patterns, a built-in library of eleven pattern swatches (dots, stripes, checks, a grid and shapes); clicking one adds its pattern and swatch to the document, once, and applies it to the active fill or stroke (`swatch.library.add`). - 2026-11-11: Pattern libraries: Patterns › Grit Textures, a second built-in pattern library, holds eight seamless black textures (Fine Grain, Coarse Grit, Sand, Speckle, Stipple, Scratches, Sparse Flecks and Dense Flecks) on tiles of 18 to 36 pt, each drawn the same way every time; marks that reach past a tile edge continue on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged. diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index c4a86dd3a5..cd112ac48a 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -821,6 +821,8 @@ pub(crate) fn unique_name_from(base: &str, next: &mut std::collections::HashMap< pub(crate) const MAX_IMPORTED_PRESETS: usize = 1000; pub(crate) use addons::{DecodedImages, refresh_color_masks}; +/// Packaging Tools' blanks and the objects their print leaves out, for the Fold Preview window. +pub use addons::{fold_source, print_hidden}; /// Document Info's category titles and the Objects category's count labels. pub use docinfo::{CATEGORIES, OBJECT_LABELS}; pub use docmenu::guide_indexes; diff --git a/crates/engine/src/cmd/addons.rs b/crates/engine/src/cmd/addons.rs index 8c310878fd..1ab2d5d9fa 100644 --- a/crates/engine/src/cmd/addons.rs +++ b/crates/engine/src/cmd/addons.rs @@ -16,6 +16,7 @@ mod shapes; mod typetools; pub(crate) use image::{DecodedImages, refresh_color_masks}; +pub use packaging::{fold_source, print_hidden}; pub(crate) use packaging::{role_swatch_edited, role_swatches_merged}; use super::CommandSpec; diff --git a/crates/engine/src/cmd/addons/packaging.rs b/crates/engine/src/cmd/addons/packaging.rs index 6099386b98..9de16ca200 100644 --- a/crates/engine/src/cmd/addons/packaging.rs +++ b/crates/engine/src/cmd/addons/packaging.rs @@ -6,8 +6,10 @@ //! (Object › Plug-ins › Packaging Tools) and its Fold Lines panel are the UI's. mod check; +mod fold; mod roles; +pub use fold::{fold_source, print_hidden}; pub(crate) use roles::{role_swatch_edited, role_swatches_merged}; use super::super::CommandSpec; @@ -15,6 +17,7 @@ use super::super::CommandSpec; pub fn specs() -> Vec<CommandSpec> { let mut v = roles::specs(); v.extend(check::specs()); + v.extend(fold::specs()); v } diff --git a/crates/engine/src/cmd/addons/packaging/check.rs b/crates/engine/src/cmd/addons/packaging/check.rs index da8f7f25dd..9507a17daa 100644 --- a/crates/engine/src/cmd/addons/packaging/check.rs +++ b/crates/engine/src/cmd/addons/packaging/check.rs @@ -4,7 +4,7 @@ use serde_json::{Value, json}; use vectorcraft_doc::{Document, Node, NodeId, NodeKind}; use vectorcraft_geom::PathData; -use vectorcraft_three_d::fold::{FoldLine, IssueCode, LineKind, MAX_SEGMENTS, blanks}; +use vectorcraft_three_d::fold::{Blank, FoldLine, Issue, IssueCode, LineKind, MAX_SEGMENTS, blanks}; use super::super::super::pathops::length_given; use super::super::super::{CommandSpec, bad, checked_ids_or_selection, cmd, has_doc, switch_or}; @@ -14,7 +14,7 @@ use crate::{Result, Session}; const CHECK: &str = "addon.packaging.check"; /// How far apart the ends of two lines may be and still be joined, in points. -const TOLERANCE: (f64, f64, f64) = (0.01, 0.1, 10.0); +pub(super) const TOLERANCE: (f64, f64, f64) = (0.01, 0.1, 10.0); pub fn specs() -> Vec<CommandSpec> { vec![cmd!( @@ -101,23 +101,44 @@ fn kind(role: Role) -> LineKind { } } -fn check(s: &mut Session, p: &Value) -> Result<Value> { - let select = switch_or(p, "select", false, CHECK)?; - let tolerance = match length_given(p, "tolerance", CHECK)? { - None => TOLERANCE.1, - Some(t) if (TOLERANCE.0..=TOLERANCE.2).contains(&t) => t, - Some(_) => return Err(bad(CHECK, format!("`tolerance` must be from {} to {} pt", TOLERANCE.0, TOLERANCE.2))), - }; +/// The fold lines a check or a fold reads: where they came from (`ids`, `selection` or +/// `document`), the lines, and the ids of those on a non-printing layer. +pub(super) struct Lines { + pub scope: &'static str, + pub lines: Vec<FoldLine>, + pub non_printing: Vec<u64>, +} + +/// The tolerance `p` gives for `cmd`, or the default. +pub(super) fn tolerance(p: &Value, cmd: &str) -> Result<f64> { + match length_given(p, "tolerance", cmd)? { + None => Ok(TOLERANCE.1), + Some(t) if (TOLERANCE.0..=TOLERANCE.2).contains(&t) => Ok(t), + Some(_) => Err(bad(cmd, format!("`tolerance` must be from {} to {} pt", TOLERANCE.0, TOLERANCE.2))), + } +} + +/// The fold lines among the objects `p` names for `cmd` (`ids`, else the selection), or, while +/// nothing is selected and `ids` is left out, every shown fold line of the document. Hidden lines +/// are left out in every scope, members of a selected group included. +pub(super) fn lines(s: &Session, p: &Value, cmd: &str) -> Result<Lines> { let given = p.get("ids").is_some_and(|v| !v.is_null()); - let roots = checked_ids_or_selection(s, p, CHECK)?; + let roots = checked_ids_or_selection(s, p, cmd)?; let d = &s.doc()?.doc; - // Hidden lines are left out in every scope, members of a selected group included. let shown = |ids: Vec<NodeId>| ids.into_iter().filter(|id| d.is_visible(*id)).collect::<Vec<_>>(); - let (scope, targets) = match (given, roots.is_empty()) { - (true, _) => ("ids", shown(role_targets(d, &roots, false).0)), - (false, false) => ("selection", shown(role_targets(d, &roots, false).0)), - (false, true) => ("document", shown_targets(d)), - }; + Ok(match (given, roots.is_empty()) { + (true, _) => lines_of(d, "ids", shown(role_targets(d, &roots, false).0)), + (false, false) => lines_of(d, "selection", shown(role_targets(d, &roots, false).0)), + (false, true) => document_lines(d), + }) +} + +/// Every shown fold line of `d`. +pub(super) fn document_lines(d: &Document) -> Lines { + lines_of(d, "document", shown_targets(d)) +} + +fn lines_of(d: &Document, scope: &'static str, targets: Vec<NodeId>) -> Lines { let table = RoleTable::of(d); let mut lines = vec![]; let mut non_printing = vec![]; @@ -136,12 +157,21 @@ fn check(s: &mut Session, p: &Value) -> Result<Value> { segments = segments.saturating_add(path.subpaths.iter().map(|sp| sp.segment_count()).sum()); lines.push(FoldLine { path, kind: kind(role), key: id.0 }); } - let (found, mut issues) = blanks(&lines, tolerance); - if !non_printing.is_empty() { - issues.push(vectorcraft_three_d::fold::Issue { code: IssueCode::NonPrinting, keys: non_printing, at: None }); + Lines { scope, lines, non_printing } +} + +/// The blanks `lines` make and their issues, the non-printing one last. +pub(super) fn found(lines: &Lines, tolerance: f64) -> (Vec<Blank>, Vec<Issue>) { + let (found, mut issues) = blanks(&lines.lines, tolerance); + if !lines.non_printing.is_empty() { + issues.push(Issue { code: IssueCode::NonPrinting, keys: lines.non_printing.clone(), at: None }); } - let ok = !issues.iter().any(|i| i.code.is_error()); - let rows: Vec<Value> = issues + (found, issues) +} + +/// `issues` as the rows `addon.packaging.check` and `addon.packaging.fold` answer with. +pub(super) fn issue_rows(issues: &[Issue], scope: &str) -> Vec<Value> { + issues .iter() .map(|i| { let mut row = json!({ @@ -155,7 +185,18 @@ fn check(s: &mut Session, p: &Value) -> Result<Value> { } row }) - .collect(); + .collect() +} + +fn check(s: &mut Session, p: &Value) -> Result<Value> { + let select = switch_or(p, "select", false, CHECK)?; + let tolerance = tolerance(p, CHECK)?; + let lines = lines(s, p, CHECK)?; + let scope = lines.scope; + let (found, issues) = found(&lines, tolerance); + let d = &s.doc()?.doc; + let ok = !issues.iter().any(|i| i.code.is_error()); + let rows = issue_rows(&issues, scope); if select { let mut ids: Vec<NodeId> = issues.iter().flat_map(|i| i.keys.iter().map(|k| NodeId(*k))).filter(|id| d.node(*id).is_some()).collect(); ids.sort_unstable_by_key(|id| id.0); diff --git a/crates/engine/src/cmd/addons/packaging/fold.rs b/crates/engine/src/cmd/addons/packaging/fold.rs new file mode 100644 index 0000000000..068b2375c9 --- /dev/null +++ b/crates/engine/src/cmd/addons/packaging/fold.rs @@ -0,0 +1,110 @@ +//! Fold Preview's model (`addon.packaging.fold`): a blank folded into its 3D shape by +//! [`vectorcraft_three_d::fold::fold`], and what the Fold Preview window needs to draw it: the +//! document's blanks ([`fold_source`]) and the objects its print leaves out ([`print_hidden`]). + +use serde_json::{Value, json}; +use vectorcraft_doc::{Document, Node, NodeId, NodeKind}; +use vectorcraft_three_d::fold::{Blank, Issue, fold, pick}; + +use super::super::super::{CommandSpec, bad, cmd, finite_numbers, has_doc, number_or}; +use super::check::{TOLERANCE, document_lines, found, issue_rows, lines, tolerance}; +use super::roles::{RoleTable, can_carry}; +use crate::{Result, Session}; + +const FOLD: &str = "addon.packaging.fold"; + +pub fn specs() -> Vec<CommandSpec> { + vec![cmd!( + query "addon.packaging.fold", + "Fold", + [], + None, + "{ids?: [id…] (default: the selection), base?: [x, y] (the panel under this point; default: the largest panel), amount?: 0..1 (1), tolerance?: pt 0.01..10 (0.1)} fold the blank that the fold lines among the objects make (as addon.packaging.check finds them; while nothing is selected and ids is left out, every fold line of the document) into its 3D shape. The base panel stays in place; every other panel turns about the hinges that join it to the base, each by its angle times amount: a Crease or a Perforation by 90° away from the printed side, a Partial Cut by 90° toward it. Hinges that close a loop of panels are not turned about: gap is how far apart their two placements end up when every hinge is folded all the way, whatever amount is, and closes is true within tolerance or 0.5% of the hinge's length. Changes nothing in the document → {ok (no error), blank (the index of the blank folded, or null when none is), blanks, base, panels: [{outline (SVG path data, document coordinates), frame: {x, y, z, origin} (where the flat blank's x and y directions, its printed side and its origin go, in points: x right, y up, z toward the printed side of the flat blank), parent (null for the base and loose panels), depth}], hinges: [{a, b, angle (degrees), kind: tree|closing, closes, gap}], collisions: [[a, b]] (panels that pass through each other; panels stacked in one plane do not), issues (as addon.packaging.check)}. Errors: a base point in no panel", + has_doc, + fold_command + )] +} + +/// The blanks the shown fold lines of `d` make, and their issues (`addon.packaging.check` on the +/// whole document): what the Fold Preview window folds. +pub fn fold_source(d: &Document) -> (Vec<Blank>, Vec<Issue>) { + found(&document_lines(d), TOLERANCE.1) +} + +/// The objects the print on a folded blank leaves out: the layers that do not print and, unless +/// `fold_lines`, every object with a line role. +pub fn print_hidden(d: &Document, fold_lines: bool) -> Vec<NodeId> { + fn walk(n: &Node, table: &RoleTable, fold_lines: bool, out: &mut Vec<NodeId>) { + match &n.kind { + NodeKind::Layer { printable: false, .. } => out.push(n.id), + NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } => children.iter().for_each(|c| walk(c, table, fold_lines, out)), + _ if !fold_lines && can_carry(n) && table.role_of(n).is_some() => out.push(n.id), + _ => {} + } + } + let table = RoleTable::of(d); + let mut out = vec![]; + d.layers.iter().for_each(|l| walk(l, &table, fold_lines, &mut out)); + out +} + +fn fold_command(s: &mut Session, p: &Value) -> Result<Value> { + let tolerance = tolerance(p, FOLD)?; + let amount = number_or(p, "amount", 1.0, FOLD)?; + if !(0.0..=1.0).contains(&amount) { + return Err(bad(FOLD, "`amount` must be from 0 to 1")); + } + let base = match p.get("base") { + None | Some(Value::Null) => None, + Some(v) => { + let [x, y] = finite_numbers::<2>(v).ok_or_else(|| bad(FOLD, "`base` must be a point: [x, y]"))?; + Some(vectorcraft_geom::Point::new(x, y)) + } + }; + let lines = lines(s, p, FOLD)?; + let (blanks, issues) = found(&lines, tolerance); + let ok = !issues.iter().any(|i| i.code.is_error()); + let picked = pick(&blanks, base); + if base.is_some() && picked.is_none() { + return Err(bad(FOLD, "`base` is in no panel")); + } + let folded = picked.and_then(|(b, panel)| Some((b, blanks.get(b)?, fold(blanks.get(b)?, Some(panel), amount, tolerance)?))); + let Some((index, blank, f)) = folded else { + return Ok(json!({ + "ok": ok, "blank": null, "blanks": blanks.len(), "base": null, "panels": [], "hinges": [], "collisions": [], + "issues": issue_rows(&issues, lines.scope), + })); + }; + let column = |m: &[[f64; 3]; 3], k: usize| json!([m[0][k], m[1][k], m[2][k]]); + let panels: Vec<Value> = blank + .panels + .iter() + .zip(&f.panels) + .map(|(panel, placed)| { + json!({ + "outline": panel.outline.to_bezpath().to_svg(), + "frame": {"x": column(&placed.pose.m, 0), "y": column(&placed.pose.m, 1), "z": column(&placed.pose.m, 2), "origin": placed.pose.t}, + "parent": placed.parent, + "depth": placed.depth, + }) + }) + .collect(); + let hinges: Vec<Value> = f + .hinges + .iter() + .map(|h| json!({"a": h.a, "b": h.b, "angle": h.angle, "kind": if h.tree { "tree" } else { "closing" }, "closes": h.closes, "gap": h.gap})) + .collect(); + Ok(json!({ + "ok": ok, + "blank": index, + "blanks": blanks.len(), + "base": f.base, + "panels": panels, + "hinges": hinges, + "collisions": f.collisions.iter().map(|(a, b)| [a, b]).collect::<Vec<_>>(), + "issues": issue_rows(&issues, lines.scope), + })) +} + +#[cfg(test)] +mod tests; diff --git a/crates/engine/src/cmd/addons/packaging/fold/tests.rs b/crates/engine/src/cmd/addons/packaging/fold/tests.rs new file mode 100644 index 0000000000..da7cd6a84e --- /dev/null +++ b/crates/engine/src/cmd/addons/packaging/fold/tests.rs @@ -0,0 +1,143 @@ +//! Tests for the Fold Preview's model: a blank drawn in a document folded into its 3D shape. + +use serde_json::{Value, json}; + +use crate::*; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 600, "height": 600})).unwrap(); + s +} + +fn path(s: &mut Session, d: &str) -> u64 { + s.execute("path.create", &json!({ "d": d })).unwrap()["id"].as_u64().unwrap() +} + +fn role(s: &mut Session, role: &str, ids: &[u64]) { + s.execute("addon.packaging.setRole", &json!({ "role": role, "ids": ids })).unwrap(); +} + +fn fold(s: &mut Session, p: Value) -> Value { + s.execute("addon.packaging.fold", &p).unwrap() +} + +/// A tray blank: a 100 pt base (x 140 to 240, y 140 to 240) with a 40 pt wall on each side → +/// (outline, creases). +fn tray(s: &mut Session) -> (u64, Vec<u64>) { + let outline = path(s, "M140 100 L240 100 L240 140 L280 140 L280 240 L240 240 L240 280 L140 280 L140 240 L100 240 L100 140 L140 140 Z"); + let creases = vec![path(s, "M140 140 L240 140"), path(s, "M240 140 L240 240"), path(s, "M240 240 L140 240"), path(s, "M140 240 L140 140")]; + role(s, "cut", &[outline]); + role(s, "crease", &creases); + s.execute("select.none", &json!({})).unwrap(); + (outline, creases) +} + +fn vector(v: &Value) -> [f64; 3] { + let a = v.as_array().unwrap(); + [a[0].as_f64().unwrap(), a[1].as_f64().unwrap(), a[2].as_f64().unwrap()] +} + +fn near(a: [f64; 3], b: [f64; 3]) -> bool { + a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-9) +} + +#[test] +fn a_tray_folds_its_walls_up_round_the_base() { + let mut s = session(); + tray(&mut s); + let steps = s.doc().unwrap().history.undo.len(); + let r = fold(&mut s, json!({})); + assert_eq!((r["ok"].as_bool(), r["blank"].as_u64(), r["blanks"].as_u64()), (Some(true), Some(0), Some(1)), "{r}"); + let panels = r["panels"].as_array().unwrap(); + assert_eq!(panels.len(), 5); + let base = r["base"].as_u64().unwrap() as usize; + let frame = &panels[base]["frame"]; + assert!( + near(vector(&frame["x"]), [1.0, 0.0, 0.0]) && near(vector(&frame["z"]), [0.0, 0.0, 1.0]) && near(vector(&frame["origin"]), [0.0; 3]), + "{frame}" + ); + assert!(panels[base]["parent"].is_null()); + assert!(panels[base]["outline"].as_str().unwrap().starts_with('M'), "SVG path data"); + for (i, p) in panels.iter().enumerate().filter(|(i, _)| *i != base) { + assert_eq!((p["parent"].as_u64(), p["depth"].as_u64()), (Some(base as u64), Some(1)), "{p}"); + // Each wall stands square to the base, its print facing out. + let z = vector(&p["frame"]["z"]); + assert!(z[2].abs() < 1e-9 && (z[0].hypot(z[1]) - 1.0).abs() < 1e-9, "wall {i}: {z:?}"); + } + let hinges = r["hinges"].as_array().unwrap(); + assert_eq!(hinges.len(), 4); + assert!(hinges.iter().all(|h| h["kind"] == "tree" && h["angle"] == 90.0 && h["closes"] == true), "{r}"); + assert_eq!(r["collisions"], json!([])); + assert_eq!(s.doc().unwrap().history.undo.len(), steps, "a fold records no undo step"); + + // Flat, every frame is the flat blank's own. + let r = fold(&mut s, json!({ "amount": 0 })); + for p in r["panels"].as_array().unwrap() { + assert!(near(vector(&p["frame"]["z"]), [0.0, 0.0, 1.0]) && near(vector(&p["frame"]["origin"]), [0.0; 3]), "{p}"); + } +} + +#[test] +fn the_base_is_the_panel_under_a_point() { + let mut s = session(); + tray(&mut s); + // The left wall: x 100 to 140, y 140 to 240. + let r = fold(&mut s, json!({ "base": [120, 190] })); + let base = r["base"].as_u64().unwrap() as usize; + let panels = r["panels"].as_array().unwrap(); + assert!(near(vector(&panels[base]["frame"]["z"]), [0.0, 0.0, 1.0])); + // The tray's base is now a child of the wall, and the other walls its children. + let depths: Vec<u64> = panels.iter().map(|p| p["depth"].as_u64().unwrap()).collect(); + let mut sorted = depths.clone(); + sorted.sort_unstable(); + assert_eq!(sorted, [0, 1, 2, 2, 2], "{depths:?}"); + let e = s.execute("addon.packaging.fold", &json!({ "base": [10, 10] })).unwrap_err().to_string(); + assert!(e.contains("`base` is in no panel"), "{e}"); +} + +#[test] +fn bad_values_are_refused() { + let mut s = session(); + tray(&mut s); + for (p, want) in [ + (json!({ "amount": 1.5 }), "`amount` must be from 0 to 1"), + (json!({ "amount": -0.1 }), "`amount` must be from 0 to 1"), + (json!({ "amount": "1" }), "`amount` must be a number"), + (json!({ "base": [1] }), "`base` must be a point"), + (json!({ "base": "middle" }), "`base` must be a point"), + (json!({ "tolerance": 50 }), "`tolerance` must be from"), + ] { + let e = s.execute("addon.packaging.fold", &p).unwrap_err().to_string(); + assert!(e.contains(want), "{p}: {e}"); + } +} + +#[test] +fn without_a_blank_nothing_is_folded_and_the_issues_say_why() { + let mut s = session(); + let r = fold(&mut s, json!({})); + assert_eq!((r["ok"].as_bool(), r["blank"].is_null(), r["blanks"].as_u64()), (Some(false), true, Some(0)), "{r}"); + assert_eq!(r["panels"], json!([])); + assert_eq!(r["issues"][0]["code"], "noCut"); +} + +#[test] +fn the_print_leaves_out_fold_lines_and_layers_that_do_not_print() { + let mut s = session(); + let (outline, creases) = tray(&mut s); + let art = path(&mut s, "M150 150 L200 150 L200 200 Z"); + let notes = s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().unwrap(); + s.execute("layer.setProps", &json!({"id": notes, "printable": false})).unwrap(); + let d = &s.doc().unwrap().doc; + let hidden: Vec<u64> = cmd::print_hidden(d, false).into_iter().map(|id| id.0).collect(); + for id in creases.iter().chain([&outline, ¬es]) { + assert!(hidden.contains(id), "{id} in {hidden:?}"); + } + assert!(!hidden.contains(&art)); + let shown: Vec<u64> = cmd::print_hidden(d, true).into_iter().map(|id| id.0).collect(); + assert_eq!(shown, vec![notes], "with the fold lines shown, only the layer is left out"); + let (blanks, issues) = cmd::fold_source(d); + assert_eq!((blanks.len(), blanks[0].panels.len()), (1, 5)); + assert!(issues.is_empty(), "{issues:?}"); +} diff --git a/crates/engine/src/cmd/plugin_call/reviewed.rs b/crates/engine/src/cmd/plugin_call/reviewed.rs index 1338bb5776..d11fc6ea00 100644 --- a/crates/engine/src/cmd/plugin_call/reviewed.rs +++ b/crates/engine/src/cmd/plugin_call/reviewed.rs @@ -41,6 +41,7 @@ pub(super) const ALLOWED: &[&str] = &[ "addon.image.removeBackground", "addon.image.removeColorMask", "addon.packaging.check", + "addon.packaging.fold", "addon.packaging.roles", "addon.packaging.setRole", "addon.packaging.setRoleSwatch", diff --git a/crates/three-d/src/fold.rs b/crates/three-d/src/fold.rs index 2dbff773f9..1bfb46f93b 100644 --- a/crates/three-d/src/fold.rs +++ b/crates/three-d/src/fold.rs @@ -34,6 +34,18 @@ pub enum LineKind { Perforation, } +impl LineKind { + /// The angle (degrees) a line of this kind folds at: 90 for a Crease or a Perforation, -90 for + /// a Partial Cut. A positive angle folds away from the printed side; none for a Cut. + pub fn fold_angle(self) -> Option<f64> { + match self { + LineKind::Cut => None, + LineKind::Crease | LineKind::Perforation => Some(90.0), + LineKind::PartialCut => Some(-90.0), + } + } +} + /// A fold line: the path (document coordinates), its kind, and a key the issues name it by. #[derive(Clone, Debug)] pub struct FoldLine { @@ -57,10 +69,18 @@ pub struct Panel { pub area: f64, } +impl Panel { + /// A point inside the panel, or the middle of its bounds for one too thin to find one in. + pub fn point_inside(&self) -> Option<Point> { + point_in(&self.outline) + } +} + /// The hinge between panels `a` and `b` (indices into the blank's panels, `a` < `b`): the straight /// line from `from` to `to`, made of the lines `keys`. `straight` is false when its pieces are not on /// one straight line within the tolerance; `from` and `to` are then on the line through its longest -/// piece. +/// piece. `angle` (degrees) is the fold angle of the kind of line its longest piece is +/// ([`LineKind::fold_angle`]). #[derive(Clone, Debug)] pub struct Hinge { pub a: usize, @@ -69,6 +89,7 @@ pub struct Hinge { pub to: Point, pub keys: Vec<u64>, pub straight: bool, + pub angle: f64, } /// What can be wrong with fold lines, in the order [`blanks`] lists them. @@ -1276,7 +1297,9 @@ impl Context<'_> { let sp = p.path.subpaths.first()?; Some((sp.anchors.first()?.p, sp.anchors.last()?.p)) }; - let (p0, p1) = group.iter().filter_map(|p| chord(p)).max_by(|x, y| x.0.distance(x.1).total_cmp(&y.0.distance(y.1)))?; + let ((p0, p1), longest) = + group.iter().filter_map(|p| Some((chord(p)?, p))).max_by(|(x, _), (y, _)| x.0.distance(x.1).total_cmp(&y.0.distance(y.1)))?; + let angle = longest.lines.iter().filter_map(|&l| self.lines.get(l)?.kind.fold_angle()).next().unwrap_or(90.0); let len = p0.distance(p1); // The longest piece only sets the direction; the length check is on the whole hinge below. if len.is_nan() || len <= 1e-9 { @@ -1308,7 +1331,7 @@ impl Context<'_> { let mut keys = self.keys(lines); keys.sort_unstable(); keys.dedup(); - Some(Hinge { a, b, from: p0 + d * lo, to: p0 + d * hi, keys, straight }) + Some(Hinge { a, b, from: p0 + d * lo, to: p0 + d * hi, keys, straight, angle }) } /// Creases with no hinge: outside every blank, or dividing no two panels; and creases beside a @@ -1426,7 +1449,7 @@ impl Context<'_> { /// The base panel of `panels`: the largest by area; panels whose areas differ by less than 1e-9 of /// the larger tie, and the tie goes to the one whose inside point is highest on the page, then /// leftmost. -fn base_panel(panels: &[Panel]) -> Option<usize> { +pub fn base_panel(panels: &[Panel]) -> Option<usize> { let top = panels.iter().map(|p| p.area).fold(f64::NEG_INFINITY, f64::max); if !top.is_finite() { return None; @@ -1440,5 +1463,9 @@ fn base_panel(panels: &[Panel]) -> Option<usize> { .map(|(i, _)| i) } +mod pose; +pub mod raster; +pub use pose::{Folded, FoldedHinge, FoldedPanel, MAX_POLYGON_POINTS, Pose, fold, panel_at, pick, polygon}; + #[cfg(test)] mod tests; diff --git a/crates/three-d/src/fold/pose.rs b/crates/three-d/src/fold/pose.rs new file mode 100644 index 0000000000..650ab54291 --- /dev/null +++ b/crates/three-d/src/fold/pose.rs @@ -0,0 +1,407 @@ +//! A blank folded into its 3D shape ([`fold`]). +//! +//! The flat blank lies at z = 0 with document x to the right and document y flipped so y points up; +//! the printed side faces +z. The base panel stays in place. The other panels are reached from it +//! through a breadth-first tree of hinges, each panel's hinges taken in the order of their ends (y, +//! then x, the first end first), so the tree does not depend on the order the lines were drawn in. A child +//! panel turns about its hinge by the hinge's angle times the fold amount; a positive angle moves it +//! toward -z, away from the printed side, whichever way the hinge was drawn. Hinges outside the tree +//! close a loop of panels: [`FoldedHinge::gap`] says how far apart their two placements end up when +//! the blank is folded all the way. + +use std::collections::{HashSet, VecDeque}; + +use vectorcraft_geom::{PathData, PathEl, Point, Shape as _}; + +use super::{Blank, base_panel, point_in}; + +/// Most points a panel's outline is flattened to; a panel with more is left out of the collision +/// test and the preview. +pub const MAX_POLYGON_POINTS: usize = 1 << 16; + +type V3 = [f64; 3]; + +fn sub(a: V3, b: V3) -> V3 { + [a[0] - b[0], a[1] - b[1], a[2] - b[2]] +} + +fn add(a: V3, b: V3) -> V3 { + [a[0] + b[0], a[1] + b[1], a[2] + b[2]] +} + +fn scale(a: V3, s: f64) -> V3 { + [a[0] * s, a[1] * s, a[2] * s] +} + +fn dot(a: V3, b: V3) -> f64 { + a[0] * b[0] + a[1] * b[1] + a[2] * b[2] +} + +fn cross(a: V3, b: V3) -> V3 { + [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]] +} + +fn length(a: V3) -> f64 { + dot(a, a).sqrt() +} + +/// A document point on the flat blank (y flipped so it points up, z = 0). +pub(super) fn flat(p: Point) -> V3 { + [p.x, -p.y, 0.0] +} + +/// Where a panel is: a rotation `m` (rows) and a translation `t`, taking a point of the flat +/// blank (see [`flat`]) to its place in 3D. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Pose { + pub m: [[f64; 3]; 3], + pub t: [f64; 3], +} + +impl Pose { + /// The flat blank's own place. + pub const IDENTITY: Pose = Pose { m: [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]], t: [0.0; 3] }; + + /// Where the flat point `v` goes. + pub fn apply(&self, v: [f64; 3]) -> [f64; 3] { + add(self.turn(v), self.t) + } + + /// The direction `v` turned by the rotation alone. + pub fn turn(&self, v: [f64; 3]) -> [f64; 3] { + let [a, b, c] = self.m; + [dot(a, v), dot(b, v), dot(c, v)] + } + + /// Where the document point `p` goes. + pub fn place(&self, p: Point) -> [f64; 3] { + self.apply(flat(p)) + } + + /// The direction the printed side faces. + pub fn normal(&self) -> [f64; 3] { + self.turn([0.0, 0.0, 1.0]) + } + + /// This pose followed, in the flat blank's terms, by a right-handed turn of `theta` radians + /// about the line through `at` along the unit direction `axis`: the pose of a panel hinged to + /// this one there. + fn turned_about(&self, at: V3, axis: V3, theta: f64) -> Pose { + let (s, c) = theta.sin_cos(); + let [x, y, z] = axis; + // Rodrigues' rotation matrix. + let r = [ + [c + x * x * (1.0 - c), x * y * (1.0 - c) - z * s, x * z * (1.0 - c) + y * s], + [y * x * (1.0 - c) + z * s, c + y * y * (1.0 - c), y * z * (1.0 - c) - x * s], + [z * x * (1.0 - c) - y * s, z * y * (1.0 - c) + x * s, c + z * z * (1.0 - c)], + ]; + let mut m = [[0.0; 3]; 3]; + for (i, row) in m.iter_mut().enumerate() { + for (j, cell) in row.iter_mut().enumerate() { + *cell = (0..3).map(|k| self.m[i][k] * r[k][j]).sum(); + } + } + // p ↦ self(r (p - at) + at) = (self.m r) p + self.m (at - r at) + self.t + let r_at = [dot(r[0], at), dot(r[1], at), dot(r[2], at)]; + Pose { m, t: add(self.turn(sub(at, r_at)), self.t) } + } +} + +/// A folded panel: where it is, its parent in the fold tree (`None` for the base and for a panel no +/// chain of hinges joins to it, which stays flat where it is) and how many hinges lie between it +/// and the base. +#[derive(Clone, Debug)] +pub struct FoldedPanel { + pub pose: Pose, + pub parent: Option<usize>, + pub depth: usize, +} + +/// A folded hinge: its panels, its angle (degrees, before the fold amount), whether it is in the +/// fold tree and, for one that is not, how far apart its two placements end up with every hinge at +/// its full angle, whatever the fold amount (`gap`, points), and whether that is close enough to call +/// it closed. +#[derive(Clone, Debug)] +pub struct FoldedHinge { + pub a: usize, + pub b: usize, + pub angle: f64, + pub tree: bool, + pub closes: bool, + pub gap: f64, +} + +/// A blank folded at one amount. +#[derive(Clone, Debug)] +pub struct Folded { + pub base: usize, + pub panels: Vec<FoldedPanel>, + /// The panels in breadth-first order from the base, the panels not joined to it last. + pub order: Vec<usize>, + pub hinges: Vec<FoldedHinge>, + /// Pairs of panels (`a` < `b`) that pass through each other. + pub collisions: Vec<(usize, usize)>, +} + +/// The panel of `blank` that `p` (document coordinates) lies in. +pub fn panel_at(blank: &Blank, p: Point) -> Option<usize> { + blank.panels.iter().position(|panel| panel.outline.to_bezpath().winding(p) != 0) +} + +/// Which of `blanks` to fold, and about which of its panels: the blank and panel `at` (document +/// coordinates) lies in, or, without a point, the blank with the largest panel (the first of equals) +/// and its base panel. `None` when `at` lies in no panel, or no blank has a panel. +pub fn pick(blanks: &[Blank], at: Option<Point>) -> Option<(usize, usize)> { + match at { + Some(p) => blanks.iter().enumerate().find_map(|(i, b)| Some((i, panel_at(b, p)?))), + None => { + let largest = |b: &Blank| b.panels.iter().map(|p| p.area).fold(f64::NEG_INFINITY, f64::max); + let (i, b) = + blanks.iter().enumerate().filter(|(_, b)| !b.panels.is_empty()).fold(None, |best: Option<(usize, &Blank)>, (i, b)| match best { + Some((_, kept)) if largest(kept) >= largest(b) => best, + _ => Some((i, b)), + })?; + Some((i, base_panel(&b.panels)?)) + } + } +} + +/// `blank` folded about its panel `base` (the largest when `None`) by `amount` (0, flat, to 1, every +/// hinge at its angle). `tolerance` (points) is how far apart a closing hinge's placements may end +/// up and still close (or 0.5% of its length, when that is more), and how far apart two panels in +/// one plane may lie and still be stacked rather than crossing. `None` when the blank has no +/// panels, `base` is not one of them, or `amount` is not from 0 to 1. +pub fn fold(blank: &Blank, base: Option<usize>, amount: f64, tolerance: f64) -> Option<Folded> { + let base = match base { + Some(b) => b, + None => base_panel(&blank.panels)?, + }; + if base >= blank.panels.len() || !(0.0..=1.0).contains(&amount) { + return None; + } + let tolerance = if tolerance.is_finite() && tolerance > 0.0 { tolerance } else { 0.01 }; + let n = blank.panels.len(); + // Each panel's hinges, by the place they start (y, then x), then by the other panel. + let mut by_panel: Vec<Vec<usize>> = vec![vec![]; n]; + for (i, h) in blank.hinges.iter().enumerate() { + for p in [h.a, h.b] { + if let Some(list) = by_panel.get_mut(p) { + list.push(i); + } + } + } + // A hinge's ends, the one first by (y, x) first. + let ends = |i: &usize| { + blank.hinges.get(*i).map_or([f64::INFINITY; 4], |h| { + let (s, e) = if (h.from.y, h.from.x) <= (h.to.y, h.to.x) { (h.from, h.to) } else { (h.to, h.from) }; + [s.y, s.x, e.y, e.x] + }) + }; + for list in &mut by_panel { + list.sort_by(|a, b| { + let (ka, kb) = (ends(a), ends(b)); + ka.iter().zip(&kb).fold(std::cmp::Ordering::Equal, |o, (x, y)| o.then(x.total_cmp(y))).then(a.cmp(b)) + }); + } + let centers: Vec<Option<V3>> = blank.panels.iter().map(|p| point_in(&p.outline).map(flat)).collect(); + let (panels, tree, order) = place(blank, &by_panel, ¢ers, base, amount); + // Closing hinges are measured with every hinge at its full angle, so a blank that closes when + // folded is not reported open part of the way there. + let full = if amount == 1.0 { None } else { Some(place(blank, &by_panel, ¢ers, base, 1.0).0) }; + let measured = full.as_deref().unwrap_or(&panels); + let hinges = blank + .hinges + .iter() + .zip(&tree) + .map(|(h, &tree)| { + let (pa, pb) = (measured.get(h.a).map(|p| p.pose), measured.get(h.b).map(|p| p.pose)); + let gap = match (pa, pb) { + (Some(pa), Some(pb)) if !tree => [h.from, h.to].iter().map(|&e| length(sub(pa.place(e), pb.place(e)))).fold(0.0, f64::max), + _ => 0.0, + }; + let closes = tree || gap <= tolerance.max(0.005 * h.from.distance(h.to)); + FoldedHinge { a: h.a, b: h.b, angle: h.angle, tree, closes, gap } + }) + .collect(); + let collisions = collisions(blank, &panels, tolerance); + Some(Folded { base, panels, order, hinges, collisions }) +} + +/// The panels of `blank` placed by the fold tree from `base` with each hinge at `amount` of its +/// angle, which hinges are in the tree, and the panels in breadth-first order (the panels not +/// joined to the base last). +fn place(blank: &Blank, by_panel: &[Vec<usize>], centers: &[Option<V3>], base: usize, amount: f64) -> (Vec<FoldedPanel>, Vec<bool>, Vec<usize>) { + let n = blank.panels.len(); + let mut panels: Vec<FoldedPanel> = vec![FoldedPanel { pose: Pose::IDENTITY, parent: None, depth: 0 }; n]; + let mut reached = vec![false; n]; + let mut tree = vec![false; blank.hinges.len()]; + let mut order = Vec::with_capacity(n); + let mut queue = VecDeque::from([base]); + if let Some(r) = reached.get_mut(base) { + *r = true; + } + while let Some(p) = queue.pop_front() { + order.push(p); + let Some(parent) = panels.get(p).cloned() else { continue }; + for &hi in by_panel.get(p).map(Vec::as_slice).unwrap_or_default() { + let Some(h) = blank.hinges.get(hi) else { continue }; + let child = if h.a == p { h.b } else { h.a }; + if reached.get(child) != Some(&false) { + continue; + } + let (mut from, mut to) = (flat(h.from), flat(h.to)); + let len = length(sub(to, from)); + if !(len.is_finite() && len > 0.0) { + continue; + } + // The parent on the left of the hinge's direction, the child on its right. The side is + // read next to the hinge, so a parent with a notch or an arm past the hinge's line still + // turns the child the right way; the panel's inside point is the fallback. + let left = match blank.panels.get(p).and_then(|panel| side_of(&panel.outline, from, to, len)) { + Some(left) => left, + None => centers.get(p).copied().flatten().is_none_or(|c| cross(sub(to, from), sub(c, from))[2] >= 0.0), + }; + if !left { + std::mem::swap(&mut from, &mut to); + } + let axis = scale(sub(to, from), 1.0 / len); + let theta = (h.angle * amount).to_radians(); + if !theta.is_finite() { + continue; + } + if let Some(slot) = panels.get_mut(child) { + *slot = FoldedPanel { pose: parent.pose.turned_about(from, axis, theta), parent: Some(p), depth: parent.depth + 1 }; + } + if let Some(r) = reached.get_mut(child) { + *r = true; + } + if let Some(t) = tree.get_mut(hi) { + *t = true; + } + queue.push_back(child); + } + } + order.extend((0..n).filter(|&i| reached.get(i) == Some(&false))); + (panels, tree, order) +} + +/// Whether `outline` lies on the left of the line from `from` to `to` (flat coordinates, `len` apart) +/// next to its middle: `Some(true)` when a point just off the middle on the left is inside it and +/// the matching point on the right is not, `Some(false)` the other way round, `None` when no offset +/// tells them apart. The nearest offset is tried first. +fn side_of(outline: &PathData, from: V3, to: V3, len: f64) -> Option<bool> { + let bp = outline.to_bezpath(); + let mid = scale(add(from, to), 0.5); + let left = [-(to[1] - from[1]) / len, (to[0] - from[0]) / len, 0.0]; + let doc = |v: V3| Point::new(v[0], -v[1]); + let mut offsets = [1e-3, 0.25, len * 0.01]; + offsets.sort_by(f64::total_cmp); + offsets.into_iter().find_map(|off| { + let (l, r) = (bp.winding(doc(add(mid, scale(left, off)))) != 0, bp.winding(doc(sub(mid, scale(left, off)))) != 0); + (l != r).then_some(l) + }) +} + +/// The rings of `path` flattened to `tolerance`, in document coordinates; `None` past +/// [`MAX_POLYGON_POINTS`] points. +pub fn polygon(path: &PathData, tolerance: f64) -> Option<Vec<Vec<Point>>> { + let mut rings: Vec<Vec<Point>> = vec![]; + let mut count = 0usize; + let mut fits = true; + vectorcraft_geom::flatten(path.to_bezpath(), tolerance, |el| { + if !fits { + return; + } + match el { + PathEl::MoveTo(p) => rings.push(vec![p]), + PathEl::LineTo(p) => match rings.last_mut() { + Some(r) => r.push(p), + None => rings.push(vec![p]), + }, + _ => return, + } + count += 1; + fits = count <= MAX_POLYGON_POINTS; + }); + rings.retain(|r| r.len() >= 3); + (fits && rings.iter().flatten().all(|p| p.is_finite())).then_some(rings) +} + +/// A panel placed in 3D: its rings, the plane it lies in (unit normal and offset) and its bounds. +struct Placed { + rings: Vec<Vec<V3>>, + normal: V3, + offset: f64, + lo: V3, + hi: V3, +} + +/// The pairs of `panels` that pass through each other. Two panels hinged to each other are not +/// tested, nor two in parallel planes (stacked in one plane, or apart). +fn collisions(blank: &Blank, panels: &[FoldedPanel], tolerance: f64) -> Vec<(usize, usize)> { + let placed: Vec<Option<Placed>> = blank + .panels + .iter() + .zip(panels) + .map(|(panel, f)| { + let rings: Vec<Vec<V3>> = + polygon(&panel.outline, tolerance)?.into_iter().map(|r| r.into_iter().map(|p| f.pose.place(p)).collect()).collect(); + let all = rings.iter().flatten(); + let lo = all.clone().fold([f64::INFINITY; 3], |a, p| [a[0].min(p[0]), a[1].min(p[1]), a[2].min(p[2])]); + let hi = all.fold([f64::NEG_INFINITY; 3], |a, p| [a[0].max(p[0]), a[1].max(p[1]), a[2].max(p[2])]); + let normal = f.pose.normal(); + let offset = dot(normal, f.pose.t); + Some(Placed { rings, normal, offset, lo, hi }) + }) + .collect(); + let hinged: HashSet<(usize, usize)> = blank.hinges.iter().map(|h| (h.a.min(h.b), h.a.max(h.b))).collect(); + let mut out = vec![]; + for (i, a) in placed.iter().enumerate() { + let Some(a) = a else { continue }; + for (j, b) in placed.iter().enumerate().skip(i + 1) { + let Some(b) = b else { continue }; + if hinged.contains(&(i, j)) || (0..3).any(|k| a.hi[k] + tolerance < b.lo[k] || b.hi[k] + tolerance < a.lo[k]) { + continue; + } + let line = cross(a.normal, b.normal); + let along = length(line); + if along.is_nan() || along <= 1e-9 { + continue; + } + let u = scale(line, 1.0 / along); + let on_a = crossings(&a.rings, b.normal, b.offset, u, tolerance); + let on_b = crossings(&b.rings, a.normal, a.offset, u, tolerance); + if on_a.iter().any(|x| on_b.iter().any(|y| x.1.min(y.1) - x.0.max(y.0) > tolerance)) { + out.push((i, j)); + } + } + } + out +} + +/// Where `rings` cross the plane `normal · p = offset`: the spans of the line along `u` that lie +/// inside them, by their place along `u`. A panel with no point more than `tolerance` to one side +/// of the plane only touches it, and crosses it nowhere; otherwise points within `tolerance` of it +/// count as on its positive side. +fn crossings(rings: &[Vec<V3>], normal: V3, offset: f64, u: V3, tolerance: f64) -> Vec<(f64, f64)> { + let side = |p: V3| dot(normal, p) - offset; + let sides = rings.iter().flatten().map(|&p| side(p)); + let (above, below) = sides.fold((false, false), |(a, b), s| (a || s > tolerance, b || s < -tolerance)); + if !(above && below) { + return vec![]; + } + let mut at = vec![]; + for ring in rings { + for (k, &p) in ring.iter().enumerate() { + let Some(&q) = ring.get((k + 1) % ring.len()) else { continue }; + let (sp, sq) = (side(p), side(q)); + if (sp >= -tolerance) != (sq >= -tolerance) { + let t = (sp / (sp - sq)).clamp(0.0, 1.0); + at.push(dot(u, add(p, scale(sub(q, p), t)))); + } + } + } + at.retain(|x| x.is_finite()); + at.sort_by(f64::total_cmp); + at.as_chunks::<2>().0.iter().map(|&[a, b]| (a, b)).collect() +} diff --git a/crates/three-d/src/fold/raster.rs b/crates/three-d/src/fold/raster.rs new file mode 100644 index 0000000000..012a9621de --- /dev/null +++ b/crates/three-d/src/fold/raster.rs @@ -0,0 +1,474 @@ +//! Draws a [`Folded`] blank as pixels: each panel's outline is projected through the view and filled +//! by scanline, with a depth buffer, and each pixel takes its color from a raster of the flat print +//! (the printed side) or from the inside color (the back), shaded by the panel's slope to a fixed +//! light. The inverse of the panel's projective map gives the flat point under every pixel, so the +//! print is drawn without seams under perspective. With perspective, each panel is cut at a near +//! plane in front of the eye before it is projected. + +use vectorcraft_geom::{Point, Rect}; + +use super::pose::{Folded, polygon}; +use super::{Blank, Panel}; + +/// Most pixels a side of the view or of the print raster may have. +pub const MAX_SIDE: u32 = 4096; +/// Most pixels the view may have in all (2,048 × 1,024; 32 MiB of buffers). +pub const MAX_PIXELS: u32 = 1 << 21; +/// The share of the eye's distance a panel is cut at in front of the eye. +const NEAREST: f64 = 1e-3; +/// How far apart (points of view depth) two panels may be and still tie. +const TIE: f64 = 1e-4; +/// The light's direction: above, to the left of and toward the viewer. +const LIGHT: [f64; 3] = [-0.37, 0.56, 0.74]; + +type V3 = [f64; 3]; + +fn dot(a: V3, b: V3) -> f64 { + a[0] * b[0] + a[1] * b[1] + a[2] * b[2] +} + +/// The view: its size in pixels, its turn (degrees: `rotate_x` tips the top toward the viewer, +/// `rotate_y` turns the right side toward the viewer), its scale (pixels per point at the center's +/// depth), how far it is moved (pixels), its perspective (the field of view in degrees; 0 for none) +/// and the 3D point at its middle. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Camera { + pub width: u32, + pub height: u32, + pub rotate_x: f64, + pub rotate_y: f64, + pub scale: f64, + pub pan: [f64; 2], + pub perspective: f64, + pub center: [f64; 3], +} + +impl Camera { + /// The turn from 3D to the view's own axes (x right, y up, z toward the viewer), as rows. + fn rotation(&self) -> [[f64; 3]; 3] { + let (sx, cx) = self.rotate_x.to_radians().sin_cos(); + let (sy, cy) = (-self.rotate_y).to_radians().sin_cos(); + // Rx · Ry + [[cy, 0.0, sy], [sx * sy, cx, -sx * cy], [-cx * sy, sx, cx * cy]] + } + + /// The point `p` in the view's own axes, its middle at the origin. + pub fn to_view(&self, p: V3) -> V3 { + let r = self.rotation(); + let d = [p[0] - self.center[0], p[1] - self.center[1], p[2] - self.center[2]]; + [dot(r[0], d), dot(r[1], d), dot(r[2], d)] + } + + /// The distance (points) from the eye to the view's middle and the focal length (pixels) under + /// perspective; `None` without it. + fn eye(&self) -> Option<(f64, f64)> { + if self.perspective <= 0.0 || self.perspective >= 180.0 { + return None; + } + let half = f64::from(self.width.min(self.height)) / 2.0; + let focal = half / (self.perspective.to_radians() / 2.0).tan(); + let eye = focal / self.scale; + (focal.is_finite() && eye.is_finite() && eye > 0.0).then_some((eye, focal)) + } + + fn usable(&self) -> bool { + let finite = + [self.rotate_x, self.rotate_y, self.scale, self.pan[0], self.pan[1], self.perspective].iter().chain(&self.center).all(|v| v.is_finite()); + let pixels = u64::from(self.width) * u64::from(self.height); + finite && self.scale > 0.0 && (1..=MAX_SIDE).contains(&self.width) && (1..=MAX_SIDE).contains(&self.height) && pixels <= u64::from(MAX_PIXELS) + } +} + +/// One level of the print raster: premultiplied RGBA, 4 bytes a pixel. +#[derive(Clone, Debug)] +pub struct Level { + pub width: u32, + pub height: u32, + pub pixels: Vec<u8>, +} + +impl Level { + /// The color at pixel `(x, y)`, clamped to the edges. + fn at(&self, x: i64, y: i64) -> [f32; 4] { + let x = x.clamp(0, i64::from(self.width) - 1); + let y = y.clamp(0, i64::from(self.height) - 1); + let i = usize::try_from((y * i64::from(self.width) + x) * 4).unwrap_or(usize::MAX); + match self.pixels.get(i..i.saturating_add(4)) { + Some(&[r, g, b, a]) => [f32::from(r), f32::from(g), f32::from(b), f32::from(a)], + _ => [0.0; 4], + } + } + + /// The color at `(x, y)` (pixels), between the four nearest pixels. + fn sample(&self, x: f64, y: f64) -> [f32; 4] { + let (fx, fy) = (x - 0.5, y - 0.5); + let (x0, y0) = (fx.floor(), fy.floor()); + let (tx, ty) = ((fx - x0) as f32, (fy - y0) as f32); + let (x0, y0) = (x0 as i64, y0 as i64); + let (a, b, c, d) = (self.at(x0, y0), self.at(x0 + 1, y0), self.at(x0, y0 + 1), self.at(x0 + 1, y0 + 1)); + let mut out = [0.0; 4]; + for (k, o) in out.iter_mut().enumerate() { + let top = a[k] + (b[k] - a[k]) * tx; + let bottom = c[k] + (d[k] - c[k]) * tx; + *o = top + (bottom - top) * ty; + } + out + } + + /// This level at half its size, rounded up, each pixel the mean of the four it covers (an odd + /// last row or column with itself). + fn half(&self) -> Option<Level> { + let (w, h) = (self.width.div_ceil(2), self.height.div_ceil(2)); + if (w, h) == (self.width, self.height) { + return None; + } + let mut pixels = Vec::with_capacity(w as usize * h as usize * 4); + for y in 0..i64::from(h) { + for x in 0..i64::from(w) { + let px = [self.at(2 * x, 2 * y), self.at(2 * x + 1, 2 * y), self.at(2 * x, 2 * y + 1), self.at(2 * x + 1, 2 * y + 1)]; + for k in 0..4 { + pixels.push((px.iter().map(|p| p[k]).sum::<f32>() / 4.0).round() as u8); + } + } + } + Some(Level { width: w, height: h, pixels }) + } +} + +/// The flat print: the document rect it covers and its raster at full size and at two halvings. +#[derive(Clone, Debug)] +pub struct Print { + pub region: Rect, + pub levels: Vec<Level>, +} + +impl Print { + /// The print of `region` from `pixels` (premultiplied RGBA, `width` × `height`); `None` when + /// the sizes do not agree, a side is 0 or more than [`MAX_SIDE`], or the region is empty. + pub fn new(region: Rect, width: u32, height: u32, pixels: Vec<u8>) -> Option<Print> { + let fits = (1..=MAX_SIDE).contains(&width) && (1..=MAX_SIDE).contains(&height); + let empty = !(region.width() > 0.0 && region.height() > 0.0 && region.is_finite()); + if !fits || empty || pixels.len() != width as usize * height as usize * 4 { + return None; + } + let mut levels = vec![Level { width, height, pixels }]; + while levels.len() < 3 { + let Some(next) = levels.last().and_then(Level::half) else { break }; + levels.push(next); + } + Some(Print { region, levels }) + } + + /// The print's color (premultiplied, 0 to 255) at document point `p`, from the level whose + /// pixels are closest to `footprint` points across; transparent outside the region. + fn sample(&self, p: Point, footprint: f64) -> [f32; 4] { + let Some(base) = self.levels.first() else { return [0.0; 4] }; + if !self.region.contains(p) { + return [0.0; 4]; + } + let per_point = f64::from(base.width) / self.region.width(); + let level = if footprint.is_finite() && footprint > 0.0 { (footprint * per_point).log2().floor().max(0.0) as usize } else { 0 }; + let level = level.min(self.levels.len() - 1); + let Some(l) = self.levels.get(level) else { return [0.0; 4] }; + // Each level halves the one before it, so a pixel of level n covers 2ⁿ of the first's. + let shrink = f64::from(1u32 << level); + let sx = f64::from(base.width) / self.region.width() / shrink; + let sy = f64::from(base.height) / self.region.height() / shrink; + l.sample((p.x - self.region.x0) * sx, (p.y - self.region.y0) * sy) + } +} + +/// What [`render`] draws: a folded blank, its print (if any), the color of the board's back and of +/// its printed side where the print has no art (straight RGBA), and the view. +pub struct Scene<'a> { + pub blank: &'a Blank, + pub folded: &'a Folded, + pub print: Option<&'a Print>, + pub inside: [u8; 4], + pub outside: [u8; 4], + pub camera: Camera, +} + +/// A drawn view: premultiplied RGBA, 4 bytes a pixel, transparent where no panel is; and for each +/// pixel the panel drawn there plus 1 (0 for none). +#[derive(Clone, Debug)] +pub struct Image { + pub width: u32, + pub height: u32, + pub pixels: Vec<u8>, + pub panels: Vec<u16>, +} + +impl Image { + /// The panel drawn at pixel `(x, y)`. + pub fn panel_at(&self, x: u32, y: u32) -> Option<usize> { + if x >= self.width || y >= self.height { + return None; + } + let i = y as usize * self.width as usize + x as usize; + self.panels.get(i).and_then(|&p| usize::from(p).checked_sub(1)) + } +} + +/// The 3D bounds of `blank`'s panels folded as `folded` places them (low and high corners). +pub fn bounds(blank: &Blank, folded: &Folded) -> Option<(V3, V3)> { + let mut lo = [f64::INFINITY; 3]; + let mut hi = [f64::NEG_INFINITY; 3]; + for (panel, f) in blank.panels.iter().zip(&folded.panels) { + let Some(b) = panel.outline.bounds() else { continue }; + for c in [Point::new(b.x0, b.y0), Point::new(b.x1, b.y0), Point::new(b.x0, b.y1), Point::new(b.x1, b.y1)] { + let p = f.pose.place(c); + for k in 0..3 { + lo[k] = lo[k].min(p[k]); + hi[k] = hi[k].max(p[k]); + } + } + } + lo.iter().chain(&hi).all(|v| v.is_finite()).then_some((lo, hi)) +} + +/// A panel ready to fill: its projective map from the flat blank to the view and back, its depth +/// plane in view terms, and its color factors. +struct Mapped { + /// Flat (u, v, 1) → (x w, y w, w) in pixels, as rows. + forward: [[f64; 3]; 3], + /// The inverse of `forward`. + inverse: [[f64; 3]; 3], + /// View depth at flat (u, v): u a + v b + c. + depth: [f64; 3], + printed: bool, + shade: f32, +} + +fn mul(m: &[[f64; 3]; 3], v: V3) -> V3 { + [dot(m[0], v), dot(m[1], v), dot(m[2], v)] +} + +fn invert(m: &[[f64; 3]; 3]) -> Option<[[f64; 3]; 3]> { + let [[a, b, c], [d, e, f], [g, h, i]] = *m; + let co = [e * i - f * h, f * g - d * i, d * h - e * g]; + let det = a * co[0] + b * co[1] + c * co[2]; + if !(det.is_finite() && det.abs() > 1e-300) { + return None; + } + let inv = [ + [co[0] / det, (c * h - b * i) / det, (b * f - c * e) / det], + [co[1] / det, (a * i - c * g) / det, (c * d - a * f) / det], + [co[2] / det, (b * g - a * h) / det, (a * e - b * d) / det], + ]; + inv.iter().flatten().all(|v| v.is_finite()).then_some(inv) +} + +fn map_panel(camera: &Camera, f: &super::FoldedPanel) -> Option<Mapped> { + let r = camera.rotation(); + let turn = |v: V3| mul(&r, f.pose.turn(v)); + let (a, b) = (turn([1.0, 0.0, 0.0]), turn([0.0, 1.0, 0.0])); + let o = camera.to_view(f.pose.t); + let (cx, cy) = (f64::from(camera.width) / 2.0 + camera.pan[0], f64::from(camera.height) / 2.0 + camera.pan[1]); + let normal = turn([0.0, 0.0, 1.0]); + let (w, k, printed) = match camera.eye() { + Some((eye, focal)) => ([-a[2], -b[2], eye - o[2]], focal, dot(normal, [-o[0], -o[1], eye - o[2]]) > 0.0), + None => ([0.0, 0.0, 1.0], camera.scale, normal[2] > 0.0), + }; + let x = [cx * w[0] + k * a[0], cx * w[1] + k * b[0], cx * w[2] + k * o[0]]; + let y = [cy * w[0] - k * a[1], cy * w[1] - k * b[1], cy * w[2] - k * o[1]]; + let forward = [x, y, w]; + let inverse = invert(&forward)?; + let facing = if printed { normal } else { [-normal[0], -normal[1], -normal[2]] }; + let shade = (0.6 + 0.4 * dot(facing, LIGHT).max(0.0)) as f32; + Some(Mapped { forward, inverse, depth: [a[2], b[2], o[2]], printed, shade }) +} + +/// `ring` (flat points) cut to the side of the plane `w · (u, v, 1) ≥ near`. +fn clip(ring: &[[f64; 2]], w: V3, near: f64) -> Vec<[f64; 2]> { + let at = |p: [f64; 2]| dot(w, [p[0], p[1], 1.0]) - near; + let mut out = Vec::with_capacity(ring.len() + 4); + for (k, &p) in ring.iter().enumerate() { + let Some(&q) = ring.get((k + 1) % ring.len()) else { continue }; + let (dp, dq) = (at(p), at(q)); + if dp >= 0.0 { + out.push(p); + } + if (dp >= 0.0) != (dq >= 0.0) { + let t = dp / (dp - dq); + out.push([p[0] + (q[0] - p[0]) * t, p[1] + (q[1] - p[1]) * t]); + } + } + out +} + +/// The buffers [`render`] fills. +struct Target { + width: usize, + height: usize, + color: Vec<u8>, + depth: Vec<f64>, + rank: Vec<u16>, + panel: Vec<u16>, +} + +/// One panel's fill: its map, rank (for ties), panel number and colors. +struct Fill<'a> { + mapped: &'a Mapped, + rank: u16, + panel: u16, + print: Option<&'a Print>, + inside: [f32; 4], + outside: [f32; 4], +} + +impl Fill<'_> { + /// The document point under pixel center `(x, y)`, or `None` behind the eye. + fn flat_at(&self, x: f64, y: f64) -> Option<(f64, f64)> { + let [u, v, w] = mul(&self.mapped.inverse, [x, y, 1.0]); + (w > 0.0 && w.is_finite()).then(|| (u / w, v / w)).filter(|(u, v)| u.is_finite() && v.is_finite()) + } + + /// The color of the panel at flat point `(u, v)`, `footprint` points across a pixel. + fn color(&self, u: f64, v: f64, footprint: f64) -> [f32; 4] { + let base = if self.mapped.printed { + let p = self.print.map_or([0.0; 4], |pr| pr.sample(Point::new(u, -v), footprint)); + let under = 1.0 - p[3] / 255.0; + [p[0] + self.outside[0] * under, p[1] + self.outside[1] * under, p[2] + self.outside[2] * under, 255.0] + } else { + self.inside + }; + let s = self.mapped.shade; + [base[0] * s, base[1] * s, base[2] * s, base[3]] + } + + /// Fill the span of row `row` from `x0` to `x1` (pixel coordinates) into `target`. + fn span(&self, target: &mut Target, row: usize, x0: f64, x1: f64) { + let first = (x0 - 0.5).ceil().max(0.0); + let last = ((x1 - 0.5).ceil() - 1.0).min(target.width as f64 - 1.0); + if first > last { + return; + } + let y = row as f64 + 0.5; + for col in first as usize..=last as usize { + let x = col as f64 + 0.5; + let Some((u, v)) = self.flat_at(x, y) else { continue }; + let [a, b, c] = self.mapped.depth; + let z = u * a + v * b + c; + let i = row * target.width + col; + let (Some(&zb), Some(&rb)) = (target.depth.get(i), target.rank.get(i)) else { continue }; + let wins = z > zb + TIE || ((z - zb).abs() <= TIE && self.rank > rb); + if !wins { + continue; + } + let footprint = self.flat_at(x + 1.0, y).map_or(0.0, |(u2, v2)| (u2 - u).hypot(v2 - v)); + let color = self.color(u, v, footprint); + if let Some(px) = target.color.get_mut(i * 4..i * 4 + 4) { + for (o, c) in px.iter_mut().zip(color) { + *o = c.round().clamp(0.0, 255.0) as u8; + } + } + if let Some(d) = target.depth.get_mut(i) { + *d = z; + } + if let Some(r) = target.rank.get_mut(i) { + *r = self.rank; + } + if let Some(p) = target.panel.get_mut(i) { + *p = self.panel; + } + } + } + + /// Fill the projected `rings` (pixel coordinates), even-odd, into `target`. + fn rings(&self, target: &mut Target, rings: &[Vec<[f64; 2]>]) { + let ys = rings.iter().flatten().map(|p| p[1]); + let (lo, hi) = ys.fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), y| (lo.min(y), hi.max(y))); + if !(lo.is_finite() && hi.is_finite()) { + return; + } + let first = (lo - 0.5).ceil().max(0.0); + let last = (hi - 0.5).floor().min(target.height as f64 - 1.0); + if first > last { + return; + } + let mut xs = vec![]; + for row in first as usize..=last as usize { + let y = row as f64 + 0.5; + xs.clear(); + for ring in rings { + for (k, p) in ring.iter().enumerate() { + let Some(q) = ring.get((k + 1) % ring.len()) else { continue }; + if (p[1] <= y) != (q[1] <= y) { + xs.push(p[0] + (y - p[1]) * (q[0] - p[0]) / (q[1] - p[1])); + } + } + } + xs.retain(|x| x.is_finite()); + xs.sort_by(f64::total_cmp); + for &[a, b] in xs.as_chunks::<2>().0 { + self.span(target, row, a, b); + } + } + } +} + +fn rgba(c: [u8; 4]) -> [f32; 4] { + let a = f32::from(c[3]) / 255.0; + [f32::from(c[0]) * a, f32::from(c[1]) * a, f32::from(c[2]) * a, f32::from(c[3])] +} + +/// The outline rings of `panel` in flat terms (u, v), flattened finely enough for `scale` pixels a +/// point. +fn flat_rings(panel: &Panel, scale: f64) -> Option<Vec<Vec<[f64; 2]>>> { + let b = panel.outline.bounds()?; + let tolerance = (0.25 / scale).max((b.width() + b.height()) * 1e-5).max(1e-6); + Some(polygon(&panel.outline, tolerance)?.into_iter().map(|r| r.into_iter().map(|p| [p.x, -p.y]).collect()).collect()) +} + +/// `scene` drawn; `None` when the view is not usable (a size of 0, a side over [`MAX_SIDE`], more +/// than [`MAX_PIXELS`] pixels, or a value that is not finite). Panels whose map is not finite, or whose outline has more than +/// [`super::MAX_POLYGON_POINTS`] points, are left out. +pub fn render(scene: &Scene) -> Option<Image> { + let camera = scene.camera; + if !camera.usable() { + return None; + } + let (width, height) = (camera.width as usize, camera.height as usize); + let pixels = width * height; + let mut target = + Target { width, height, color: vec![0; pixels * 4], depth: vec![f64::NEG_INFINITY; pixels], rank: vec![0; pixels], panel: vec![0; pixels] }; + let (inside, outside) = (rgba(scene.inside), rgba(scene.outside)); + let near = camera.eye().map(|(eye, _)| eye * NEAREST); + for (rank, &pi) in scene.folded.order.iter().enumerate() { + let (Some(panel), Some(f)) = (scene.blank.panels.get(pi), scene.folded.panels.get(pi)) else { continue }; + let Some(mapped) = map_panel(&camera, f) else { continue }; + let Some(rings) = flat_rings(panel, camera.scale) else { continue }; + let projected: Vec<Vec<[f64; 2]>> = rings + .iter() + .map(|r| match near { + Some(near) => clip(r, mapped.forward[2], near), + None => r.clone(), + }) + .filter(|r| r.len() >= 3) + .map(|r| { + r.into_iter() + .filter_map(|[u, v]| { + let [x, y, w] = mul(&mapped.forward, [u, v, 1.0]); + let p = [x / w, y / w]; + (w > 0.0 && p[0].is_finite() && p[1].is_finite()).then_some(p) + }) + .collect::<Vec<_>>() + }) + .filter(|r| r.len() >= 3) + .collect(); + let fill = Fill { + mapped: &mapped, + rank: u16::try_from(rank + 1).unwrap_or(u16::MAX), + panel: u16::try_from(pi + 1).unwrap_or(u16::MAX), + print: scene.print, + inside, + outside, + }; + fill.rings(&mut target, &projected); + } + Some(Image { width: camera.width, height: camera.height, pixels: target.color, panels: target.panel }) +} + +#[cfg(test)] +mod tests; diff --git a/crates/three-d/src/fold/raster/tests.rs b/crates/three-d/src/fold/raster/tests.rs new file mode 100644 index 0000000000..477040b571 --- /dev/null +++ b/crates/three-d/src/fold/raster/tests.rs @@ -0,0 +1,179 @@ +use vectorcraft_geom::{PathData, Point, Rect, SubPath}; + +use super::super::{Blank, Folded, FoldedPanel, Panel, Pose}; +use super::*; + +fn square(x0: f64, y0: f64, x1: f64, y1: f64) -> SubPath { + SubPath::polyline(&[Point::new(x0, y0), Point::new(x1, y0), Point::new(x1, y1), Point::new(x0, y1)], true) +} + +fn panel(subpaths: Vec<SubPath>) -> Panel { + Panel { outline: PathData::new(subpaths), area: 0.0 } +} + +/// A blank of `panels` and a fold that places each at `poses`, in the order given. +fn scene_of(panels: Vec<Panel>, poses: Vec<Pose>) -> (Blank, Folded) { + let n = panels.len(); + let folded = Folded { + base: 0, + panels: poses.into_iter().map(|pose| FoldedPanel { pose, parent: None, depth: 0 }).collect(), + order: (0..n).collect(), + hinges: vec![], + collisions: vec![], + }; + (Blank { panels, hinges: vec![], holes: vec![] }, folded) +} + +/// Facing the printed side, 100 × 100 pixels, one pixel a point, the flat square 0..100 filling it. +fn front() -> Camera { + Camera { width: 100, height: 100, rotate_x: 0.0, rotate_y: 0.0, scale: 1.0, pan: [0.0; 2], perspective: 0.0, center: [50.0, -50.0, 0.0] } +} + +fn moved(z: f64) -> Pose { + Pose { t: [0.0, 0.0, z], ..Pose::IDENTITY } +} + +fn pixel(img: &Image, x: u32, y: u32) -> [u8; 4] { + let i = (y * img.width + x) as usize * 4; + [img.pixels[i], img.pixels[i + 1], img.pixels[i + 2], img.pixels[i + 3]] +} + +/// A 2 × 2 print of the square 0..100: red, green on top; blue, white below. +fn quads() -> Print { + let px = [[255, 0, 0, 255], [0, 255, 0, 255], [0, 0, 255, 255], [255, 255, 255, 255]]; + Print::new(Rect::new(0.0, 0.0, 100.0, 100.0), 2, 2, px.concat()).expect("a print") +} + +const WHITE: [u8; 4] = [255, 255, 255, 255]; + +#[test] +fn a_flat_panel_takes_the_print_s_color_under_each_pixel() { + let (b, f) = scene_of(vec![panel(vec![square(0.0, 0.0, 100.0, 100.0)])], vec![Pose::IDENTITY]); + let print = quads(); + let img = render(&Scene { blank: &b, folded: &f, print: Some(&print), inside: [0, 0, 0, 255], outside: WHITE, camera: front() }).expect("drawn"); + let shade = 0.6 + 0.4 * 0.74; + let lit = |c: f64| (c * shade).round() as u8; + assert_eq!(pixel(&img, 5, 5), [lit(255.0), 0, 0, 255], "top left is red"); + assert_eq!(pixel(&img, 94, 5), [0, lit(255.0), 0, 255], "top right is green"); + assert_eq!(pixel(&img, 5, 94), [0, 0, lit(255.0), 255], "bottom left is blue"); + assert_eq!(img.panel_at(50, 50), Some(0)); + // Where the print has no art, the board's printed side shows. + let empty = Print::new(Rect::new(0.0, 0.0, 100.0, 100.0), 1, 1, vec![0; 4]).expect("a print"); + let img = render(&Scene { blank: &b, folded: &f, print: Some(&empty), inside: [0, 0, 0, 255], outside: [200, 100, 50, 255], camera: front() }) + .expect("drawn"); + assert_eq!(pixel(&img, 50, 50), [lit(200.0), lit(100.0), lit(50.0), 255]); +} + +#[test] +fn the_back_of_a_panel_shows_the_inside_color() { + let (b, f) = scene_of(vec![panel(vec![square(0.0, 0.0, 100.0, 100.0)])], vec![Pose::IDENTITY]); + let print = quads(); + let camera = Camera { rotate_y: 180.0, ..front() }; + let img = render(&Scene { blank: &b, folded: &f, print: Some(&print), inside: [0, 200, 0, 255], outside: WHITE, camera }).expect("drawn"); + let [r, g, bl, a] = pixel(&img, 50, 50); + assert!(r == 0 && bl == 0 && g > 100 && a == 255, "{:?}", [r, g, bl, a]); +} + +#[test] +fn the_nearer_of_two_panels_shows_and_a_tie_goes_to_the_later_one() { + let whole = || panel(vec![square(0.0, 0.0, 100.0, 100.0)]); + let draw = |z: f64| { + let (b, f) = scene_of(vec![whole(), whole()], vec![Pose::IDENTITY, moved(z)]); + render(&Scene { blank: &b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera: front() }).expect("drawn") + }; + assert_eq!(draw(5.0).panel_at(50, 50), Some(1), "panel 1 is in front"); + assert_eq!(draw(-5.0).panel_at(50, 50), Some(0), "panel 1 is behind"); + assert_eq!(draw(0.0).panel_at(50, 50), Some(1), "a tie goes to the panel later in the order"); + // Panels that cross: each shows where it is nearer. + let tilted = Pose { m: [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.5, 0.0, 1.0]], t: [0.0, 0.0, -25.0] }; + let (b, f) = scene_of(vec![whole(), whole()], vec![Pose::IDENTITY, tilted]); + let img = render(&Scene { blank: &b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera: front() }).expect("drawn"); + assert_eq!(img.panel_at(20, 50), Some(0), "the tilted panel is behind on the left"); + assert_eq!(img.panel_at(80, 50), Some(1), "and in front on the right"); +} + +#[test] +fn a_hole_in_a_panel_is_left_empty() { + let (b, f) = scene_of(vec![panel(vec![square(0.0, 0.0, 100.0, 100.0), square(30.0, 30.0, 70.0, 70.0)])], vec![Pose::IDENTITY]); + let img = render(&Scene { blank: &b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera: front() }).expect("drawn"); + assert_eq!(img.panel_at(50, 50), None); + assert_eq!(pixel(&img, 50, 50), [0; 4]); + assert_eq!(img.panel_at(10, 50), Some(0)); +} + +#[test] +fn a_panel_past_the_eye_at_a_wide_perspective_is_cut_at_the_near_plane() { + // A long panel standing out of the page toward the viewer, through the eye. + let toward = Pose { m: [[1.0, 0.0, 0.0], [0.0, 0.0, -1.0], [0.0, 1.0, 0.0]], t: [0.0, -50.0, 0.0] }; + let (b, f) = scene_of(vec![panel(vec![square(0.0, -1000.0, 100.0, 1000.0)])], vec![toward]); + for perspective in [1.0, 60.0, 160.0, 179.0] { + let camera = Camera { perspective, scale: 8.0, rotate_x: 30.0, ..front() }; + let img = render(&Scene { blank: &b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn"); + let drawn = img.panels.iter().filter(|&&p| p != 0).count(); + assert!(drawn > 0, "{perspective}°: some of it shows"); + assert_eq!(img.pixels.len(), 100 * 100 * 4); + } +} + +#[test] +fn unusable_views_and_prints_are_refused() { + let (b, f) = scene_of(vec![panel(vec![square(0.0, 0.0, 100.0, 100.0)])], vec![Pose::IDENTITY]); + for camera in [ + Camera { width: 0, ..front() }, + Camera { height: MAX_SIDE + 1, ..front() }, + Camera { width: MAX_SIDE, height: MAX_PIXELS / MAX_SIDE + 1, ..front() }, + Camera { scale: 0.0, ..front() }, + Camera { rotate_x: f64::NAN, ..front() }, + Camera { center: [f64::INFINITY, 0.0, 0.0], ..front() }, + ] { + assert!(render(&Scene { blank: &b, folded: &f, print: None, inside: [0; 4], outside: WHITE, camera }).is_none(), "{camera:?}"); + } + let region = Rect::new(0.0, 0.0, 10.0, 10.0); + assert!(Print::new(region, 2, 2, vec![0; 15]).is_none(), "too few bytes"); + assert!(Print::new(region, 0, 2, vec![]).is_none()); + assert!(Print::new(region, MAX_SIDE + 1, 1, vec![0; (MAX_SIDE as usize + 1) * 4]).is_none()); + assert!(Print::new(Rect::new(0.0, 0.0, 0.0, 10.0), 1, 1, vec![0; 4]).is_none(), "an empty region"); + let p = Print::new(region, 8, 4, vec![255; 8 * 4 * 4]).expect("a print"); + assert_eq!(p.levels.iter().map(|l| (l.width, l.height)).collect::<Vec<_>>(), vec![(8, 4), (4, 2), (2, 1)]); +} + +#[test] +fn halving_an_odd_sized_print_keeps_its_last_row_and_column() { + // 3 × 3, transparent but for an opaque white last column and last row. + let mut px = vec![0u8; 3 * 3 * 4]; + for i in [2, 5, 6, 7, 8] { + px[i * 4..i * 4 + 4].copy_from_slice(&[255; 4]); + } + let p = Print::new(Rect::new(0.0, 0.0, 30.0, 30.0), 3, 3, px).expect("a print"); + let half = &p.levels[1]; + assert_eq!((half.width, half.height), (2, 2)); + // The bottom right pixel of the half level covers only the corner pixel. + assert_eq!(&half.pixels[12..16], &[255; 4]); + assert_eq!(&half.pixels[0..4], &[0; 4], "the top left covers four transparent pixels"); +} + +#[test] +fn a_print_far_smaller_on_screen_samples_a_halved_level() { + // Columns alternate black and white: halved, they average to gray. + let mut px = vec![]; + for _ in 0..4 { + for x in 0..4 { + px.extend(if x % 2 == 0 { [0, 0, 0, 255] } else { [255, 255, 255, 255] }); + } + } + let print = Print::new(Rect::new(0.0, 0.0, 100.0, 100.0), 4, 4, px).expect("a print"); + let (b, f) = scene_of(vec![panel(vec![square(0.0, 0.0, 100.0, 100.0)])], vec![Pose::IDENTITY]); + // 100 points in 2 pixels: 2 print pixels a view pixel. + let camera = Camera { width: 2, height: 2, scale: 0.02, ..front() }; + let img = render(&Scene { blank: &b, folded: &f, print: Some(&print), inside: [0; 4], outside: WHITE, camera }).expect("drawn"); + let [r, ..] = pixel(&img, 0, 0); + assert!((80..=150).contains(&r), "gray, not a black or white column: {r}"); +} + +#[test] +fn the_bounds_take_in_every_folded_panel() { + let (b, f) = + scene_of(vec![panel(vec![square(0.0, 0.0, 10.0, 10.0)]), panel(vec![square(0.0, 0.0, 10.0, 10.0)])], vec![Pose::IDENTITY, moved(-7.0)]); + let (lo, hi) = bounds(&b, &f).expect("bounds"); + assert_eq!((lo, hi), ([0.0, -10.0, -7.0], [10.0, 0.0, 0.0])); +} diff --git a/crates/three-d/src/fold/tests.rs b/crates/three-d/src/fold/tests.rs index ef014300c0..8031a0b2a1 100644 --- a/crates/three-d/src/fold/tests.rs +++ b/crates/three-d/src/fold/tests.rs @@ -913,4 +913,323 @@ proptest! { sorted.sort_by_key(|i| i.code); prop_assert_eq!(sorted, issues); } + + /// Random fold lines fold at any amount without a panic, every pose finite and every panel + /// keeping its shape. + #[test] + fn random_blanks_fold_to_finite_poses( + segs in proptest::collection::vec((1u8..4, -50.0f64..50.0, -50.0f64..50.0, -50.0f64..50.0, -50.0f64..50.0), 1..8), + amount in 0.0f64..=1.0, + ) { + let kinds = [LineKind::Cut, LineKind::Crease, LineKind::PartialCut, LineKind::Perforation]; + let mut lines: Vec<FoldLine> = segs + .iter() + .enumerate() + .map(|(i, &(k, a, b, c, d))| line(kinds[usize::from(k)], &[(a, b), (c, d)], false, i as u64)) + .collect(); + lines.push(cut(&[(-40.0, -40.0), (40.0, -40.0), (40.0, 40.0), (-40.0, 40.0)], 99)); + let (blanks, _) = blanks(&lines, TOL); + for b in &blanks { + let Some(f) = fold(b, None, amount, TOL) else { continue }; + prop_assert_eq!(f.panels.len(), b.panels.len()); + prop_assert_eq!(f.order.len(), b.panels.len()); + for p in &f.panels { + prop_assert!(p.pose.m.iter().flatten().chain(&p.pose.t).all(|v| v.is_finite())); + let n = p.pose.normal(); + prop_assert!((n[0] * n[0] + n[1] * n[1] + n[2] * n[2] - 1.0).abs() < 1e-9); + } + } + } +} + +/// The 3D corners of panel `i` of `b` folded as `f` places them. +fn corners(b: &Blank, f: &Folded, i: usize) -> Vec<[f64; 3]> { + let rings = polygon(&b.panels[i].outline, 0.01).expect("a polygon"); + rings.into_iter().flatten().map(|p| f.panels[i].pose.place(p)).collect() +} + +fn flat_center(b: &Blank, i: usize) -> [f64; 3] { + let c = point_in(&b.panels[i].outline).expect("a point inside"); + [c.x, -c.y, 0.0] +} + +#[test] +fn a_slotted_box_folds_every_panel_onto_a_face_of_the_box_with_the_print_outside() { + let (b, issues) = check(¬ched_box()); + assert!(issues.is_empty(), "{issues:?}"); + let b = &b[0]; + let f = fold(b, None, 1.0, TOL).expect("folds"); + // The base panel is the leftmost of the two largest body panels: x 20 to 120, y 30 to 110. + let base = &b.panels[f.base]; + assert_eq!(base.outline.bounds().map(|r| (r.x0.round(), r.y0.round())), Some((20.0, 30.0))); + // The box: the base panel's face (z = 0), 60 deep (the narrow body panels' width). + let (lo, hi) = ([20.0, -110.0, -60.0], [120.0, -30.0, 0.0]); + let middle = [70.0, -70.0, -30.0]; + for i in 0..b.panels.len() { + let points = corners(b, &f, i); + let face = (0..3).find_map(|k| [lo[k], hi[k]].into_iter().find(|&at| points.iter().all(|p| (p[k] - at).abs() < 1e-6)).map(|at| (k, at))); + let (k, at) = face.unwrap_or_else(|| panic!("panel {i} lies on no face of the box: {points:?}")); + for p in &points { + for j in 0..3 { + assert!(p[j] > lo[j] - 1e-6 && p[j] < hi[j] + 1e-6, "panel {i} reaches out of the box: {p:?}"); + } + } + // The printed side faces out of the box. + let n = f.panels[i].pose.normal(); + assert!((n[k].abs() - 1.0).abs() < 1e-9, "panel {i} is square to its face: {n:?}"); + assert!(n[k] * (at - middle[k]) > 0.0, "panel {i}'s print faces out: {n:?}"); + } + assert!(f.hinges.iter().all(|h| h.tree && h.closes && (h.angle - 90.0).abs() < 1e-12), "{:?}", f.hinges); + assert!(f.collisions.is_empty(), "the stacked flaps and the glue flap do not cross: {:?}", f.collisions); + assert_eq!(f.order.first(), Some(&f.base)); + assert_eq!(f.order.len(), 13); +} + +#[test] +fn at_amount_0_the_blank_is_flat() { + let (b, _) = check(¬ched_box()); + let f = fold(&b[0], None, 0.0, TOL).expect("folds"); + for p in &f.panels { + for (row, want) in p.pose.m.iter().zip(Pose::IDENTITY.m) { + assert!(row.iter().zip(want).all(|(a, b)| (a - b).abs() < 1e-12), "{:?}", p.pose); + } + assert!(p.pose.t.iter().all(|v| v.abs() < 1e-9), "{:?}", p.pose); + } +} + +/// A 100 × 60 rectangle split by a line of `kind` at x = 60 (drawn upward when `up`), turned by +/// `quarter` quarter turns about the origin and mirrored in x when `mirror`. +fn two_panels(kind: LineKind, quarter: u8, mirror: bool, up: bool) -> Vec<FoldLine> { + let at = |(x, y): (f64, f64)| { + let x = if mirror { -x } else { x }; + (0..quarter).fold((x, y), |(x, y), _| (-y, x)) + }; + let outline: Vec<(f64, f64)> = [(0.0, 0.0), (100.0, 0.0), (100.0, 60.0), (0.0, 60.0)].into_iter().map(at).collect(); + let (a, b) = if up { ((60.0, 60.0), (60.0, 0.0)) } else { ((60.0, 0.0), (60.0, 60.0)) }; + vec![cut(&outline, 1), line(kind, &[at(a), at(b)], false, 2)] +} + +#[test] +fn a_crease_folds_away_from_the_print_and_a_partial_cut_toward_it_however_it_is_drawn() { + for quarter in 0..4 { + for mirror in [false, true] { + for up in [false, true] { + for (kind, sign) in [(LineKind::Crease, -1.0), (LineKind::Perforation, -1.0), (LineKind::PartialCut, 1.0)] { + let case = format!("{kind:?}, {quarter} quarter turns, mirrored {mirror}, drawn up {up}"); + let (b, issues) = check(&two_panels(kind, quarter, mirror, up)); + assert!(issues.is_empty(), "{case}: {issues:?}"); + let b = &b[0]; + let f = fold(b, None, 1.0, TOL).expect("folds"); + let child = 1 - f.base; + let h = &b.hinges[0]; + let hinge = [(h.from.x + h.to.x) / 2.0, -(h.from.y + h.to.y) / 2.0, 0.0]; + let c = flat_center(b, child); + let away = [c[0] - hinge[0], c[1] - hinge[1], 0.0]; + let along = [h.to.x - h.from.x, h.from.y - h.to.y]; + let off_line = (along[0] * away[1] - along[1] * away[0]).abs() / along[0].hypot(along[1]); + let placed = f.panels[child].pose.apply(c); + // The child stands up out of the plane: behind it for a crease, in front of it + // for a partial cut, at its distance from the hinge. + assert!(placed[2] * sign > 0.0, "{case}: {placed:?}"); + assert!((placed[2].abs() - off_line).abs() < 1e-6, "{case}: {placed:?} {off_line}"); + // Its printed side faces away from the base panel after a crease, back toward + // it after a partial cut. + let n = f.panels[child].pose.normal(); + assert!((n[0] * away[0] + n[1] * away[1]) * -sign > 0.0, "{case}: {n:?}"); + // Half way, the child is half way round. + let half = fold(b, None, 0.5, TOL).expect("folds"); + let z = half.panels[child].pose.normal()[2]; + assert!((z - std::f64::consts::FRAC_1_SQRT_2).abs() < 1e-9, "{case}: {z}"); + } + } + } + } +} + +/// A 100 × 100 square divided into four panels by a crease across it each way. +fn crossed() -> Vec<FoldLine> { + vec![ + cut(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)], 1), + crease((50.0, 0.0), (50.0, 100.0), 2), + crease((0.0, 50.0), (100.0, 50.0), 3), + ] +} + +#[test] +fn a_loop_of_hinges_closes_when_flat_and_reports_its_gap_when_folded() { + let (b, issues) = check(&crossed()); + assert!(issues.is_empty(), "{issues:?}"); + let b = &b[0]; + assert_eq!((b.panels.len(), b.hinges.len()), (4, 4)); + let folded = fold(b, None, 1.0, TOL).expect("folds"); + let closing: Vec<&FoldedHinge> = folded.hinges.iter().filter(|h| !h.tree).collect(); + assert_eq!(closing.len(), 1, "three hinges make the tree, one closes the loop"); + assert!(!closing[0].closes && closing[0].gap > 10.0, "{closing:?}"); + // The gap is measured folded all the way, whatever the amount: flat or half way, the loop is + // still reported open by the same gap. + for amount in [0.0, 0.5] { + let part = fold(b, None, amount, TOL).expect("folds"); + let h = part.hinges.iter().find(|h| !h.tree).expect("a closing hinge"); + assert!(!h.closes && (h.gap - closing[0].gap).abs() < 1e-9, "{amount}: {h:?}"); + } + // The base is the top-left panel: four equal panels tie, and the highest, then leftmost, wins. + assert_eq!(b.panels[folded.base].outline.bounds().map(|r| (r.x0.round(), r.y0.round())), Some((0.0, 0.0))); +} + +#[test] +fn hinges_that_start_at_one_point_fold_the_same_in_any_line_order() { + // About the bottom-right panel, its two hinges both start at the middle of the square. + let lines = crossed(); + let orders = [[0, 1, 2], [0, 2, 1], [2, 1, 0], [1, 2, 0], [1, 0, 2], [2, 0, 1]]; + let mut seen = None; + for order in orders { + let lines: Vec<FoldLine> = order.iter().map(|&i| lines[i].clone()).collect(); + let (b, issues) = check(&lines); + assert!(issues.is_empty(), "{order:?}: {issues:?}"); + let b = &b[0]; + let base = panel_at(b, p(75.0, 75.0)).expect("the bottom-right panel"); + let f = fold(b, Some(base), 1.0, TOL).expect("folds"); + let closing = f.hinges.iter().zip(&b.hinges).find(|(h, _)| !h.tree).map(|(_, h)| ((h.from.x + h.to.x) / 2.0, (h.from.y + h.to.y) / 2.0)); + let top_left = panel_at(b, p(25.0, 25.0)).expect("the top-left panel"); + let placed = f.panels[top_left].pose.place(p(25.0, 25.0)).map(|v| (v * 1e6).round()); + let got = (closing, placed); + assert_eq!(seen.get_or_insert(got), &got, "{order:?}"); + } +} + +/// A 100 × 60 rectangle: the left 60 pt is one panel, the right is split across at y = 30, and the +/// line between them bends by `lean` pt over its lower half. +fn leaning(lean: f64) -> Vec<FoldLine> { + vec![ + cut(&[(0.0, 0.0), (100.0, 0.0), (100.0, 60.0), (0.0, 60.0)], 1), + crease((60.0, 0.0), (60.0, 30.0), 2), + crease((60.0, 30.0), (60.0 + lean, 60.0), 3), + crease((60.0, 30.0), (100.0, 30.0), 4), + ] +} + +#[test] +fn a_loop_closes_within_the_tolerance_or_half_a_percent_of_its_hinge() { + // Both right panels turn about one line, so the hinge between them closes exactly. + let gap = |lean: f64, amount: f64| { + let (b, issues) = check(&leaning(lean)); + assert!(issues.is_empty(), "{lean}: {issues:?}"); + let b = &b[0]; + assert_eq!((b.panels.len(), b.hinges.len()), (3, 3)); + let base = panel_at(b, p(30.0, 30.0)).expect("the left panel"); + let f = fold(b, Some(base), amount, TOL).expect("folds"); + let h = f.hinges.iter().find(|h| !h.tree).expect("a closing hinge").clone(); + (h.closes, h.gap) + }; + let (closes, at) = gap(0.0, 1.0); + assert!(closes && at < 1e-9, "{at}"); + // A small lean opens it by more than the 0.1 pt tolerance but less than 0.5% of its 40 pt + // length (0.2 pt): still closed. + let (closes, at) = gap(0.1, 1.0); + assert!(closes && at > TOL && at <= 0.2, "{at}"); + // A larger lean opens it past both, flat or folded. + for amount in [0.0, 1.0] { + let (closes, at) = gap(1.0, amount); + assert!(!closes && at > 0.2, "{amount}: {at}"); + } +} + +#[test] +fn a_panel_no_hinge_joins_stays_flat_where_it_is() { + let lines = vec![ + cut(&[(0.0, 0.0), (50.0, 0.0), (50.0, 49.95), (100.0, 49.95), (100.0, 99.95), (50.0, 99.95), (50.0, 50.0), (0.0, 50.0)], 1), + crease((50.0, 49.95), (50.0, 50.0), 2), + ]; + let (b, _) = check(&lines); + let b = &b[0]; + assert_eq!((b.panels.len(), b.hinges.len()), (2, 0)); + let f = fold(b, None, 1.0, TOL).expect("folds"); + let loose = 1 - f.base; + assert_eq!(f.panels[loose].parent, None); + assert_eq!(f.panels[loose].pose, Pose::IDENTITY); + assert_eq!(f.order, vec![f.base, loose], "the loose panel comes last"); +} + +#[test] +fn a_child_of_a_notched_panel_folds_away_from_the_print() { + // The base is an L: a 30 × 140 strip with an 80 pt arm along its top running right to x = 300. + // The child, below the arm past a 2 pt slot, is hinged to the strip along x = 30. + let lines = vec![ + cut(&[(0.0, 0.0), (300.0, 0.0), (300.0, 80.0), (30.0, 80.0), (30.0, 82.0), (300.0, 82.0), (300.0, 140.0), (0.0, 140.0)], 1), + crease((30.0, 82.0), (30.0, 140.0), 2), + ]; + let (b, issues) = check(&lines); + assert!(issues.is_empty(), "{issues:?}"); + let b = &b[0]; + let base = panel_at(b, p(15.0, 110.0)).expect("the L"); + let child = panel_at(b, p(150.0, 110.0)).expect("the child"); + // The L's inside point lies in its arm, on the child's side of the hinge's line. + let inside = b.panels[base].point_inside().expect("a point inside"); + assert!(inside.x > 30.0, "{inside:?}"); + for (kind, sign) in [(LineKind::Crease, -1.0), (LineKind::PartialCut, 1.0)] { + let mut lines = lines.clone(); + lines[1].kind = kind; + let (b, _) = check(&lines); + let f = fold(&b[0], Some(base), 1.0, TOL).expect("folds"); + let placed = f.panels[child].pose.place(p(150.0, 110.0)); + assert!(placed[2] * sign > 99.0, "{kind:?}: {placed:?}"); + } +} + +#[test] +fn a_lid_folded_over_the_base_crosses_the_taller_wall_opposite() { + // A strip: a 120 pt lid, a 30 pt wall, the 100 pt base and a 60 pt wall, all 50 pt deep. + let lines = vec![ + cut(&[(0.0, 0.0), (310.0, 0.0), (310.0, 50.0), (0.0, 50.0)], 1), + crease((120.0, 0.0), (120.0, 50.0), 2), + crease((150.0, 0.0), (150.0, 50.0), 3), + crease((250.0, 0.0), (250.0, 50.0), 4), + ]; + let (b, issues) = check(&lines); + assert!(issues.is_empty(), "{issues:?}"); + let b = &b[0]; + let base = panel_at(b, p(200.0, 25.0)).expect("the base panel"); + let (lid, wall) = (panel_at(b, p(60.0, 25.0)).unwrap(), panel_at(b, p(280.0, 25.0)).unwrap()); + let f = fold(b, Some(base), 1.0, TOL).expect("folds"); + assert_eq!(f.collisions, vec![(lid.min(wall), lid.max(wall))]); + // Half folded, nothing crosses yet. + assert!(fold(b, Some(base), 0.4, TOL).expect("folds").collisions.is_empty()); +} + +#[test] +fn the_base_is_the_panel_under_a_point_and_the_same_in_any_input_order() { + let lines = vec![cut(&[(0.0, 0.0), (100.0, 0.0), (100.0, 60.0), (0.0, 60.0)], 1), crease((50.0, 0.0), (50.0, 60.0), 2)]; + let (b, _) = check(&lines); + assert_eq!(panel_at(&b[0], p(500.0, 500.0)), None, "a point outside every panel"); + let right = panel_at(&b[0], p(75.0, 30.0)).expect("the right panel"); + assert_eq!(fold(&b[0], Some(right), 1.0, TOL).expect("folds").base, right); + let mut reversed = lines.clone(); + reversed.reverse(); + let (r, _) = check(&reversed); + for blank in [&b[0], &r[0]] { + let f = fold(blank, None, 1.0, TOL).expect("folds"); + // Equal panels: the leftmost wins. + assert_eq!(blank.panels[f.base].outline.bounds().map(|r| r.x0.round()), Some(0.0)); + } + assert!(fold(&b[0], Some(9), 1.0, TOL).is_none(), "no panel 9"); + assert!(fold(&b[0], None, 1.5, TOL).is_none(), "past 1"); + assert!(fold(&b[0], None, f64::NAN, TOL).is_none()); + assert!(fold(&Blank::default(), None, 1.0, TOL).is_none(), "no panels"); +} + +#[test] +fn a_partial_cut_takes_its_own_angle_and_a_hinge_its_longest_piece_s() { + let (b, _) = check(&two_panels(LineKind::PartialCut, 0, false, false)); + assert_eq!(b[0].hinges[0].angle, -90.0); + let (b, _) = check(&two_panels(LineKind::Perforation, 0, false, false)); + assert_eq!(b[0].hinges[0].angle, 90.0); + // A crease and a short partial cut on one line: the crease is the longer piece. + let lines = vec![ + cut(&[(0.0, 0.0), (100.0, 0.0), (100.0, 60.0), (0.0, 60.0)], 1), + line(LineKind::PartialCut, &[(60.0, 0.0), (60.0, 10.0)], false, 2), + crease((60.0, 10.0), (60.0, 60.0), 3), + ]; + let (b, _) = check(&lines); + assert_eq!(b[0].hinges.len(), 1); + assert_eq!(b[0].hinges[0].angle, 90.0); } diff --git a/crates/ui-egui/src/addons/packaging.rs b/crates/ui-egui/src/addons/packaging.rs index 54f233d945..4a9303efdd 100644 --- a/crates/ui-egui/src/addons/packaging.rs +++ b/crates/ui-egui/src/addons/packaging.rs @@ -4,7 +4,8 @@ //! paths that role (`addon.packaging.setRole`). Its menu's Role Swatches… picks the swatch that //! carries a role (`addon.packaging.setRoleSwatch`). Its Check button, like the Check Fold Lines menu //! item, checks the fold lines (`addon.packaging.check`) and lists the issues found under it, each -//! with a Select button; the list is kept until the document changes. +//! with a Select button; the list is kept until the document changes. Its Fold Preview button, like +//! the Fold Preview menu item, shows the blank folded in 3D ([`preview`], `ui.foldPreview`). use std::sync::{Arc, Weak}; @@ -25,6 +26,8 @@ pub const SET_ROLE: &str = "addon.packaging.setRole"; pub const SET_ROLE_SWATCH: &str = "addon.packaging.setRoleSwatch"; /// The command that checks the fold lines. pub const CHECK: &str = "addon.packaging.check"; +/// The command that shows the Fold Preview window. +pub const PREVIEW: &str = "ui.foldPreview"; /// The roles by name, as `addon.packaging.setRole` and Role Swatches… take them. pub const ROLES: &[(&str, &str)] = &[("Cut Line", "cut"), ("Crease Line", "crease"), ("Partial Cut Line", "partialCut"), ("Perforation Line", "perforation")]; @@ -46,6 +49,8 @@ pub fn menu() -> Vec<Item> { make("Make Perforation Line", "perforation"), Item::Sep, Item::Cmd("Check Fold Lines", CHECK, Value::Null), + Item::Sep, + Item::Cmd("Fold Preview", PREVIEW, json!({})), ] } @@ -147,6 +152,11 @@ fn show_check(app: &mut VectorcraftApp, ui: &mut Ui) { if widgets::flat_button(ui, tl!("Check"), width).clicked() { run_check(app, ui.ctx(), json!({})); } + if widgets::flat_button(ui, tl!("Fold Preview"), width).clicked() + && let Err(e) = app.run(PREVIEW, json!({})) + { + app.status(e); + } let Some(checked) = last_check(app, ui.ctx()) else { return }; ui.add_space(4.0); dim_label(ui, &crate::i18n::msg(&checked.summary())); @@ -272,5 +282,7 @@ pub fn panel_menu(app: &mut VectorcraftApp, ui: &mut Ui) { } } +pub mod preview; + #[cfg(test)] mod tests; diff --git a/crates/ui-egui/src/addons/packaging/preview.rs b/crates/ui-egui/src/addons/packaging/preview.rs new file mode 100644 index 0000000000..a85b8650d9 --- /dev/null +++ b/crates/ui-egui/src/addons/packaging/preview.rs @@ -0,0 +1,702 @@ +//! The Fold Preview window: the document's blank folded into its 3D shape +//! ([`vectorcraft_three_d::fold::fold`]), with the printed art on the outside of each panel and the +//! board's inside color on the back, drawn by [`vectorcraft_three_d::fold::raster::render`]. +//! +//! The window folds the blank that the document's shown fold lines make, about its largest panel +//! or the panel the user double-clicked. Its print is a raster of the document with the fold lines +//! and the layers that do not print left out ([`vectorcraft_engine::cmd::print_hidden`]), rendered +//! once per document revision, off the UI thread on native builds ([`crate::thumb_worker`]), and +//! sampled through each panel's projective map when the fold, the view or the print changes. Dragging turns the view, a Shift-drag +//! keeps to one axis, a middle-drag or a Space-drag moves it, the wheel zooms, a double-click on a +//! panel makes it the base, and the arrow keys turn the view by 5° when it has the keyboard focus. +//! The settings live in `UiState::fold_preview` (`ui.inspect`); `ui.foldPreview` sets them. + +use std::sync::Arc; + +use egui::{Color32, Rect, Sense, Ui, vec2}; +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; +use vectorcraft_geom::{Point, Rect as DRect}; +use vectorcraft_three_d::fold::raster::{self, Camera, Image, MAX_PIXELS, MAX_SIDE, Print}; +use vectorcraft_three_d::fold::{Blank, Folded, fold, pick}; + +use crate::VectorcraftApp; +use crate::thumb_worker::{Settle, ThumbWorker}; +use crate::widgets::{self, dim_label}; + +/// The window's id (`window.panel {panel: "foldPreview"}`). +pub const ID: &str = "foldPreview"; + +/// The view presets: label, id, the turn about x (the top toward the viewer) and about y (the +/// right side toward the viewer), in degrees. +pub const VIEWS: [(&str, &str, f64, f64); 7] = [ + ("Front", "front", 0.0, 0.0), + ("Back", "back", 0.0, 180.0), + ("Left", "left", 0.0, -90.0), + ("Right", "right", 0.0, 90.0), + ("Top", "top", 90.0, 0.0), + ("Bottom", "bottom", -90.0, 0.0), + ("Three-Quarter", "threeQuarter", 25.0, 35.0), +]; + +/// The tolerance the window folds with (points), as Check Fold Lines' default. +const TOLERANCE: f64 = 0.1; +/// The share of the view's shorter side the folded blank fills at a zoom of 1. +const FIT: f64 = 0.45; +/// The print raster's longest side, in pixels, and the fewest pixels it gives a point. +const PRINT_SIDE: f64 = 2048.0; +/// Degrees the view turns for each point dragged, and for each arrow key press. +const DRAG_TURN: f64 = 0.5; +const KEY_TURN: f64 = 5.0; + +/// The window's settings (kept with the UI state). +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default, rename_all = "camelCase")] +pub struct Settings { + /// How far the blank is folded: 0 flat, 1 every hinge at its angle. + pub amount: f64, + /// The view's turn, in degrees (see [`VIEWS`]). + pub rotate_x: f64, + pub rotate_y: f64, + /// The zoom: 1 fits the folded blank in the view. + pub zoom: f64, + /// How far the view is moved, in points. + pub pan: [f64; 2], + /// The field of view in degrees; 0 for none. + pub perspective: f64, + /// The board's inside color: `#rrggbb` or the name of a swatch. + pub inside: String, + /// Draw the fold lines on the print. + pub show_fold_lines: bool, + /// The base panel: the one under this point (document coordinates); the largest when `None`. + pub base: Option<[f64; 2]>, +} + +impl Default for Settings { + fn default() -> Self { + let (_, _, rotate_x, rotate_y) = VIEWS[6]; + Self { + amount: 1.0, + rotate_x, + rotate_y, + zoom: 1.0, + pan: [0.0; 2], + perspective: 0.0, + inside: "#ffffff".into(), + show_fold_lines: false, + base: None, + } + } +} + +impl Settings { + /// The view preset these settings show, if any. + fn view(&self) -> Option<&'static (&'static str, &'static str, f64, f64)> { + VIEWS.iter().find(|v| (v.2 - self.rotate_x).abs() < 1e-9 && (v.3 - self.rotate_y).abs() < 1e-9) + } + + /// These settings with every value in the range `ui.foldPreview` allows: saved UI state is read + /// as it was stored. A value that is not a number takes its default. + fn clamped(mut self) -> Self { + let within = |v: f64, lo: f64, hi: f64, or: f64| if v.is_finite() { v.clamp(lo, hi) } else { or }; + let turn = |v: f64| if (-180.0..=180.0).contains(&v) { v } else { wrapped(v) }; + let fresh = Settings::default(); + self.amount = within(self.amount, 0.0, 1.0, fresh.amount); + self.zoom = within(self.zoom, 0.1, 8.0, fresh.zoom); + self.perspective = within(self.perspective, 0.0, 160.0, fresh.perspective); + (self.rotate_x, self.rotate_y) = (turn(self.rotate_x), turn(self.rotate_y)); + self.pan = self.pan.map(|v| if v.is_finite() { v } else { 0.0 }); + self.base = self.base.filter(|b| b.iter().all(|v| v.is_finite())); + self + } +} + +/// `angle` (degrees) brought into -180 to 180. +fn wrapped(angle: f64) -> f64 { + let a = (angle + 180.0).rem_euclid(360.0) - 180.0; + if a.is_finite() { a } else { 0.0 } +} + +/// What the print raster shows: the document, its revision, whether the fold lines are drawn, and +/// the region and size. +#[derive(Clone, Copy, Debug, PartialEq)] +struct PrintKey { + uid: u64, + revision: u64, + fold_lines: bool, + region: [u64; 4], + width: u32, + height: u32, +} + +/// The last frame drawn: its size in pixels and how long the fold and the drawing took (ms). +#[derive(Clone, Copy, Debug, Default)] +struct Frame { + width: u32, + height: u32, + fold_ms: f64, + draw_ms: f64, +} + +/// A document's blanks and whether its fold lines have an error, by (uid, revision). +type Blanks = ((u64, u64), Arc<Vec<Blank>>, bool); + +/// What a fold folds: the document (uid, revision), the blank, the base panel and the amount's bits. +type FoldKey = (u64, u64, usize, usize, u64); + +/// What the last image shows: the fold, the camera, the inside color and the print. +#[derive(Clone, Copy, Debug, PartialEq)] +struct DrawKey { + fold: FoldKey, + camera: Camera, + inside: [u8; 4], + print: Option<PrintKey>, +} + +#[derive(Default)] +struct Cache { + blanks: Option<Blanks>, + /// The last fold, what it folds and how long it took (ms). + folded: Option<(FoldKey, Arc<Folded>, f64)>, + /// What the texture shows. + drawn: Option<DrawKey>, + /// Folds worked out and images rendered (tests count them). + folds: u64, + renders: u64, + /// The print shown and what it shows. + print: Option<(PrintKey, Arc<Print>)>, + /// Renders the print off the UI thread (None: on this thread). + worker: Option<ThumbWorker<(), PrintKey>>, + worker_started: bool, + pending: Option<PrintKey>, + settle: Settle, + tex: Option<egui::TextureHandle>, + /// The last frame's image, for double-click picking, and the screen rect it filled. + image: Option<(Image, Rect)>, + frame: Option<Frame>, + /// Prints rendered (tests count them). + prints: u64, +} + +thread_local! { + static CACHE: crate::graphics::TexCache<Cache> = crate::graphics::TexCache::default(); + static RENDERER: std::cell::RefCell<vectorcraft_render::Renderer> = std::cell::RefCell::new(vectorcraft_render::Renderer::new()); +} + +/// The board's inside color (straight RGBA) for `inside`: `#rrggbb`, or a swatch of `d` with a +/// plain color; `None` for anything else. +fn inside_color(d: &vectorcraft_engine::doc::Document, inside: &str) -> Option<[u8; 4]> { + if inside.starts_with('#') { + return vectorcraft_color::Color::from_hex(inside).map(|c| c.to_rgba8(1.0)); + } + match &d.swatch(inside)?.paint { + vectorcraft_color::Paint::Solid { color, .. } => Some(color.to_rgba8(1.0)), + _ => None, + } +} + +/// The document rect a print of `blank` covers: its panels' bounds, with a point to spare. +fn print_region(blank: &Blank) -> Option<DRect> { + let r = blank.panels.iter().filter_map(|p| p.outline.bounds()).reduce(|a, b| a.union(b))?; + let r = r.inflate(1.0, 1.0); + (r.width() > 0.0 && r.height() > 0.0 && r.is_finite()).then_some(r) +} + +/// The pixel size of the print of `region`: its longest side [`PRINT_SIDE`]. +fn print_size(region: DRect) -> (u32, u32, f64) { + let scale = PRINT_SIDE / region.width().max(region.height()); + let side = |len: f64| ((len * scale).ceil() as u32).clamp(1, MAX_SIDE); + (side(region.width()), side(region.height()), scale) +} + +impl Cache { + /// The blanks of document `uid` at `revision`, worked out again only when it changed. + fn blanks(&mut self, uid: u64, revision: u64, d: &vectorcraft_engine::doc::Document) -> (Arc<Vec<Blank>>, bool) { + if let Some((key, blanks, errors)) = &self.blanks + && *key == (uid, revision) + { + return (blanks.clone(), *errors); + } + let (blanks, issues) = vectorcraft_engine::cmd::fold_source(d); + let errors = issues.iter().any(|i| i.code.is_error()); + let blanks = Arc::new(blanks); + self.blanks = Some(((uid, revision), blanks.clone(), errors)); + (blanks, errors) + } + + /// `blank` folded about `panel` by `amount` (what `key` names), worked out again only when the + /// key changed, and how long that took (ms). + fn fold(&mut self, key: FoldKey, blank: &Blank, panel: usize, amount: f64) -> Option<(Arc<Folded>, f64)> { + if let Some((k, f, ms)) = &self.folded + && *k == key + { + return Some((f.clone(), *ms)); + } + let t0 = crate::now_ms(); + let f = Arc::new(fold(blank, Some(panel), amount, TOLERANCE)?); + let ms = crate::now_ms() - t0; + self.folded = Some((key, f.clone(), ms)); + self.folds += 1; + Some((f, ms)) + } + + /// Bring the print up to `key`: on the worker when there is one, else here, and not before the + /// document has settled unless there is no print of it yet. + fn update_print(&mut self, ctx: &egui::Context, doc: &Arc<vectorcraft_engine::doc::Document>, key: PrintKey, region: DRect, scale: f64) { + if !self.worker_started { + self.worker_started = true; + self.worker = ThumbWorker::spawn(ctx, "fold-preview"); + } + let done = match self.worker.as_ref().map(ThumbWorker::poll) { + Some(Some(done)) => done, + Some(None) => { + (self.worker, self.pending) = (None, None); + vec![] + } + None => vec![], + }; + for d in done { + if self.pending == Some(d.key) { + self.pending = None; + } + if let Some(img) = d.img { + self.keep_print(d.key, img); + } + } + let shown = self.print.as_ref().map(|(k, _)| *k); + if shown == Some(key) || self.pending == Some(key) { + return; + } + let have = shown.is_some_and(|k| k.uid == key.uid); + if have && !self.settle.settled(ctx, key.uid, key.revision, ctx.input(|i| i.time)) { + return; + } + let opts = vectorcraft_render::RenderOptions { + skip_templates: true, + image_mips: true, + hidden: vectorcraft_engine::cmd::print_hidden(doc, key.fold_lines), + ..Default::default() + }; + if let Some(w) = &self.worker { + let (doc, opts) = (doc.clone(), opts.clone()); + if w.submit((), key, Box::new(move |r| Some(r.render_region_with(&doc, region, scale, &opts)))) { + self.pending = Some(key); + return; + } + self.worker = None; + } + let img = RENDERER.with(|r| r.borrow_mut().render_region_with(doc, region, scale, &opts)); + self.keep_print(key, img); + } + + /// The print to draw for `want`: the one shown when it is of the same document, blank region and + /// Show Fold Lines setting (an older revision while the new one renders), else none. + fn print_for(&self, want: &PrintKey) -> Option<(PrintKey, Arc<Print>)> { + let same = |k: &PrintKey| (k.uid, k.fold_lines, k.region) == (want.uid, want.fold_lines, want.region); + self.print.as_ref().filter(|(k, _)| same(k)).map(|(k, p)| (*k, p.clone())) + } + + fn keep_print(&mut self, key: PrintKey, img: vectorcraft_render::Rendered) { + let region = + DRect::new(f64::from_bits(key.region[0]), f64::from_bits(key.region[1]), f64::from_bits(key.region[2]), f64::from_bits(key.region[3])); + if let Some(print) = Print::new(region, img.width, img.height, img.pixels) { + self.print = Some((key, Arc::new(print))); + self.prints += 1; + } + } +} + +/// `ui.foldPreview {amount?, view?, rotateX?, rotateY?, zoom?, perspective?, inside?, +/// showFoldLines?, base?}`: set the window's settings, show it, and answer with them and the last +/// frame's size and times. A value of the wrong kind or out of range is an error, and nothing is +/// set. +pub(crate) fn command(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> { + let mut set = app.ui.fold_preview.clone(); + let number = |key: &str, lo: f64, hi: f64| -> Result<Option<f64>, String> { + match p.get(key) { + None | Some(Value::Null) => Ok(None), + Some(v) => match v.as_f64() { + Some(n) if (lo..=hi).contains(&n) => Ok(Some(n)), + _ => Err(format!("`{key}` must be a number from {lo} to {hi}")), + }, + } + }; + if let Some(a) = number("amount", 0.0, 1.0)? { + set.amount = a; + } + match p.get("view") { + None | Some(Value::Null) => {} + Some(v) => { + let (_, _, x, y) = v + .as_str() + .and_then(|v| VIEWS.iter().find(|view| view.1 == v)) + .ok_or_else(|| format!("`view` must be one of {}", VIEWS.iter().map(|v| v.1).collect::<Vec<_>>().join(", ")))?; + (set.rotate_x, set.rotate_y) = (*x, *y); + } + } + if let Some(x) = number("rotateX", -180.0, 180.0)? { + set.rotate_x = x; + } + if let Some(y) = number("rotateY", -180.0, 180.0)? { + set.rotate_y = y; + } + if let Some(z) = number("zoom", 0.1, 8.0)? { + set.zoom = z; + } + if let Some(v) = number("perspective", 0.0, 160.0)? { + set.perspective = v; + } + match p.get("inside") { + None | Some(Value::Null) => {} + Some(v) => { + let inside = v.as_str().unwrap_or_default(); + let known = app.session.active().and_then(|st| inside_color(&st.doc, inside)).is_some() + || (inside.starts_with('#') && vectorcraft_color::Color::from_hex(inside).is_some()); + if !known { + return Err(format!("`inside` must be #rrggbb or the name of a swatch with a plain color, not {v}")); + } + set.inside = inside.to_string(); + } + } + match p.get("showFoldLines") { + None | Some(Value::Null) => {} + Some(v) => set.show_fold_lines = v.as_bool().ok_or("`showFoldLines` must be true or false")?, + } + match p.get("base") { + None => {} + Some(Value::Null) => set.base = None, + Some(v) => { + let a = v.as_array().filter(|a| a.len() == 2); + let xy: Option<Vec<f64>> = a.map(|a| a.iter().filter_map(Value::as_f64).filter(|n| n.is_finite()).collect()); + let Some(&[x, y]) = xy.as_deref() else { return Err("`base` must be a point: [x, y], or null".into()) }; + let blanks = app.session.active().map(|st| vectorcraft_engine::cmd::fold_source(&st.doc).0).unwrap_or_default(); + if pick(&blanks, Some(Point::new(x, y))).is_none() { + return Err("`base` is in no panel".into()); + } + set.base = Some([x, y]); + } + } + if p.get("view").is_some_and(|v| !v.is_null()) || p.get("zoom").is_some_and(|v| !v.is_null()) { + set.pan = [0.0; 2]; + } + app.ui.fold_preview = set; + crate::panel_docking::reveal_panel(app, ID)?; + if let Some(ctx) = &app.ui_ctx { + ctx.request_repaint(); + } + Ok(state(app)) +} + +/// The window's settings and the last frame's size and times. +fn state(app: &VectorcraftApp) -> Value { + let frame = CACHE.with(|c| c.borrow().frame); + let mut out = serde_json::to_value(&app.ui.fold_preview).unwrap_or_default(); + if let Some(o) = out.as_object_mut() { + o.insert( + "frame".into(), + frame.map_or(Value::Null, |f| json!({"width": f.width, "height": f.height, "foldMs": f.fold_ms, "drawMs": f.draw_ms})), + ); + } + out +} + +/// The toolbar: the view presets, Perspective, Inside, Show Fold Lines and Reset. +fn toolbar(app: &VectorcraftApp, ui: &mut Ui, set: &mut Settings) { + ui.horizontal_wrapped(|ui| { + let labels: Vec<&str> = VIEWS.iter().map(|v| v.0).collect(); + let current = set.view().map_or("", |v| v.0); + if let Some(i) = widgets::dropdown_named(ui, "fold-preview-view", Some(tl!("View")), current, &labels, 120.0) + && let Some(&(_, _, x, y)) = VIEWS.get(i) + { + (set.rotate_x, set.rotate_y, set.pan) = (x, y, [0.0; 2]); + } + let swatches: Vec<String> = app.session.active().map_or_else(Vec::new, |st| { + st.doc.swatches.iter().filter(|s| matches!(s.paint, vectorcraft_color::Paint::Solid { .. })).map(|s| s.name.clone()).collect() + }); + let mut names: Vec<&str> = vec![tl!("White")]; + names.extend(swatches.iter().map(String::as_str)); + let shown = if set.inside == "#ffffff" { tl!("White") } else { set.inside.as_str() }; + ui.label(tl!("Inside")); + if let Some(i) = widgets::dropdown_names_named(ui, "fold-preview-inside", Some(tl!("Inside")), shown, &names, 110.0) { + set.inside = swatches.get(i.wrapping_sub(1)).cloned().unwrap_or_else(|| "#ffffff".into()); + } + if widgets::check(ui, tl!("Show Fold Lines"), set.show_fold_lines, true) { + set.show_fold_lines = !set.show_fold_lines; + } + if widgets::flat_button_fit(ui, tl!("Reset"), 48.0).clicked() { + let fresh = Settings::default(); + (set.rotate_x, set.rotate_y, set.zoom, set.pan, set.perspective) = (fresh.rotate_x, fresh.rotate_y, 1.0, [0.0; 2], 0.0); + } + }); + ui.horizontal(|ui| { + ui.label(tl!("Perspective")); + widgets::slider(ui, egui::Slider::new(&mut set.perspective, 0.0..=160.0).suffix("°").fixed_decimals(0)); + }); +} + +/// The Fold and Zoom sliders. +fn sliders(ui: &mut Ui, set: &mut Settings) { + ui.horizontal(|ui| { + ui.label(tl!("Fold")); + let mut percent = set.amount * 100.0; + if widgets::slider(ui, egui::Slider::new(&mut percent, 0.0..=100.0).suffix("%").fixed_decimals(0)).changed() { + set.amount = (percent / 100.0).clamp(0.0, 1.0); + } + }); + ui.horizontal(|ui| { + ui.label(tl!("Zoom")); + let mut percent = set.zoom * 100.0; + if widgets::slider(ui, egui::Slider::new(&mut percent, 10.0..=800.0).suffix("%").fixed_decimals(0).logarithmic(true)).changed() { + set.zoom = (percent / 100.0).clamp(0.1, 8.0); + } + }); +} + +/// Turns, moves and zooms the view with the pointer, the wheel and the arrow keys, and picks the +/// base panel of `blank` (the blank `key` folds) on a double-click. +fn interact(ui: &Ui, response: &egui::Response, set: &mut Settings, blank: Option<(&Blank, FoldKey)>) { + if response.clicked() || response.drag_started() { + response.request_focus(); + } + let (shift, space) = ui.input(|i| (i.modifiers.shift, i.key_down(egui::Key::Space))); + let delta = response.drag_delta(); + if delta != egui::Vec2::ZERO { + if response.dragged_by(egui::PointerButton::Middle) || (space && response.dragged_by(egui::PointerButton::Primary)) { + set.pan[0] += f64::from(delta.x); + set.pan[1] += f64::from(delta.y); + } else if response.dragged_by(egui::PointerButton::Primary) { + let (mut dx, mut dy) = (f64::from(delta.x), f64::from(delta.y)); + if shift { + if dx.abs() >= dy.abs() { + dy = 0.0; + } else { + dx = 0.0; + } + } + set.rotate_y = wrapped(set.rotate_y + dx * DRAG_TURN); + set.rotate_x = wrapped(set.rotate_x + dy * DRAG_TURN); + } + } + if response.hovered() { + let scroll = f64::from(ui.input(|i| i.smooth_scroll_delta.y + (i.zoom_delta() - 1.0) * 200.0)); + if scroll != 0.0 { + set.zoom = (set.zoom * (scroll * 0.002).exp()).clamp(0.1, 8.0); + } + } + if response.has_focus() { + // The view keeps the arrow keys, so they turn it rather than move the focus on. + ui.memory_mut(|m| { + m.set_focus_lock_filter(response.id, egui::EventFilter { horizontal_arrows: true, vertical_arrows: true, ..Default::default() }) + }); + let presses = |key| ui.input_mut(|i| i.count_and_consume_key(egui::Modifiers::NONE, key)) as f64 * KEY_TURN; + let (left, right, up, down) = + (presses(egui::Key::ArrowLeft), presses(egui::Key::ArrowRight), presses(egui::Key::ArrowUp), presses(egui::Key::ArrowDown)); + if left + right + up + down > 0.0 { + set.rotate_y = wrapped(set.rotate_y + right - left); + set.rotate_x = wrapped(set.rotate_x + down - up); + } + } + if response.double_clicked() + && let Some(pos) = response.interact_pointer_pos() + && let Some((blank, key)) = blank + { + // The image on screen is the last one drawn; its panel numbers are used only while it shows + // the same blank of the same document revision. + let picked = CACHE.with(|c| { + let c = c.borrow(); + let shown = c.drawn.map(|d| (d.fold.0, d.fold.1, d.fold.2)); + if shown != Some((key.0, key.1, key.2)) { + return None; + } + let (img, rect) = c.image.as_ref()?; + let x = (pos.x - rect.left()) / rect.width() * img.width as f32; + let y = (pos.y - rect.top()) / rect.height() * img.height as f32; + img.panel_at(x.max(0.0) as u32, y.max(0.0) as u32) + }); + if let Some(p) = picked.and_then(|i| blank.panels.get(i)).and_then(|p| p.point_inside()) { + set.base = Some([p.x, p.y]); + } + } +} + +/// The status line under the view, in English (shown translated). +fn status(blanks: usize, folded: Option<(&Blank, &Folded)>, errors: bool) -> Vec<String> { + let Some((blank, f)) = folded else { + return vec!["Check the fold lines first.".into()]; + }; + let mut out = vec![crate::i18n::fmt( + "Panels: {panels}, hinges: {hinges}", + &[("panels", &blank.panels.len().to_string()), ("hinges", &blank.hinges.len().to_string())], + )]; + if errors { + out.push("Check the fold lines first.".into()); + } + if blanks > 1 { + out.push(crate::i18n::fmt("Other blanks not shown: {count}", &[("count", &(blanks - 1).to_string())])); + } + if let Some(gap) = f.hinges.iter().filter(|h| !h.closes).map(|h| h.gap).reduce(f64::max) { + out.push(crate::i18n::fmt("A joint does not close by {gap} pt.", &[("gap", &format!("{gap:.1}"))])); + } + if !f.collisions.is_empty() { + out.push("Two panels pass through each other.".into()); + } + out +} + +pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { + let Some(st) = app.session.active() else { + crate::panels::empty_state(ui, "box", tl!("No document"), tl!("Open a document to preview its folded shape.")); + return; + }; + let (uid, revision, doc) = (st.uid, st.revision, st.doc.clone()); + let mut set = app.ui.fold_preview.clone().clamped(); + toolbar(app, ui, &mut set); + let (blanks, errors) = CACHE.with(|c| c.borrow_mut().blanks(uid, revision, &doc)); + let base_point = set.base.map(|[x, y]| Point::new(x, y)); + let picked = pick(&blanks, base_point).or_else(|| pick(&blanks, None)); + let folded = picked.and_then(|(b, panel)| { + let blank = blanks.get(b)?; + let key = (uid, revision, b, panel, set.amount.to_bits()); + let (f, ms) = CACHE.with(|c| c.borrow_mut().fold(key, blank, panel, set.amount))?; + Some((blank, f, key, ms)) + }); + + let bottom = ui.spacing().interact_size.y * 3.0 + 12.0; + let size = vec2(ui.available_width().max(64.0), (ui.available_height() - bottom).max(64.0)); + let (rect, response) = ui.allocate_exact_size(size, Sense::click_and_drag()); + let view_name = set.view().map_or("", |v| v.0); + response.widget_info(|| { + let mut info = egui::WidgetInfo::labeled(egui::Role::Image, true, tl!("Fold Preview")); + info.current_text_value = Some(crate::i18n::t(view_name).to_string()); + info + }); + interact(ui, &response, &mut set, folded.as_ref().map(|(b, _, key, _)| (*b, *key))); + let t = crate::theme::Tokens::get(ui.ctx()); + ui.painter().rect_filled(rect, 2.0, t.pasteboard); + if let Some((blank, f, key, fold_ms)) = &folded { + draw(ui, rect, &doc, *key, blank, f, &set, *fold_ms); + } + if response.has_focus() { + ui.painter().rect_stroke(rect, 2.0, egui::Stroke::new(1.0, t.accent), egui::StrokeKind::Inside); + } + for line in status(blanks.len(), folded.as_ref().map(|(b, f, ..)| (*b, &**f)), errors) { + dim_label(ui, &crate::i18n::msg(&line)); + } + sliders(ui, &mut set); + if set != app.ui.fold_preview { + app.ui.fold_preview = set; + } +} + +/// Draws `blank` folded as `f` (the fold `key` names) into `rect`, with the print of `doc`. The image +/// is rendered again only when the fold, the view, the inside color or the print changed. +#[allow(clippy::too_many_arguments)] +fn draw(ui: &Ui, rect: Rect, doc: &Arc<vectorcraft_engine::doc::Document>, key: FoldKey, blank: &Blank, f: &Folded, set: &Settings, fold_ms: f64) { + // Pixels per point of the view, lowered when the window has more pixels than the view may have + // in all or along either side, so the image keeps the window's proportions. + let (w, h) = (f64::from(rect.width()), f64::from(rect.height())); + let mut ppp = f64::from(ui.ctx().pixels_per_point()); + let area = w * h * ppp * ppp; + if area > f64::from(MAX_PIXELS) { + ppp *= (f64::from(MAX_PIXELS) / area).sqrt(); + } + ppp = ppp.min(f64::from(MAX_SIDE) / w.max(h).max(1.0)); + let width = ((w * ppp).floor() as u32).clamp(1, MAX_SIDE); + let height = ((h * ppp).floor() as u32).clamp(1, MAX_SIDE); + let Some((lo, hi)) = raster::bounds(blank, f) else { return }; + let center = [(lo[0] + hi[0]) / 2.0, (lo[1] + hi[1]) / 2.0, (lo[2] + hi[2]) / 2.0]; + let radius = ((hi[0] - lo[0]).powi(2) + (hi[1] - lo[1]).powi(2) + (hi[2] - lo[2]).powi(2)).sqrt() / 2.0; + let mut fit = FIT * f64::from(width.min(height)) / radius.max(1e-6); + if set.perspective > 0.0 { + // The eye at two radii from the middle or farther, so at a zoom of 1 the whole blank is in + // front of it. + let focal = f64::from(width.min(height)) / 2.0 / (set.perspective.to_radians() / 2.0).tan(); + fit = fit.min(focal / (2.0 * radius.max(1e-6))); + } + let camera = Camera { + width, + height, + rotate_x: set.rotate_x, + rotate_y: set.rotate_y, + scale: fit * set.zoom, + pan: [set.pan[0] * ppp, set.pan[1] * ppp], + perspective: set.perspective, + center, + }; + let inside = inside_color(doc, &set.inside).unwrap_or([255; 4]); + // While the print of a new revision renders, the last one of the same blank and setting is + // drawn; a print of another document, blank or Show Fold Lines setting is not. + let print = CACHE.with(|c| { + let mut c = c.borrow_mut(); + let region = print_region(blank)?; + let (pw, ph, scale) = print_size(region); + let pkey = PrintKey { + uid: key.0, + revision: key.1, + fold_lines: set.show_fold_lines, + region: [region.x0.to_bits(), region.y0.to_bits(), region.x1.to_bits(), region.y1.to_bits()], + width: pw, + height: ph, + }; + c.update_print(ui.ctx(), doc, pkey, region, scale); + c.print_for(&pkey) + }); + let draw_key = DrawKey { fold: key, camera, inside, print: print.as_ref().map(|(k, _)| *k) }; + let kept = CACHE.with(|c| { + let mut c = c.borrow_mut(); + let Some(tex) = c.tex.as_ref().filter(|_| c.drawn == Some(draw_key)).map(|t| t.id()) else { return false }; + ui.painter().image(tex, rect, Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)), Color32::WHITE); + if let Some((_, at)) = &mut c.image { + *at = rect; + } + true + }); + if kept { + return; + } + let t0 = crate::now_ms(); + let scene = raster::Scene { blank, folded: f, print: print.as_ref().map(|(_, p)| &**p), inside, outside: [255; 4], camera }; + let Some(img) = raster::render(&scene) else { return }; + let draw_ms = crate::now_ms() - t0; + let color = egui::ColorImage::from_rgba_premultiplied([img.width as usize, img.height as usize], &img.pixels); + CACHE.with(|c| { + let mut c = c.borrow_mut(); + c.drawn = Some(draw_key); + c.renders += 1; + match &mut c.tex { + Some(tex) => tex.set(color, egui::TextureOptions::LINEAR), + None => c.tex = Some(ui.ctx().load_texture("fold-preview", color, egui::TextureOptions::LINEAR)), + } + if let Some(tex) = &c.tex { + let uv = Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)); + ui.painter().image(tex.id(), rect, uv, Color32::WHITE); + } + c.frame = Some(Frame { width: img.width, height: img.height, fold_ms, draw_ms }); + c.image = Some((img, rect)); + }); +} + +#[cfg(test)] +pub(crate) fn prints_rendered() -> u64 { + CACHE.with(|c| c.borrow().prints) +} + +#[cfg(test)] +pub(crate) fn last_image() -> Option<Image> { + CACHE.with(|c| c.borrow().image.as_ref().map(|(i, _)| i.clone())) +} + +/// The folds worked out and the images rendered so far. +#[cfg(test)] +pub(crate) fn work_done() -> (u64, u64) { + CACHE.with(|c| (c.borrow().folds, c.borrow().renders)) +} + +/// The screen rect the last image filled. +#[cfg(test)] +pub(crate) fn last_rect() -> Option<Rect> { + CACHE.with(|c| c.borrow().image.as_ref().map(|(_, r)| *r)) +} + +#[cfg(test)] +mod tests; diff --git a/crates/ui-egui/src/addons/packaging/preview/tests.rs b/crates/ui-egui/src/addons/packaging/preview/tests.rs new file mode 100644 index 0000000000..9fdfb1972e --- /dev/null +++ b/crates/ui-egui/src/addons/packaging/preview/tests.rs @@ -0,0 +1,489 @@ +use serde_json::{Value, json}; +use vectorcraft_engine::Session; + +use std::sync::Arc; + +use egui::{Event, Modifiers, PointerButton, Pos2, vec2}; + +use super::{Cache, ID, PrintKey, Settings, last_image, last_rect, prints_rendered, show, status, work_done}; +use crate::{VectorcraftApp, menus}; + +/// An app with a tray blank (a 100 pt base at x 140 to 240, y 140 to 240, and a 40 pt wall on each +/// side) and a red square printed on the base, nothing selected → (app, the red square's id). +fn app() -> (VectorcraftApp, u64) { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + let path = |app: &mut VectorcraftApp, d: &str| app.run("path.create", json!({ "d": d })).unwrap()["id"].as_u64().unwrap(); + let outline = path(&mut app, "M140 100 L240 100 L240 140 L280 140 L280 240 L240 240 L240 280 L140 280 L140 240 L100 240 L100 140 L140 140 Z"); + let creases = [ + path(&mut app, "M140 140 L240 140"), + path(&mut app, "M240 140 L240 240"), + path(&mut app, "M240 240 L140 240"), + path(&mut app, "M140 240 L140 140"), + ]; + app.run("addon.packaging.setRole", json!({ "role": "cut", "ids": [outline] })).unwrap(); + app.run("addon.packaging.setRole", json!({ "role": "crease", "ids": creases })).unwrap(); + let red = app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 180, "height": 180})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({ "ids": [red] })).unwrap(); + app.run("paint.setFill", json!({ "color": "#ff0000" })).unwrap(); + app.run("paint.setStroke", json!({ "none": true })).unwrap(); + app.run("object.arrange.sendToBack", json!({})).unwrap(); + app.run("select.none", json!({})).unwrap(); + (app, red) +} + +/// Draws the window in a 520 × 440 frame, twice (egui lays out on the first). +fn frame(app: &mut VectorcraftApp) { + frame_at(app, 1.0); +} + +/// [`frame`] at `zoom` pixels per point. +fn frame_at(app: &mut VectorcraftApp, zoom: f32) { + crate::i18n::set_current(crate::i18n::Lang::EN); + let ctx = egui::Context::default(); + ctx.set_pixels_per_point(zoom); + crate::theme::install_fonts(&ctx); + for time in [0.0, 1.0] { + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(520.0, 440.0)); + let input = egui::RawInput { time: Some(time), screen_rect: Some(screen), ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| show(app, ui)); + out.textures_delta.clear(); + } +} + +fn color_at(img: &vectorcraft_three_d::fold::raster::Image, x: u32, y: u32) -> [u8; 4] { + let i = (y * img.width + x) as usize * 4; + [img.pixels[i], img.pixels[i + 1], img.pixels[i + 2], img.pixels[i + 3]] +} + +/// The color at the middle of the window's last image. +fn middle(img: &vectorcraft_three_d::fold::raster::Image) -> [u8; 4] { + color_at(img, img.width / 2, img.height / 2) +} + +#[test] +fn the_menu_item_and_the_panel_button_show_the_window_and_a_second_run_keeps_it() { + let (mut app, _) = app(); + let entries = menus::menu_entries(&app); + let item = entries.iter().find(|e| e.path == ["Object", "Plug-ins", "Packaging Tools"] && e.label == "Fold Preview").expect("listed"); + assert_eq!((item.command.as_deref(), &item.params), (Some("ui.foldPreview"), &json!({}))); + assert!(!crate::panel_docking::showing(&app.ui, ID)); + menus::invoke(&mut app, "ui.foldPreview", json!({})); + assert!(crate::panel_docking::visible(&app.ui, ID), "the window opens"); + menus::invoke(&mut app, "ui.foldPreview", json!({})); + assert!(crate::panel_docking::visible(&app.ui, ID), "a second run leaves it open"); + let text = crate::tests_labels::painted_text(&mut app, super::super::show); + assert!(text.contains("Fold Preview"), "the Fold Lines panel has the button: {text}"); +} + +#[test] +fn ui_fold_preview_sets_the_window_and_refuses_bad_values() { + let (mut app, _) = app(); + let r = app + .run( + "ui.foldPreview", + json!({"amount": 0.5, "view": "top", "zoom": 2, "perspective": 40, "inside": "#00ff00", "showFoldLines": true, "base": [120, 190]}), + ) + .unwrap(); + let want = Settings { + amount: 0.5, + rotate_x: 90.0, + rotate_y: 0.0, + zoom: 2.0, + pan: [0.0; 2], + perspective: 40.0, + inside: "#00ff00".into(), + show_fold_lines: true, + base: Some([120.0, 190.0]), + }; + assert_eq!(app.ui.fold_preview, want); + assert_eq!(r["rotateX"], 90.0, "{r}"); + assert!(r.get("frame").is_some(), "{r}"); + app.run("ui.foldPreview", json!({"rotateX": -30, "rotateY": 170, "base": null})).unwrap(); + assert_eq!((app.ui.fold_preview.rotate_x, app.ui.fold_preview.rotate_y, app.ui.fold_preview.base), (-30.0, 170.0, None)); + let kept = app.ui.fold_preview.clone(); + for (p, want) in [ + (json!({"amount": 2}), "`amount` must be a number from 0 to 1"), + (json!({"amount": "half"}), "`amount` must be a number from 0 to 1"), + (json!({"view": "sideways"}), "`view` must be one of"), + (json!({"rotateX": 200}), "`rotateX` must be a number from -180 to 180"), + (json!({"zoom": 0}), "`zoom` must be a number from 0.1 to 8"), + (json!({"perspective": 170}), "`perspective` must be a number from 0 to 160"), + (json!({"inside": "no such swatch"}), "`inside` must be #rrggbb"), + (json!({"inside": 7}), "`inside` must be #rrggbb"), + (json!({"showFoldLines": "yes"}), "`showFoldLines` must be true or false"), + (json!({"base": [1, "2"]}), "`base` must be a point"), + (json!({"base": [5, 5]}), "`base` is in no panel"), + (json!({"amount": 0.2, "zoom": 99}), "`zoom` must be a number"), + ] { + let e = app.run("ui.foldPreview", p.clone()).unwrap_err().to_string(); + assert!(e.contains(want), "{p}: {e}"); + assert_eq!(app.ui.fold_preview, kept, "{p} sets nothing"); + } + // A swatch with a plain color names the inside. + app.run("ui.foldPreview", json!({"inside": "White"})).unwrap(); + assert_eq!(app.ui.fold_preview.inside, "White"); +} + +#[test] +fn the_window_draws_the_print_on_the_folded_panels_and_the_inside_on_their_backs() { + let (mut app, _) = app(); + // Flat, from the front: the base's print, red, fills the middle. + app.run("ui.foldPreview", json!({"amount": 0, "view": "front"})).unwrap(); + let before = prints_rendered(); + frame(&mut app); + assert!(prints_rendered() > before, "the print is rendered on this thread without a worker"); + let img = last_image().expect("a frame"); + let [r, g, b, a] = middle(&img); + assert!(r > 150 && g < 40 && b < 40 && a == 255, "red print: {:?}", [r, g, b, a]); + let state = app.run("ui.foldPreview", json!({})).unwrap(); + assert_eq!((state["frame"]["width"].as_u64(), state["frame"]["height"].as_u64()), (Some(u64::from(img.width)), Some(u64::from(img.height)))); + // From the back, the base's inside shows in the inside color. + app.run("ui.foldPreview", json!({"view": "back", "inside": "#00ff00"})).unwrap(); + frame(&mut app); + let [r, g, b, _] = middle(&last_image().expect("a frame")); + assert!(r < 40 && g > 150 && b < 40, "green inside: {:?}", [r, g, b]); + // Folded and seen from the front, the walls stand edge on: the base fills the same place. + app.run("ui.foldPreview", json!({"amount": 1, "view": "front"})).unwrap(); + frame(&mut app); + let img = last_image().expect("a frame"); + let [r, ..] = middle(&img); + assert!(r > 150, "the base still shows its print: {:?}", middle(&img)); + // The same print is not rendered again while the document does not change. + let prints = prints_rendered(); + frame(&mut app); + assert_eq!(prints_rendered(), prints); +} + +#[test] +fn a_wide_perspective_still_fits_the_whole_folded_blank_in_the_view() { + let (mut app, _) = app(); + // Without perspective, the base and the two walls behind it that face the viewer show. + let mut flat = None; + for perspective in [0, 60, 160] { + app.run("ui.foldPreview", json!({"amount": 1, "view": "threeQuarter", "zoom": 1, "perspective": perspective})).unwrap(); + frame(&mut app); + let img = last_image().expect("a frame"); + let mut shown: Vec<usize> = + (0..img.height).flat_map(|y| (0..img.width).map(move |x| (x, y))).filter_map(|(x, y)| img.panel_at(x, y)).collect(); + shown.sort_unstable(); + shown.dedup(); + let flat = flat.get_or_insert_with(|| shown.clone()); + assert_eq!(flat.len(), 3); + assert_eq!(&shown, flat, "{perspective}°: the same panels show"); + let edge = (0..img.width).flat_map(|x| [(x, 0), (x, img.height - 1)]).chain((0..img.height).flat_map(|y| [(0, y), (img.width - 1, y)])); + assert!(edge.into_iter().all(|(x, y)| img.panel_at(x, y).is_none()), "{perspective}°: nothing reaches the edge of the view"); + } +} + +#[test] +fn a_window_with_more_pixels_than_the_view_may_have_is_drawn_smaller() { + let (mut app, _) = app(); + app.run("ui.foldPreview", json!({"amount": 0, "view": "front"})).unwrap(); + frame_at(&mut app, 8.0); + let img = last_image().expect("a frame"); + assert!(u64::from(img.width) * u64::from(img.height) <= u64::from(vectorcraft_three_d::fold::raster::MAX_PIXELS), "{}×{}", img.width, img.height); + assert!(img.width > 1000, "still sharper than one pixel a point: {}", img.width); + let [r, ..] = middle(&img); + assert!(r > 150, "the base's print shows: {:?}", middle(&img)); +} + +#[test] +fn the_print_leaves_out_the_fold_lines_unless_they_are_shown() { + let (mut app, red) = app(); + // Without the red square, the base's middle shows the board with no art; with a crease drawn + // across the middle and the fold lines shown, the crease's color shows there. + app.run("select.set", json!({ "ids": [red] })).unwrap(); + app.run("edit.clear", json!({})).unwrap(); + let mid = app.run("path.create", json!({ "d": "M140 190 L240 190" })).unwrap()["id"].as_u64().unwrap(); + app.run("addon.packaging.setRole", json!({ "role": "crease", "ids": [mid] })).unwrap(); + app.run("select.set", json!({ "ids": [mid] })).unwrap(); + app.run("stroke.set", json!({ "weight": 20 })).unwrap(); + app.run("select.none", json!({})).unwrap(); + app.run("ui.foldPreview", json!({"amount": 0, "view": "front", "zoom": 1})).unwrap(); + frame(&mut app); + let plain = middle(&last_image().expect("a frame")); + app.run("ui.foldPreview", json!({"showFoldLines": true})).unwrap(); + frame(&mut app); + let lined = middle(&last_image().expect("a frame")); + assert_ne!(plain, lined, "the crease shows only with Show Fold Lines on"); + assert!(plain[0] > 200 && plain[1] > 200 && plain[2] > 200, "the board is white where the print has no art: {plain:?}"); +} + +#[test] +fn the_window_says_when_there_is_nothing_to_fold() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + let text = crate::tests_labels::painted_text(&mut app, show); + assert!(text.contains("Check the fold lines first."), "{text}"); + let mut none = VectorcraftApp::new(Session::new(), Default::default()); + let text = crate::tests_labels::painted_text(&mut none, show); + assert!(text.contains("Open a document to preview its folded shape."), "{text}"); +} + +#[test] +fn the_settings_are_kept_with_the_ui_state() { + let (mut app, _) = app(); + app.run("ui.foldPreview", json!({"amount": 0.25, "view": "left"})).unwrap(); + let saved: Value = serde_json::to_value(&app.ui).unwrap(); + assert_eq!(saved["fold_preview"]["amount"], 0.25, "{}", saved["fold_preview"]); + let back: crate::state::UiState = serde_json::from_value(saved).unwrap(); + assert_eq!(back.fold_preview, app.ui.fold_preview); +} + +#[test] +fn saved_settings_out_of_range_are_brought_into_range() { + let (mut app, _) = app(); + app.ui.fold_preview = Settings { + amount: 3.0, + rotate_x: 200.0, + rotate_y: 180.0, + zoom: 0.0, + pan: [f64::NAN, 4.0], + perspective: -5.0, + base: Some([f64::INFINITY, 0.0]), + ..Settings::default() + }; + frame(&mut app); + let set = &app.ui.fold_preview; + assert_eq!( + (set.amount, set.rotate_x, set.rotate_y, set.zoom, set.pan, set.perspective, set.base), + (1.0, -160.0, 180.0, 0.1, [0.0, 4.0], 0.0, None) + ); + let text = crate::tests_labels::painted_text(&mut app, show); + assert!(!text.contains("Check the fold lines first."), "the blank folds: {text}"); + assert!(last_image().is_some(), "and is drawn"); +} + +/// A window kept open over frames, as the app draws it. +struct View { + ctx: egui::Context, + time: f64, +} + +impl View { + fn new(app: &mut VectorcraftApp) -> Self { + crate::i18n::set_current(crate::i18n::Lang::EN); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut v = View { ctx, time: 0.0 }; + v.idle(app); + v + } + + fn step(&mut self, app: &mut VectorcraftApp, events: Vec<Event>, modifiers: Modifiers) { + self.time += 0.05; + let screen = egui::Rect::from_min_size(Pos2::ZERO, vec2(520.0, 440.0)); + let events = std::iter::once(Event::ModifiersChanged(modifiers)).chain(events).collect(); + let input = egui::RawInput { time: Some(self.time), screen_rect: Some(screen), events, ..Default::default() }; + let mut out = self.ctx.run_ui(input, |ui| show(app, ui)); + out.textures_delta.clear(); + } + + fn idle(&mut self, app: &mut VectorcraftApp) { + for _ in 0..3 { + self.step(app, vec![], Modifiers::NONE); + } + } + + /// Presses `button` at `at`, drags by `by` in four steps and lets go, holding `modifiers`. + fn drag(&mut self, app: &mut VectorcraftApp, at: Pos2, by: egui::Vec2, button: PointerButton, modifiers: Modifiers) { + let press = |pos, pressed| Event::PointerButton { pos, button, pressed, modifiers }; + self.step(app, vec![Event::PointerMoved(at)], modifiers); + self.step(app, vec![press(at, true)], modifiers); + for k in 1..=4 { + self.step(app, vec![Event::PointerMoved(at + by * (k as f32 / 4.0))], modifiers); + } + self.step(app, vec![press(at + by, false)], modifiers); + self.idle(app); + } + + fn click(&mut self, app: &mut VectorcraftApp, at: Pos2) { + let press = |pressed| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }; + self.step(app, vec![Event::PointerMoved(at)], Modifiers::NONE); + self.step(app, vec![press(true)], Modifiers::NONE); + self.step(app, vec![press(false)], Modifiers::NONE); + } + + fn key(&mut self, app: &mut VectorcraftApp, key: egui::Key) { + let press = Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }; + self.step(app, vec![press], Modifiers::NONE); + self.step(app, vec![], Modifiers::NONE); + } +} + +/// The app showing the tray flat from the front, in a [`View`], and the middle of the view. +fn front_view() -> (VectorcraftApp, View, Pos2) { + let (mut app, _) = app(); + app.run("ui.foldPreview", json!({"amount": 0, "view": "front"})).unwrap(); + let view = View::new(&mut app); + let at = last_rect().expect("the view is drawn").center(); + (app, view, at) +} + +#[test] +fn a_drag_turns_the_view_and_a_shift_drag_keeps_to_one_axis() { + let (mut app, mut view, at) = front_view(); + view.drag(&mut app, at, vec2(40.0, 20.0), PointerButton::Primary, Modifiers::NONE); + let set = app.ui.fold_preview.clone(); + assert!(set.rotate_y > 5.0 && set.rotate_y <= 20.0 + 1e-9, "{set:?}"); + assert!(set.rotate_x > 2.0 && set.rotate_x <= 10.0 + 1e-9, "{set:?}"); + app.run("ui.foldPreview", json!({"view": "front"})).unwrap(); + view.drag(&mut app, at, vec2(40.0, 20.0), PointerButton::Primary, Modifiers::SHIFT); + let set = app.ui.fold_preview.clone(); + assert!(set.rotate_y > 5.0 && set.rotate_x == 0.0, "only the larger move turns the view: {set:?}"); +} + +#[test] +fn a_middle_drag_moves_the_view_and_the_wheel_zooms_it() { + let (mut app, mut view, at) = front_view(); + view.drag(&mut app, at, vec2(30.0, -10.0), PointerButton::Middle, Modifiers::NONE); + let set = app.ui.fold_preview.clone(); + assert!(set.pan[0] > 0.0 && set.pan[1] < 0.0, "{set:?}"); + assert_eq!((set.rotate_x, set.rotate_y), (0.0, 0.0), "the view does not turn"); + let wheel = Event::MouseWheel { + unit: egui::MouseWheelUnit::Point, + delta: vec2(0.0, 60.0), + phase: egui::TouchPhase::Move, + modifiers: Modifiers::NONE, + source: egui::MouseWheelSource::Unknown, + }; + view.step(&mut app, vec![Event::PointerMoved(at), wheel], Modifiers::NONE); + for _ in 0..20 { + view.step(&mut app, vec![], Modifiers::NONE); + } + assert!(app.ui.fold_preview.zoom > 1.05, "{:?}", app.ui.fold_preview); +} + +#[test] +fn the_arrow_keys_turn_the_focused_view_and_keep_the_focus() { + let (mut app, mut view, at) = front_view(); + view.click(&mut app, at); + view.idle(&mut app); + // Up first: the toolbar is above the view, where the focus would go if the view let it. + view.key(&mut app, egui::Key::ArrowUp); + view.key(&mut app, egui::Key::ArrowRight); + view.key(&mut app, egui::Key::ArrowRight); + let set = &app.ui.fold_preview; + assert_eq!((set.rotate_x, set.rotate_y), (-5.0, 10.0), "every press turns the view by 5°"); + // A focused view seen from the back stays there until a key turns it. + app.run("ui.foldPreview", json!({"view": "back"})).unwrap(); + view.idle(&mut app); + assert_eq!(app.ui.fold_preview.rotate_y, 180.0); +} + +#[test] +fn a_double_click_on_a_panel_makes_it_the_base() { + let (mut app, mut view, at) = front_view(); + // The left wall is the base; the middle of the view shows the tray's base panel. + app.run("ui.foldPreview", json!({"base": [120, 190]})).unwrap(); + view.idle(&mut app); + view.click(&mut app, at); + view.click(&mut app, at); + let [x, y] = app.ui.fold_preview.base.expect("a base"); + assert!((140.0..240.0).contains(&x) && (140.0..240.0).contains(&y), "the base panel is picked: {x}, {y}"); +} + +#[test] +fn a_double_click_as_the_document_changes_picks_nothing_from_the_old_image() { + let (mut app, mut view, at) = front_view(); + app.run("ui.foldPreview", json!({"base": [120, 190]})).unwrap(); + view.idle(&mut app); + view.click(&mut app, at); + let press = |pressed| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }; + view.step(&mut app, vec![press(true)], Modifiers::NONE); + // The document changes between the image on screen and the release that ends the double-click. + app.run("shape.rectangle", json!({"x": 350, "y": 350, "width": 10, "height": 10})).unwrap(); + view.step(&mut app, vec![press(false)], Modifiers::NONE); + assert_eq!(app.ui.fold_preview.base, Some([120.0, 190.0]), "the base is kept"); +} + +#[test] +fn the_view_is_folded_and_drawn_again_only_when_something_changes() { + let (mut app, mut view, _) = front_view(); + let (folds, renders) = work_done(); + view.idle(&mut app); + assert_eq!(work_done(), (folds, renders), "nothing changed: no fold and no render"); + app.run("ui.foldPreview", json!({"rotateY": 10})).unwrap(); + view.idle(&mut app); + assert_eq!(work_done(), (folds, renders + 1), "a turn renders once and does not fold again"); + app.run("ui.foldPreview", json!({"amount": 0.5})).unwrap(); + view.idle(&mut app); + assert_eq!(work_done(), (folds + 1, renders + 2), "a new amount folds and renders once"); +} + +#[test] +fn a_short_wide_window_keeps_its_proportions() { + let (mut app, _) = app(); + app.run("ui.foldPreview", json!({"amount": 0, "view": "front"})).unwrap(); + crate::i18n::set_current(crate::i18n::Lang::EN); + let ctx = egui::Context::default(); + ctx.set_pixels_per_point(2.0); + crate::theme::install_fonts(&ctx); + for time in [0.0, 1.0] { + let screen = egui::Rect::from_min_size(Pos2::ZERO, vec2(2200.0, 260.0)); + let input = egui::RawInput { time: Some(time), screen_rect: Some(screen), ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| show(&mut app, ui)); + out.textures_delta.clear(); + } + let (img, rect) = (last_image().expect("a frame"), last_rect().expect("a rect")); + let (image, window) = (f64::from(img.width) / f64::from(img.height), f64::from(rect.width() / rect.height())); + assert!(img.width <= vectorcraft_three_d::fold::raster::MAX_SIDE, "{}", img.width); + assert!((image - window).abs() / window < 0.02, "image {image}, window {window}"); +} + +#[test] +fn a_print_of_another_blank_or_setting_is_not_drawn_while_the_new_one_renders() { + let key = PrintKey { uid: 1, revision: 5, fold_lines: false, region: [0, 0, 10, 10], width: 1, height: 1 }; + let region = vectorcraft_geom::Rect::new(0.0, 0.0, 10.0, 10.0); + let print = vectorcraft_three_d::fold::raster::Print::new(region, 1, 1, vec![255; 4]).expect("a print"); + let cache = Cache { print: Some((key, Arc::new(print))), ..Default::default() }; + assert!(cache.print_for(&PrintKey { revision: 6, ..key }).is_some(), "a newer revision of the same blank keeps the last print"); + for other in [PrintKey { uid: 2, ..key }, PrintKey { fold_lines: true, ..key }, PrintKey { region: [0, 0, 20, 10], ..key }] { + assert!(cache.print_for(&other).is_none(), "{other:?}"); + } +} + +#[test] +fn the_status_line_reports_open_joints_crossing_panels_and_other_blanks() { + use vectorcraft_three_d::fold::{Blank, Folded, FoldedHinge}; + let hinge = |tree, closes, gap| FoldedHinge { a: 0, b: 1, angle: 90.0, tree, closes, gap }; + let f = Folded { + base: 0, + panels: vec![], + order: vec![], + hinges: vec![hinge(true, true, 0.0), hinge(false, false, 12.34), hinge(false, false, 3.0), hinge(false, true, 0.05)], + collisions: vec![(0, 1)], + }; + let lines = status(3, Some((&Blank::default(), &f)), true); + assert_eq!( + lines, + [ + "Panels: 0, hinges: 0", + "Check the fold lines first.", + "Other blanks not shown: 2", + "A joint does not close by 12.3 pt.", + "Two panels pass through each other." + ] + ); + let f = Folded { hinges: vec![hinge(false, true, 0.05)], collisions: vec![], ..f }; + assert_eq!(status(1, Some((&Blank::default(), &f)), false), ["Panels: 0, hinges: 0"]); +} + +#[test] +fn the_window_says_when_folded_panels_pass_through_each_other() { + // A strip: a 120 pt lid, a 30 pt wall, the 100 pt base and a 60 pt wall, all 50 pt deep. Folded + // about the base, the lid crosses the taller wall. + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + let path = |app: &mut VectorcraftApp, d: &str| app.run("path.create", json!({ "d": d })).unwrap()["id"].as_u64().unwrap(); + let outline = path(&mut app, "M0 0 L310 0 L310 50 L0 50 Z"); + let creases = [path(&mut app, "M120 0 L120 50"), path(&mut app, "M150 0 L150 50"), path(&mut app, "M250 0 L250 50")]; + app.run("addon.packaging.setRole", json!({ "role": "cut", "ids": [outline] })).unwrap(); + app.run("addon.packaging.setRole", json!({ "role": "crease", "ids": creases })).unwrap(); + app.run("select.none", json!({})).unwrap(); + app.run("ui.foldPreview", json!({"base": [200, 25], "amount": 1})).unwrap(); + let text = crate::tests_labels::painted_text(&mut app, show); + assert!(text.contains("Two panels pass through each other."), "{text}"); + assert!(!text.contains("A joint does not close"), "{text}"); +} diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index b27a198fc1..2e6ca34ff5 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -7120,4 +7120,14 @@ breakText Glyphs Глифи @msg A panel is not joined to the rest by a crease. Панел не е свързан с останалите с линия за биговане. @msg A fold line is on a non-printing layer. Линия на сгъване е на слой, който не се печата. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Панели: {panels}, панти: {hinges}, грешки: {errors}, предупреждения: {warnings} + Fold Preview Преглед на сгъването + Fold Сгъване + Show Fold Lines Покажи линиите на сгъване + Three-Quarter Три четвърти + Open a document to preview its folded shape. Отворете документ, за да прегледате сгънатата му форма. +@msg Check the fold lines first. Първо проверете линиите на сгъване. +@msg Panels: {panels}, hinges: {hinges} Панели: {panels}, панти: {hinges} +@msg Other blanks not shown: {count} Други разкрои не са показани: {count} +@msg A joint does not close by {gap} pt. Една връзка не се затваря с {gap} pt. +@msg Two panels pass through each other. Два панела минават един през друг. @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer трябва да е "singleLine", "everyLine", "standardSingleLine" или "standardEveryLine" diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index df8c34eeeb..9bdc66c1a0 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -7173,4 +7173,14 @@ shape Open Otvoren @msg A panel is not joined to the rest by a crease. Panel nije povezan s ostatkom nijednom linijom bigovanja. @msg A fold line is on a non-printing layer. Linija savijanja je na sloju koji se ne štampa. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Paneli: {panels}, šarke: {hinges}, greške: {errors}, upozorenja: {warnings} + Fold Preview Pregled savijanja + Fold Savijanje + Show Fold Lines Prikaži linije savijanja + Three-Quarter Tri četvrtine + Open a document to preview its folded shape. Otvorite dokument da pregledate njegov savijeni oblik. +@msg Check the fold lines first. Prvo provjerite linije savijanja. +@msg Panels: {panels}, hinges: {hinges} Paneli: {panels}, šarke: {hinges} +@msg Other blanks not shown: {count} Ostali krojevi nisu prikazani: {count} +@msg A joint does not close by {gap} pt. Spoj se ne zatvara za {gap} pt. +@msg Two panels pass through each other. Dva panela prolaze jedan kroz drugi. @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer mora biti "singleLine", "everyLine", "standardSingleLine" ili "standardEveryLine" diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index a3f6252a3f..43bb40fc9f 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -7981,4 +7981,14 @@ breakText Glyphs Glifs @msg A panel is not joined to the rest by a crease. Un panell no està unit a la resta per cap línia d’hendit. @msg A fold line is on a non-printing layer. Una línia de plegat és en una capa que no s’imprimeix. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Panells: {panels}, frontisses: {hinges}, errors: {errors}, avisos: {warnings} + Fold Preview Previsualització del plegat + Fold Plegat + Show Fold Lines Mostra les línies de plegat + Three-Quarter Tres quarts + Open a document to preview its folded shape. Obre un document per previsualitzar-ne la forma plegada. +@msg Check the fold lines first. Primer comprova les línies de plegat. +@msg Panels: {panels}, hinges: {hinges} Panells: {panels}, frontisses: {hinges} +@msg Other blanks not shown: {count} Altres troquelats no mostrats: {count} +@msg A joint does not close by {gap} pt. Una unió no es tanca per {gap} pt. +@msg Two panels pass through each other. Dos panells es travessen l’un a l’altre. @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer ha de ser "singleLine", "everyLine", "standardSingleLine" o "standardEveryLine" diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 83662e4b5b..98440947cb 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -9778,3 +9778,13 @@ breakText Glyphs Glyfy @msg A panel is not joined to the rest by a crease. Panel není se zbytkem spojen žádnou linií bigu. @msg A fold line is on a non-printing layer. Linie skladu je na netisknutelné vrstvě. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Panely: {panels}, panty: {hinges}, chyby: {errors}, upozornění: {warnings} + Fold Preview Náhled skládání + Fold Složení + Show Fold Lines Zobrazit linie skladu + Three-Quarter Tři čtvrtě + Open a document to preview its folded shape. Otevřete dokument, abyste zobrazili náhled jeho složeného tvaru. +@msg Check the fold lines first. Nejprve zkontrolujte linie skladu. +@msg Panels: {panels}, hinges: {hinges} Panely: {panels}, panty: {hinges} +@msg Other blanks not shown: {count} Další přířezy nejsou zobrazeny: {count} +@msg A joint does not close by {gap} pt. Spoj se nezavírá o {gap} pt. +@msg Two panels pass through each other. Dva panely procházejí jeden druhým. diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 6a7c29cbce..cdcff1b2b1 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -9880,4 +9880,14 @@ breakText Glyphs Glyffer @msg A panel is not joined to the rest by a crease. Et panel er ikke forbundet med resten af en rillelinje. @msg A fold line is on a non-printing layer. En foldelinje ligger på et lag, der ikke udskrives. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Paneler: {panels}, hængsler: {hinges}, fejl: {errors}, advarsler: {warnings} + Fold Preview Forhåndsvisning af foldning + Fold Foldning + Show Fold Lines Vis foldelinjer + Three-Quarter Trekvart + Open a document to preview its folded shape. Åbn et dokument for at se dets foldede form. +@msg Check the fold lines first. Kontrollér foldelinjerne først. +@msg Panels: {panels}, hinges: {hinges} Paneler: {panels}, hængsler: {hinges} +@msg Other blanks not shown: {count} Andre emner vises ikke: {count} +@msg A joint does not close by {gap} pt. En samling lukker ikke med {gap} pt. +@msg Two panels pass through each other. To paneler går gennem hinanden. @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer skal være "singleLine", "everyLine", "standardSingleLine" eller "standardEveryLine" diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 1b1ec46863..02896284d5 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -9376,3 +9376,13 @@ breakText Glyphs Glyphen @msg A panel is not joined to the rest by a crease. Ein Feld ist durch keine Rilllinie mit den übrigen verbunden. @msg A fold line is on a non-printing layer. Eine Faltlinie liegt auf einer nicht druckbaren Ebene. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Felder: {panels}, Scharniere: {hinges}, Fehler: {errors}, Warnungen: {warnings} + Fold Preview Faltvorschau + Fold Falten + Show Fold Lines Faltlinien einblenden + Three-Quarter Dreiviertelansicht + Open a document to preview its folded shape. Öffnen Sie ein Dokument, um seine gefaltete Form in der Vorschau zu sehen. +@msg Check the fold lines first. Prüfen Sie zuerst die Faltlinien. +@msg Panels: {panels}, hinges: {hinges} Felder: {panels}, Scharniere: {hinges} +@msg Other blanks not shown: {count} Weitere Zuschnitte nicht angezeigt: {count} +@msg A joint does not close by {gap} pt. Eine Verbindung schließt um {gap} pt nicht. +@msg Two panels pass through each other. Zwei Felder durchdringen einander. diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 618db0a6a8..aea697439c 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -7955,4 +7955,14 @@ breakText Glyphs Γλύφοι @msg A panel is not joined to the rest by a crease. Ένα πάνελ δεν συνδέεται με τα υπόλοιπα με καμία γραμμή πτύχωσης. @msg A fold line is on a non-printing layer. Μια γραμμή δίπλωσης βρίσκεται σε επίπεδο που δεν εκτυπώνεται. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Πάνελ: {panels}, μεντεσέδες: {hinges}, σφάλματα: {errors}, προειδοποιήσεις: {warnings} + Fold Preview Προεπισκόπηση δίπλωσης + Fold Δίπλωση + Show Fold Lines Εμφάνιση γραμμών δίπλωσης + Three-Quarter Τρία τέταρτα + Open a document to preview its folded shape. Ανοίξτε ένα έγγραφο για να δείτε σε προεπισκόπηση το διπλωμένο σχήμα του. +@msg Check the fold lines first. Ελέγξτε πρώτα τις γραμμές δίπλωσης. +@msg Panels: {panels}, hinges: {hinges} Πάνελ: {panels}, μεντεσέδες: {hinges} +@msg Other blanks not shown: {count} Άλλα αναπτύγματα δεν εμφανίζονται: {count} +@msg A joint does not close by {gap} pt. Μια ένωση δεν κλείνει κατά {gap} pt. +@msg Two panels pass through each other. Δύο πάνελ διαπερνούν το ένα το άλλο. @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" το composer πρέπει να είναι "singleLine", "everyLine", "standardSingleLine" ή "standardEveryLine" diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 3cf461791e..2f95bcbf1c 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -7942,4 +7942,14 @@ breakText Glyphs Glifos @msg A panel is not joined to the rest by a crease. Un panel no está unido al resto por ninguna línea de hendido. @msg A fold line is on a non-printing layer. Una línea de plegado está en una capa que no se imprime. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Paneles: {panels}, bisagras: {hinges}, errores: {errors}, advertencias: {warnings} + Fold Preview Vista previa del plegado + Fold Plegado + Show Fold Lines Mostrar líneas de plegado + Three-Quarter Tres cuartos + Open a document to preview its folded shape. Abre un documento para previsualizar su forma plegada. +@msg Check the fold lines first. Comprueba primero las líneas de plegado. +@msg Panels: {panels}, hinges: {hinges} Paneles: {panels}, bisagras: {hinges} +@msg Other blanks not shown: {count} Otros troquelados no mostrados: {count} +@msg A joint does not close by {gap} pt. Una unión no cierra por {gap} pt. +@msg Two panels pass through each other. Dos paneles se atraviesan entre sí. @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer debe ser "singleLine", "everyLine", "standardSingleLine" o "standardEveryLine" diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index 0b1e3c881b..6b01d0477c 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -8038,4 +8038,14 @@ breakText Glyphs Merkit @msg A panel is not joined to the rest by a crease. Paneelia ei ole liitetty muihin millään nuuttausviivalla. @msg A fold line is on a non-printing layer. Taittoviiva on tasolla, jota ei tulosteta. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Paneelit: {panels}, saranat: {hinges}, virheet: {errors}, varoitukset: {warnings} + Fold Preview Taiton esikatselu + Fold Taitto + Show Fold Lines Näytä taittoviivat + Three-Quarter Kolme neljäsosaa + Open a document to preview its folded shape. Avaa asiakirja, niin voit esikatsella sen taitettua muotoa. +@msg Check the fold lines first. Tarkista ensin taittoviivat. +@msg Panels: {panels}, hinges: {hinges} Paneelit: {panels}, saranat: {hinges} +@msg Other blanks not shown: {count} Muita aihioita ei näytetä: {count} +@msg A joint does not close by {gap} pt. Liitos ei sulkeudu, rako {gap} pt. +@msg Two panels pass through each other. Kaksi paneelia kulkee toistensa läpi. @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer on oltava "singleLine", "everyLine", "standardSingleLine" tai "standardEveryLine" diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 66d3c23c01..e166d67798 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -9763,4 +9763,14 @@ breakText Glyphs Glyphes @msg A panel is not joined to the rest by a crease. Un panneau n’est relié au reste par aucune ligne de rainage. @msg A fold line is on a non-printing layer. Une ligne de pliage se trouve sur un calque non imprimable. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} {panels} panneau(x), {hinges} charnière(s), {errors} erreur(s), {warnings} avertissement(s) + Fold Preview Aperçu du pliage + Fold Pliage + Show Fold Lines Afficher les lignes de pliage + Three-Quarter Trois-quarts + Open a document to preview its folded shape. Ouvrez un document pour prévisualiser sa forme pliée. +@msg Check the fold lines first. Vérifiez d’abord les lignes de pliage. +@msg Panels: {panels}, hinges: {hinges} {panels} panneau(x), {hinges} charnière(s) +@msg Other blanks not shown: {count} {count} autre(s) flan(s) non affiché(s) +@msg A joint does not close by {gap} pt. Un joint ne se ferme pas, avec un écart de {gap} pt. +@msg Two panels pass through each other. Deux panneaux se traversent. @msg {_1} × {_2} pixels is too large for GIF (at most 65535 pixels a side): lower the resolution {_1} × {_2} pixels, c’est trop grand pour le GIF (65535 pixels par côté au plus) : réduisez la résolution diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 385fccc138..76057376ed 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -4877,6 +4877,16 @@ swatch [Registration] [રજિસ્ટ્રેશન] @msg A panel is not joined to the rest by a crease. એક પેનલ કોઈ ક્રીઝ લાઇનથી બાકીના સાથે જોડાયેલી નથી. @msg A fold line is on a non-printing layer. એક ફોલ્ડ લાઇન નોન-પ્રિન્ટિંગ લેયર પર છે. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} પેનલ: {panels}, હિન્જ: {hinges}, ભૂલો: {errors}, ચેતવણીઓ: {warnings} + Fold Preview ફોલ્ડ પ્રિવ્યૂ + Fold ફોલ્ડ + Show Fold Lines ફોલ્ડ લાઇન્સ બતાવો + Three-Quarter ત્રણ-ચતુર્થાંશ + Open a document to preview its folded shape. તેનો ફોલ્ડ કરેલો આકાર જોવા દસ્તાવેજ ખોલો. +@msg Check the fold lines first. પહેલાં ફોલ્ડ લાઇન્સ ચેક કરો. +@msg Panels: {panels}, hinges: {hinges} પેનલ: {panels}, હિન્જ: {hinges} +@msg Other blanks not shown: {count} બીજા બ્લેન્ક બતાવ્યા નથી: {count} +@msg A joint does not close by {gap} pt. એક સાંધો {gap} pt થી બંધ થતો નથી. +@msg Two panels pass through each other. બે પેનલ એકબીજામાંથી પસાર થાય છે. Middle Eastern & South Asian Single-line Composer સિંગલ-લાઇન કમ્પોઝર (મધ્ય પૂર્વ અને દક્ષિણ એશિયા) Middle Eastern & South Asian Every-line Composer એવરી-લાઇન કમ્પોઝર (મધ્ય પૂર્વ અને દક્ષિણ એશિયા) Standard Single-line Composer સ્ટાન્ડર્ડ સિંગલ-લાઇન કમ્પોઝર diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index e332f6be32..a465a78cc8 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -9383,3 +9383,13 @@ theme Appearance अपीयरेंस @msg A panel is not joined to the rest by a crease. कोई पैनल किसी क्रीज़ लाइन से बाकी से जुड़ा नहीं है। @msg A fold line is on a non-printing layer. एक फ़ोल्ड लाइन नॉन-प्रिंटिंग लेयर पर है। @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} पैनल: {panels}, हिंज: {hinges}, एरर: {errors}, वॉर्निंग: {warnings} + Fold Preview फ़ोल्ड प्रीव्यू + Fold फ़ोल्ड + Show Fold Lines फ़ोल्ड लाइनें दिखाएँ + Three-Quarter तीन-चौथाई + Open a document to preview its folded shape. इसका फ़ोल्ड किया हुआ आकार देखने के लिए कोई डॉक्यूमेंट ओपन करें। +@msg Check the fold lines first. पहले फ़ोल्ड लाइनें चेक करें। +@msg Panels: {panels}, hinges: {hinges} पैनल: {panels}, हिंज: {hinges} +@msg Other blanks not shown: {count} दूसरे ब्लैंक नहीं दिखाए गए: {count} +@msg A joint does not close by {gap} pt. एक जोड़ {gap} pt से बंद नहीं होता। +@msg Two panels pass through each other. दो पैनल एक-दूसरे के आर-पार जाते हैं। diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index e4452cb211..f3570ab058 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -9766,3 +9766,13 @@ breakText Glyphs Glifák @msg A panel is not joined to the rest by a crease. Egy panelt egyetlen bigvonal sem köt a többihez. @msg A fold line is on a non-printing layer. Egy hajtásvonal nem nyomtatható rétegen van. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Panelek: {panels}, zsanérok: {hinges}, hibák: {errors}, figyelmeztetések: {warnings} + Fold Preview Hajtás előnézete + Fold Hajtás + Show Fold Lines Hajtásvonalak megjelenítése + Three-Quarter Háromnegyed + Open a document to preview its folded shape. Nyiss meg egy dokumentumot a hajtogatott alakja előnézetéhez. +@msg Check the fold lines first. Előbb ellenőrizd a hajtásvonalakat. +@msg Panels: {panels}, hinges: {hinges} Panelek: {panels}, zsanérok: {hinges} +@msg Other blanks not shown: {count} További kiterítékek nincsenek megjelenítve: {count} +@msg A joint does not close by {gap} pt. Egy illesztés {gap} pt-tal nem záródik. +@msg Two panels pass through each other. Két panel áthatol egymáson. diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 37ea827f3c..6601f2cfe7 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -7135,4 +7135,14 @@ breakText Glyphs Glif @msg A panel is not joined to the rest by a crease. Sebuah panel tidak tersambung ke bagian lain oleh garis lekuk apa pun. @msg A fold line is on a non-printing layer. Sebuah garis lipat berada di lapisan yang tidak dicetak. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Panel: {panels}, engsel: {hinges}, galat: {errors}, peringatan: {warnings} + Fold Preview Pratinjau lipatan + Fold Lipat + Show Fold Lines Tampilkan garis lipat + Three-Quarter Tiga perempat + Open a document to preview its folded shape. Buka dokumen untuk melihat pratinjau bentuk terlipatnya. +@msg Check the fold lines first. Periksa garis lipat terlebih dahulu. +@msg Panels: {panels}, hinges: {hinges} Panel: {panels}, engsel: {hinges} +@msg Other blanks not shown: {count} Bentangan lain tidak ditampilkan: {count} +@msg A joint does not close by {gap} pt. Sebuah sambungan tidak menutup sejauh {gap} pt. +@msg Two panels pass through each other. Dua panel saling menembus. @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer harus "singleLine", "everyLine", "standardSingleLine", atau "standardEveryLine" diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 7005d218f7..53a9f9ab07 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -9410,3 +9410,13 @@ breakText Glyphs Glifi @msg A panel is not joined to the rest by a crease. Un pannello non è unito al resto da alcuna linea di cordonatura. @msg A fold line is on a non-printing layer. Una linea di piega si trova su un livello non stampabile. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Pannelli: {panels}, cerniere: {hinges}, errori: {errors}, avvisi: {warnings} + Fold Preview Anteprima piegatura + Fold Piegatura + Show Fold Lines Mostra linee di piega + Three-Quarter Tre quarti + Open a document to preview its folded shape. Apri un documento per vederne in anteprima la forma piegata. +@msg Check the fold lines first. Verifica prima le linee di piega. +@msg Panels: {panels}, hinges: {hinges} Pannelli: {panels}, cerniere: {hinges} +@msg Other blanks not shown: {count} Altri fustellati non mostrati: {count} +@msg A joint does not close by {gap} pt. Una giunzione non si chiude di {gap} pt. +@msg Two panels pass through each other. Due pannelli si attraversano. diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 9b403f103c..1d72426468 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -9477,3 +9477,13 @@ breakText Glyphs 字形 @msg A panel is not joined to the rest by a crease. パネルがどの筋入れ線でも他とつながっていません。 @msg A fold line is on a non-printing layer. 折り線が印刷しないレイヤーにあります。 @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} パネル: {panels}、ヒンジ: {hinges}、エラー: {errors}、警告: {warnings} + Fold Preview 折りプレビュー + Fold 折り + Show Fold Lines 折り線を表示 + Three-Quarter 斜め + Open a document to preview its folded shape. ドキュメントを開くと折った形をプレビューできます。 +@msg Check the fold lines first. 先に折り線をチェックしてください。 +@msg Panels: {panels}, hinges: {hinges} パネル: {panels}、ヒンジ: {hinges} +@msg Other blanks not shown: {count} 表示されていない他の展開図: {count} +@msg A joint does not close by {gap} pt. 継ぎ目が {gap} pt 閉じていません。 +@msg Two panels pass through each other. 2 つのパネルが互いを貫通しています。 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index a069c9bac6..7baa711ee9 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -10044,4 +10044,14 @@ font-script Japanese იაპონური @msg A panel is not joined to the rest by a crease. პანელი დანარჩენს არცერთი ბიგის ხაზით არ უერთდება. @msg A fold line is on a non-printing layer. მოკეცვის ხაზი არასაბეჭდ შრეზეა. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} პანელები: {panels}, ანჯამები: {hinges}, შეცდომები: {errors}, გაფრთხილებები: {warnings} + Fold Preview მოკეცვის გადახედვა + Fold მოკეცვა + Show Fold Lines მოკეცვის ხაზების ჩვენება + Three-Quarter სამი მეოთხედი + Open a document to preview its folded shape. გახსენით დოკუმენტი მისი მოკეცილი ფორმის სანახავად. +@msg Check the fold lines first. ჯერ შეამოწმეთ მოკეცვის ხაზები. +@msg Panels: {panels}, hinges: {hinges} პანელები: {panels}, ანჯამები: {hinges} +@msg Other blanks not shown: {count} სხვა ნამზადები არ ჩანს: {count} +@msg A joint does not close by {gap} pt. შეერთება არ იხურება {gap} pt-ით. +@msg Two panels pass through each other. ორი პანელი ერთმანეთში გადის. @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer უნდა იყოს "singleLine", "everyLine", "standardSingleLine" ან "standardEveryLine" diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index e2de2a8d46..e2eb144f28 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -9373,3 +9373,13 @@ breakText Glyphs 글리프 @msg A panel is not joined to the rest by a crease. 패널이 어떤 오시선으로도 나머지와 연결되어 있지 않습니다. @msg A fold line is on a non-printing layer. 접는 선이 인쇄되지 않는 레이어에 있습니다. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} 패널: {panels}, 힌지: {hinges}, 오류: {errors}, 경고: {warnings} + Fold Preview 접기 미리 보기 + Fold 접기 + Show Fold Lines 접는 선 표시 + Three-Quarter 3/4 보기 + Open a document to preview its folded shape. 접은 모양을 미리 보려면 문서를 여세요. +@msg Check the fold lines first. 먼저 접는 선을 검사하세요. +@msg Panels: {panels}, hinges: {hinges} 패널: {panels}, 힌지: {hinges} +@msg Other blanks not shown: {count} 표시되지 않은 다른 전개도: {count} +@msg A joint does not close by {gap} pt. 이음매가 {gap} pt만큼 닫히지 않습니다. +@msg Two panels pass through each other. 두 패널이 서로 관통합니다. diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index aaa159876e..fa05510f1a 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -9811,3 +9811,13 @@ breakText Glyphs Glyphs @msg A panel is not joined to the rest by a crease. Een paneel is door geen rillijn met de rest verbonden. @msg A fold line is on a non-printing layer. Een vouwlijn staat op een laag die niet wordt afgedrukt. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Panelen: {panels}, scharnieren: {hinges}, fouten: {errors}, waarschuwingen: {warnings} + Fold Preview Vouwvoorbeeld + Fold Vouwen + Show Fold Lines Vouwlijnen tonen + Three-Quarter Driekwart + Open a document to preview its folded shape. Open een document om de gevouwen vorm te bekijken. +@msg Check the fold lines first. Controleer eerst de vouwlijnen. +@msg Panels: {panels}, hinges: {hinges} Panelen: {panels}, scharnieren: {hinges} +@msg Other blanks not shown: {count} Andere uitslagen niet getoond: {count} +@msg A joint does not close by {gap} pt. Een naad sluit {gap} pt niet. +@msg Two panels pass through each other. Twee panelen gaan door elkaar heen. diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 6f7c6eb49a..a0540715ae 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -9631,3 +9631,13 @@ breakText Glyphs Glify @msg A panel is not joined to the rest by a crease. Panel nie jest połączony z resztą żadną linią bigowania. @msg A fold line is on a non-printing layer. Linia zgięcia znajduje się na warstwie niedrukowanej. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Panele: {panels}, zawiasy: {hinges}, błędy: {errors}, ostrzeżenia: {warnings} + Fold Preview Podgląd złożenia + Fold Złożenie + Show Fold Lines Pokaż linie zgięcia + Three-Quarter Trzy czwarte + Open a document to preview its folded shape. Otwórz dokument, aby zobaczyć podgląd jego złożonego kształtu. +@msg Check the fold lines first. Najpierw sprawdź linie zgięcia. +@msg Panels: {panels}, hinges: {hinges} Panele: {panels}, zawiasy: {hinges} +@msg Other blanks not shown: {count} Inne wykroje nie są pokazane: {count} +@msg A joint does not close by {gap} pt. Połączenie nie domyka się o {gap} pt. +@msg Two panels pass through each other. Dwa panele przechodzą przez siebie. diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 4138d050c8..eb9d9c52ae 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -9849,3 +9849,13 @@ swatch Yellow Green Verde-amarelado @msg A panel is not joined to the rest by a crease. Um painel não está unido ao restante por nenhuma linha de vinco. @msg A fold line is on a non-printing layer. Uma linha de dobra está em uma camada não imprimível. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Painéis: {panels}, dobradiças: {hinges}, erros: {errors}, avisos: {warnings} + Fold Preview Visualização da Dobra + Fold Dobra + Show Fold Lines Mostrar Linhas de Dobra + Three-Quarter Três Quartos + Open a document to preview its folded shape. Abra um documento para visualizar sua forma dobrada. +@msg Check the fold lines first. Verifique primeiro as linhas de dobra. +@msg Panels: {panels}, hinges: {hinges} Painéis: {panels}, dobradiças: {hinges} +@msg Other blanks not shown: {count} Outras planificações não exibidas: {count} +@msg A joint does not close by {gap} pt. Uma junção não fecha por {gap} pt. +@msg Two panels pass through each other. Dois painéis se atravessam. diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 5f73b0dd78..1c1dda90c2 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -9870,5 +9870,15 @@ shape Open Открытый @msg A panel is not joined to the rest by a crease. Панель не соединена с остальными ни одной линией биговки. @msg A fold line is on a non-printing layer. Линия сгиба находится на непечатаемом слое. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Панели: {panels}, шарниры: {hinges}, ошибки: {errors}, предупреждения: {warnings} + Fold Preview Предпросмотр сгиба + Fold Сгиб + Show Fold Lines Показать линии сгиба + Three-Quarter Три четверти + Open a document to preview its folded shape. Откройте документ, чтобы просмотреть его в сложенном виде. +@msg Check the fold lines first. Сначала проверьте линии сгиба. +@msg Panels: {panels}, hinges: {hinges} Панели: {panels}, шарниры: {hinges} +@msg Other blanks not shown: {count} Другие развёртки не показаны: {count} +@msg A joint does not close by {gap} pt. Стык не смыкается на {gap} pt. +@msg Two panels pass through each other. Две панели проходят друг сквозь друга. @msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution {w} × {h} пикселей — слишком большой размер для PSD (не более {MAX_SIDE} пикселей по стороне): уменьшите разрешение @msg composer must be "singleLine", "everyLine", "standardSingleLine" or "standardEveryLine" composer должен быть "singleLine", "everyLine", "standardSingleLine" или "standardEveryLine" diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 769e5c7873..0ca8801ade 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -9459,4 +9459,14 @@ digits Hindi Hindi @msg A panel is not joined to the rest by a crease. En panel är inte förbunden med resten av någon biglinje. @msg A fold line is on a non-printing layer. En falslinje ligger på ett lager som inte skrivs ut. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Paneler: {panels}, gångjärn: {hinges}, fel: {errors}, varningar: {warnings} + Fold Preview Förhandsgranskning av falsning + Fold Falsning + Show Fold Lines Visa falslinjer + Three-Quarter Trekvarts + Open a document to preview its folded shape. Öppna ett dokument för att förhandsgranska dess falsade form. +@msg Check the fold lines first. Kontrollera falslinjerna först. +@msg Panels: {panels}, hinges: {hinges} Paneler: {panels}, gångjärn: {hinges} +@msg Other blanks not shown: {count} Andra ämnen visas inte: {count} +@msg A joint does not close by {gap} pt. En fog sluter inte med {gap} pt. +@msg Two panels pass through each other. Två paneler går igenom varandra. @msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution {w} × {h} pixlar är för stort för PSD (högst {MAX_SIDE} pixlar per sida): sänk upplösningen diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 8937e9fe77..25975ba9ee 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -9732,3 +9732,13 @@ breakText Glyphs Glifler @msg A panel is not joined to the rest by a crease. Bir panel geri kalanlara hiçbir pilyaj çizgisiyle bağlı değil. @msg A fold line is on a non-printing layer. Bir katlama çizgisi yazdırılmayan bir katmanda. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Paneller: {panels}, menteşeler: {hinges}, hatalar: {errors}, uyarılar: {warnings} + Fold Preview Katlama Önizlemesi + Fold Katlama + Show Fold Lines Katlama Çizgilerini Göster + Three-Quarter Dörtte Üç + Open a document to preview its folded shape. Katlanmış şeklini önizlemek için bir belgeyi açın. +@msg Check the fold lines first. Önce katlama çizgilerini denetleyin. +@msg Panels: {panels}, hinges: {hinges} Paneller: {panels}, menteşeler: {hinges} +@msg Other blanks not shown: {count} Gösterilmeyen diğer açınımlar: {count} +@msg A joint does not close by {gap} pt. Bir birleşim {gap} pt kadar kapanmıyor. +@msg Two panels pass through each other. İki panel birbirinin içinden geçiyor. diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 99f8038a30..1aca1f7cfa 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -9385,3 +9385,13 @@ breakText Glyphs Гліфи @msg A panel is not joined to the rest by a crease. Панель не з’єднана з рештою жодною лінією біговки. @msg A fold line is on a non-printing layer. Лінія згину лежить на шарі, що не друкується. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Панелі: {panels}, шарніри: {hinges}, помилки: {errors}, попередження: {warnings} + Fold Preview Перегляд згину + Fold Згин + Show Fold Lines Показати лінії згину + Three-Quarter Три чверті + Open a document to preview its folded shape. Відкрийте документ, щоб переглянути його у складеному вигляді. +@msg Check the fold lines first. Спершу перевірте лінії згину. +@msg Panels: {panels}, hinges: {hinges} Панелі: {panels}, шарніри: {hinges} +@msg Other blanks not shown: {count} Інші розгортки не показано: {count} +@msg A joint does not close by {gap} pt. Стик не змикається на {gap} pt. +@msg Two panels pass through each other. Дві панелі проходять одна крізь одну. diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index cece3dcf1b..21713b4b2b 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -7495,6 +7495,16 @@ breakText Glyphs Glyph @msg A panel is not joined to the rest by a crease. Một mặt không được nối với phần còn lại bằng đường cấn nào. @msg A fold line is on a non-printing layer. Một đường gấp nằm trên lớp không in. @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} Mặt: {panels}, bản lề: {hinges}, lỗi: {errors}, cảnh báo: {warnings} + Fold Preview Xem trước nếp gấp + Fold Gấp + Show Fold Lines Hiện đường gấp + Three-Quarter Ba phần tư + Open a document to preview its folded shape. Mở tài liệu để xem trước hình dạng đã gấp của nó. +@msg Check the fold lines first. Hãy kiểm tra đường gấp trước. +@msg Panels: {panels}, hinges: {hinges} Mặt: {panels}, bản lề: {hinges} +@msg Other blanks not shown: {count} Các khuôn trải khác không được hiển thị: {count} +@msg A joint does not close by {gap} pt. Một mối nối hở {gap} pt. +@msg Two panels pass through each other. Hai mặt xuyên qua nhau. # Messages of the effects, 3D, image export, color profiles, swatch exchange files, color books and DXF import. @msg 3D effects require finite coordinates within 100 million points Hiệu ứng 3D yêu cầu tọa độ hữu hạn trong phạm vi 100 triệu điểm diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 677f7268b4..bb53379905 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -9616,4 +9616,14 @@ breakText Glyphs 字形 @msg A panel is not joined to the rest by a crease. 一个面板没有通过任何压痕线与其余部分相连。 @msg A fold line is on a non-printing layer. 一条折线位于不打印的图层上。 @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} 面板:{panels},铰链:{hinges},错误:{errors},警告:{warnings} + Fold Preview 折叠预览 + Fold 折叠 + Show Fold Lines 显示折线 + Three-Quarter 四分之三视图 + Open a document to preview its folded shape. 打开文档以预览其折叠后的形状。 +@msg Check the fold lines first. 请先检查折线。 +@msg Panels: {panels}, hinges: {hinges} 面板:{panels},铰链:{hinges} +@msg Other blanks not shown: {count} 未显示的其他展开图:{count} +@msg A joint does not close by {gap} pt. 有一处接缝相差 {gap} pt 未闭合。 +@msg Two panels pass through each other. 两个面板相互穿插。 @msg {w} × {h} pixels is too large for PSD (at most {MAX_SIDE} pixels a side): lower the resolution {w} × {h} 像素对 PSD 而言过大 (每边最多 {MAX_SIDE} 像素):请降低分辨率 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index b50f0671b0..b165b4fa03 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -9426,4 +9426,14 @@ breakText Glyphs 字符 @msg A panel is not joined to the rest by a crease. 一個面板沒有透過任何壓痕線與其餘部分相連。 @msg A fold line is on a non-printing layer. 一條摺線位於不列印的圖層上。 @msg Panels: {panels}, hinges: {hinges}, errors: {errors}, warnings: {warnings} 面板:{panels},鉸鏈:{hinges},錯誤:{errors},警告:{warnings} + Fold Preview 摺疊預覽 + Fold 摺疊 + Show Fold Lines 顯示摺線 + Three-Quarter 四分之三視圖 + Open a document to preview its folded shape. 開啟文件以預覽其摺疊後的形狀。 +@msg Check the fold lines first. 請先檢查摺線。 +@msg Panels: {panels}, hinges: {hinges} 面板:{panels},鉸鏈:{hinges} +@msg Other blanks not shown: {count} 未顯示的其他展開圖:{count} +@msg A joint does not close by {gap} pt. 有一處接縫相差 {gap} pt 未閉合。 +@msg Two panels pass through each other. 兩個面板相互穿插。 @msg {what} would print on more than {MAX_TILES} tiles: scale it down {what} 會列印在超過 {MAX_TILES} 個拼貼上:請縮小 diff --git a/crates/ui-egui/src/menus/run.rs b/crates/ui-egui/src/menus/run.rs index b4e1c668ac..4966b9b31b 100644 --- a/crates/ui-egui/src/menus/run.rs +++ b/crates/ui-egui/src/menus/run.rs @@ -860,6 +860,7 @@ fn run_ui_part9(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option<Result< } "ui.imageTracePresetDialog" => crate::dialogs::trace_presets::open(app, p), "ui.flattenerPreview" => crate::panels::flattener_preview::command(app, p), + "ui.foldPreview" => crate::addons::packaging::preview::command(app, p), "ui.copyScriptConsole" => crate::panels::script_console::copy(app, p), "window.graphicStyleLibrary" => crate::panels::graphic_styles::open_library(app, p), "ui.libraryPanel" => crate::panels::library_panel::command(app, p), diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 2b285c704b..af7f870f83 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1148,6 +1148,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{highlight?: none|rasterizedRegions|transparentObjects|allAffected|expandedPatterns|outlinedStrokes|outlinedText|allRasterized, overprints?: preserve|simulate|discard, preset?: name (loads its options), options?: {option keys, over the preset's}, showOptions?} set the Flattener Preview panel (ui.inspect: ui.flattener_preview), show it and refresh its snapshot → what flattener.preview answers for it", ), + ( + "ui.foldPreview", + "Fold Preview", + "", + "{amount?: 0..1 (how far the blank is folded), view?: front|back|left|right|top|bottom|threeQuarter, rotateX?: deg -180..180 (the top toward the viewer), rotateY?: deg -180..180 (the right side toward the viewer), zoom?: 0.1..8 (1 fits the folded blank), perspective?: deg 0..160 (field of view; 0 for none), inside?: #rrggbb or the name of a swatch with a plain color (the board's inside), showFoldLines?: bool, base?: [x, y] (the panel under this point stays in place; an error when it is in no panel) or null (the largest panel)} set the Fold Preview window (ui.inspect: ui.fold_preview), which folds the blank that the document's shown fold lines make (addon.packaging.fold) with the document's art printed on the outside, show it and draw it again; view and zoom also center the view. A value of the wrong kind or out of range is an error and sets nothing → the window's settings and frame: the last frame's {width, height (pixels), foldMs, drawMs} or null", + ), ( "ui.copyScriptConsole", "Copy Script Console", diff --git a/crates/ui-egui/src/panel_docking.rs b/crates/ui-egui/src/panel_docking.rs index 0a4f01879d..7bf9249234 100644 --- a/crates/ui-egui/src/panel_docking.rs +++ b/crates/ui-egui/src/panel_docking.rs @@ -1377,6 +1377,7 @@ pub(crate) fn floating_size(panel: &str) -> egui::Vec2 { // Tall enough to show its Corners and Shared Edges sections, last in it, which the Corner // Tool's and Shared Edge Merge Tool's menu items open. crate::addons::pathtools::ID => egui::vec2(260.0, 660.0), + crate::addons::packaging::preview::ID => egui::vec2(520.0, 440.0), _ => egui::vec2(260.0, 360.0), } } diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rs index 487d501054..67a90c90e2 100644 --- a/crates/ui-egui/src/panels.rs +++ b/crates/ui-egui/src/panels.rs @@ -191,6 +191,7 @@ pub fn show_icon_panel(app: &mut VectorcraftApp, ui: &mut Ui, id: &str) { crate::addons::cleanup::ID => crate::addons::cleanup::show(app, ui), crate::addons::color::ID => crate::addons::color::show(app, ui), crate::addons::packaging::ID => crate::addons::packaging::show(app, ui), + crate::addons::packaging::preview::ID => crate::addons::packaging::preview::show(app, ui), crate::addons::pathtools::ID => crate::addons::pathtools::show(app, ui), crate::addons::pathtools::shape::ID => crate::addons::pathtools::shape::show(app, ui), crate::addons::pen::ID => crate::addons::pen::show(app, ui), diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index d3698aaeef..480bb37ed8 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -228,6 +228,7 @@ pub const ICON_PANELS: &[(&str, &str, &str)] = &[ (crate::addons::cleanup::ID, "Artwork Cleanup", "sparkles"), (crate::addons::color::ID, "Color Effects", "sun"), (crate::addons::packaging::ID, "Fold Lines", "scissors"), + (crate::addons::packaging::preview::ID, "Fold Preview", "box"), (crate::addons::pathtools::ID, "Anchor Inspector", "dc-anchor-smooth"), (crate::addons::pathtools::shape::ID, "Parametric Shape", "hexagon"), (crate::addons::pen::ID, "Smart Pen", "spline-pointer"), @@ -712,6 +713,10 @@ pub struct UiState { /// Flattener Preview panel: highlight, overprints, preset and options (`ui.flattenerPreview`). #[serde(default)] pub flattener_preview: crate::panels::flattener_preview::Settings, + /// Fold Preview window: fold amount, view, zoom, perspective, inside color, fold lines and + /// base panel (`ui.foldPreview`). + #[serde(default)] + pub fold_preview: crate::addons::packaging::preview::Settings, /// Color Guide panel: Limit to Library, a swatch library id, "document" (the document's /// swatches) or "" (none) (`ui.colorGuideLimit`). #[serde(default)] @@ -1237,6 +1242,7 @@ impl Default for UiState { color_guide: Default::default(), library_panels: vec![], flattener_preview: Default::default(), + fold_preview: Default::default(), color_guide_limit: String::new(), color_guide_base: None, align_to: Default::default(), diff --git a/docs/mcp.md b/docs/mcp.md index 044b452de5..f7075c4397 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -13099,10 +13099,10 @@ there is no step. → `{symbols: [name…], ids: [instance id…], skipped: [{la ## Packaging Tools add-on Packaging Tools is a built-in add-on for the dielines of boxes and other folded packaging. Its commands are -`addon.packaging.setRole`, `addon.packaging.roles`, `addon.packaging.setRoleSwatch` and `addon.packaging.check`. In the -desktop app, Object › Plug-ins › Packaging Tools › Fold Lines opens the Fold Lines panel, Make Cut Line, Make Crease Line, -Make Partial Cut Line and Make Perforation Line run `addon.packaging.setRole` on the selection, and Check Fold Lines runs -`addon.packaging.check`. +`addon.packaging.setRole`, `addon.packaging.roles`, `addon.packaging.setRoleSwatch`, `addon.packaging.check` and +`addon.packaging.fold`. In the desktop app, Object › Plug-ins › Packaging Tools › Fold Lines opens the Fold Lines panel, +Make Cut Line, Make Crease Line, Make Partial Cut Line and Make Perforation Line run `addon.packaging.setRole` on the +selection, Check Fold Lines runs `addon.packaging.check`, and Fold Preview runs `ui.foldPreview`. ### Fold line roles @@ -13198,6 +13198,54 @@ The list is shown until the document changes. {"name":"run_command","arguments":{"command":"addon.packaging.check","params":{"tolerance":0.5,"select":true}}} ``` +### Fold Preview + +`addon.packaging.fold` (`{ids?, base?: [x, y], amount?: 1, tolerance?: 0.1}`) folds a blank into its 3D shape. It reads +the fold lines as `addon.packaging.check` does, and folds the blank that holds the base panel: the panel under `base`, or +the largest panel of all the blanks. The base panel stays in place. Every other panel turns about the hinges that join it +to the base, each by its angle times `amount` (0 is flat, 1 is folded): a Crease or a Perforation folds 90° away from +the printed side, so the print ends up outside, and a Partial Cut folds 90° toward it. A hinge that closes a loop of +panels is not turned about; `gap` says how far apart its two placements end up when every hinge is folded all the way, +whatever `amount` is, and it `closes` when that is within `tolerance` or 0.5% of its length. A panel that no chain of +hinges joins to the base stays flat where it is. `amount` must be from 0 to 1 and `base` a point in a panel; anything +else is an error. The command does not change the document. + +Result: `{ok, blank, blanks, base, panels: [{outline, frame: {x, y, z, origin}, parent, depth}], hinges: [{a, b, +angle, kind, closes, gap}], collisions: [[a, b]], issues}`. `outline` is the panel's SVG path data in document +coordinates. `frame` gives where the flat blank's x and y directions, its printed side and its origin end up, in points, +with x to the right, y up and z toward the printed side of the flat blank. `kind` is `tree` for the hinges the panels +turn about and `closing` for the others. `collisions` lists the panels that pass through each other; panels stacked in +one plane, such as the top flaps of a closed box, are not listed. Without a blank (`ok` false), `blank` and `base` are +null and the lists are empty; `issues` are those of `addon.packaging.check`. + +The Fold Preview window (Object › Plug-ins › Packaging Tools › Fold Preview, or the Fold Lines panel's Fold Preview +button) shows the blank that the document's shown fold lines make, folded, with the document's printed art on the +outside of each panel and the board's inside color on the back. The print leaves out the fold lines, unless Show Fold +Lines is on, and the layers that do not print. Under the view, the Fold slider sets the amount and the Zoom slider the +zoom; a status line gives the panels and hinges and says when a joint does not close, when two panels pass through each +other, when other blanks are not shown and when the fold lines have an error. Dragging in the view turns it, a +Shift-drag keeps to one axis, a middle-drag or a Space-drag moves it, the wheel zooms, a double-click on a panel makes it +the base, and the arrow keys turn the view by 5° when it has the keyboard focus. The view is drawn at the display's +pixel density up to 2,097,152 pixels (2,048 × 1,024) and 4,096 pixels along a side, and at a lower density past either, +and the print is a raster whose longest side is 2,048 pixels, rendered again when the document changes. + +`ui.foldPreview` (`{amount?, view?: front|back|left|right|top|bottom|threeQuarter, rotateX?, rotateY?, zoom?, +perspective?, inside?, showFoldLines?, base?}`) sets the window, shows it and draws it again. A second run leaves the +window open. `rotateX` (-180 to 180) tips the top toward the viewer and `rotateY` (-180 to 180) turns the right side +toward the viewer, in degrees; `zoom` is 0.1 to 8, where 1 fits the folded blank; `perspective` is the field of view, 0 to +160 degrees, 0 for none; `inside` is `#rrggbb` or the name of a swatch with a plain color; `base` is a point in a panel +of the document's blanks, or null for the largest panel. With perspective, the zoom of 1 keeps the eye at least twice +the folded blank's radius from its middle. A value of the wrong kind or out of range is an error and sets nothing. +VectorCraft's own defaults are a Three-Quarter view (`rotateX` 25, `rotateY` 35), no perspective, a white inside and the +fold lines hidden. Saved settings out of range are brought into range when the window is drawn. Result: the window's +settings, and `frame`: the last frame's `{width, height}` in pixels and how long the fold and the drawing took (`foldMs`, +`drawMs`), or null before the first frame. The view is folded and drawn again only when the document, the settings or +the window's size change. + +```json +{"name":"run_command","arguments":{"command":"ui.foldPreview","params":{"amount":0.5,"view":"threeQuarter","perspective":30}}} +``` + ## Image Tools add-on Image Tools is a built-in add-on for placed images: its commands are `addon.image.removeBackground`, From 62ef2f4e6871c7abe29f458368444b9791496198 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Mon, 16 Nov 2026 10:24:23 -0800 Subject: [PATCH 067/176] Docs: Tile counts each view of a document as a window window.arrange.tile counts windows for its two-window minimum, its grid columns and the panes of the 2-Up to 6-Up layouts. docs/mcp.md said documents. --- docs/mcp.md | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/docs/mcp.md b/docs/mcp.md index 4be2808189..b7372cec7a 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7345,14 +7345,15 @@ document current, and its tool keeps its state; closing the current document mak current, or the one before it when it was the last tab. In the desktop app a modified document comes to the front first, to ask whether to save it. `window.arrange.tile` (Window › Arrange › Tile) shows every open document in its own pane, edge to edge in the document -area, in a grid of as many columns as the square root of the number of documents, rounded up, and fits each document to -its pane; with fewer than two documents open it leaves the view, `tiled` and the layout as they are. It returns +area, in a grid of as many columns as the square root of the number of windows, rounded up, and fits each document to +its pane. Each view of a document counts as a window (see `window.newWindow` below). With fewer than two windows open it +leaves the view, `tiled` and the layout as they are. It returns `{tiled, panes, layout}`. `window.arrange.tile {layout}` picks another layout, as the other Tile items of Window › Arrange and of the application bar's Arrange Documents button do: `grid` (the default), `vertical` (Tile All Vertically: side by side in one row), `horizontal` (Tile All Horizontally: stacked in one column), and `2up`, `3up`, -`4up` and `6up`, which show at most that many documents (2-Up and 3-Up side by side, 4-Up two by two, 6-Up three by -two) and leave the others under their tabs. Those layouts show the first documents in tab order, and the current -document takes the last pane when it is not among them, so a click on another tab brings that document into the last +`4up` and `6up`, which show at most that many windows (2-Up and 3-Up side by side, 4-Up two by two, 6-Up three by +two) and leave the others under their tabs. Those layouts show the first windows in tab order, and the current +window takes the last pane when it is not among them, so a click on another tab brings that window into the last pane. Any other `layout` is an error, and the view stays as it is. The set of layouts and how each one places the panes are VectorCraft's own. The current document's pane is the canvas, and a press in another pane makes its document the current one. `window.arrange.consolidateAllWindows` (Window › Arrange › Consolidate All Windows, also first in Arrange From 46c8a86fbd81c9a52301efd04ec4c3f4d94a7618 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Mon, 16 Nov 2026 12:01:11 -0800 Subject: [PATCH 068/176] Window: Arrange Documents tests find the search icon by its current label The command palette's search icon is labeled "Search commands, tools, panels and effects" since 44f75df965. The two application bar tests still looked for "Search commands and tools", so the narrow-bar test saw Arrange Documents without the search icon at every width. --- crates/ui-egui/src/canvas/panes/tests.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/canvas/panes/tests.rs b/crates/ui-egui/src/canvas/panes/tests.rs index 24a4690b3c..8b3f7277b1 100644 --- a/crates/ui-egui/src/canvas/panes/tests.rs +++ b/crates/ui-egui/src/canvas/panes/tests.rs @@ -376,7 +376,7 @@ fn the_arrange_documents_button_tiles_and_consolidates() { crate::theme::install_fonts(&ctx); app_bar_frame(&mut app, &ctx, vec![]); let nodes = app_bar_frame(&mut app, &ctx, vec![]); - let (arrange, search) = (app_bar_node(&nodes, "Arrange Documents"), app_bar_node(&nodes, "Search commands and tools")); + let (arrange, search) = (app_bar_node(&nodes, "Arrange Documents"), app_bar_node(&nodes, "Search commands, tools, panels and effects")); let (arrange, search) = (arrange.expect("the application bar has Arrange Documents"), search.expect("the search icon shows")); assert!(arrange.x > search.x && (arrange.y - search.y).abs() < 1.0, "right of the search icon: {arrange:?}, {search:?}"); click_app_bar(&mut app, &ctx, "Arrange Documents"); @@ -412,7 +412,8 @@ fn a_narrow_application_bar_keeps_search_before_arrange_documents() { for width in (200..=1400).rev().step_by(4) { app_bar_frame_in(&mut app, &ctx, vec![], width as f32); let nodes = app_bar_frame_in(&mut app, &ctx, vec![], width as f32); - let (arrange, search) = (app_bar_node(&nodes, "Arrange Documents").is_some(), app_bar_node(&nodes, "Search commands and tools").is_some()); + let (arrange, search) = + (app_bar_node(&nodes, "Arrange Documents").is_some(), app_bar_node(&nodes, "Search commands, tools, panels and effects").is_some()); assert!(search || !arrange, "{width} pt: Arrange Documents shows without the search icon"); search_alone |= search && !arrange; } From c0667364ed3dc86243842a4d4848f9991b024b0c Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Mon, 16 Nov 2026 12:22:19 -0800 Subject: [PATCH 069/176] Navigator: View Artboard Contents Only is on by default and hides art outside the artboards The Navigator panel menu item View Artboard Only is renamed View Artboard Contents Only and is now on by default. While it is on, the thumbnail fits the artboards and draws only the art inside them: art on the pasteboard and in the gaps between artboards is left out, and a shape that crosses an artboard's edge is cut there. Before, the option only narrowed the thumbnail to the artboards' bounding box, so art in the gaps and past an artboard's edge still showed. The choice is kept with the UI state for every document, instead of being lost on restart. UI state saved without it reads it as on, and a saved off stays off. A user who wants the pasteboard art in the thumbnail turns the menu item off, or runs ui.navigatorPanelOptions {viewArtboardContentsOnly: false}. - ui.navigatorPanelOptions takes viewArtboardContentsOnly (true or false; any other value is an error and changes nothing) and answers {color, solidDashes, viewArtboardContentsOnly}. - The renamed label has a row in every catalog that had the old one. Docs: docs/mcp.md (Navigator panel options), docs/target-app-parity.md. --- crates/mcp/src/ui_catalog.rs | 2 +- .../src/dialogs/navigator_panel_options.rs | 2 +- crates/ui-egui/src/i18n/bg.tsv | 2 +- crates/ui-egui/src/i18n/bs.tsv | 2 +- crates/ui-egui/src/i18n/ca.tsv | 2 +- crates/ui-egui/src/i18n/cs.tsv | 2 +- crates/ui-egui/src/i18n/da.tsv | 2 +- crates/ui-egui/src/i18n/de.tsv | 2 +- crates/ui-egui/src/i18n/el.tsv | 2 +- crates/ui-egui/src/i18n/es.tsv | 2 +- crates/ui-egui/src/i18n/fi.tsv | 2 +- crates/ui-egui/src/i18n/fr.tsv | 2 +- crates/ui-egui/src/i18n/gu.tsv | 2 +- crates/ui-egui/src/i18n/hi.tsv | 2 +- crates/ui-egui/src/i18n/hu.tsv | 2 +- crates/ui-egui/src/i18n/id.tsv | 2 +- crates/ui-egui/src/i18n/it.tsv | 2 +- crates/ui-egui/src/i18n/ja.tsv | 2 +- crates/ui-egui/src/i18n/ka.tsv | 2 +- crates/ui-egui/src/i18n/ko.tsv | 2 +- crates/ui-egui/src/i18n/nl.tsv | 2 +- crates/ui-egui/src/i18n/pl.tsv | 2 +- crates/ui-egui/src/i18n/pt-br.tsv | 2 +- crates/ui-egui/src/i18n/ru.tsv | 2 +- crates/ui-egui/src/i18n/sv.tsv | 2 +- crates/ui-egui/src/i18n/tests.rs | 14 ++ crates/ui-egui/src/i18n/tr.tsv | 2 +- crates/ui-egui/src/i18n/uk.tsv | 2 +- crates/ui-egui/src/i18n/vi.tsv | 2 +- crates/ui-egui/src/i18n/zh-hans.tsv | 2 +- crates/ui-egui/src/i18n/zh-hant.tsv | 2 +- crates/ui-egui/src/menus/ui_commands.rs | 2 +- crates/ui-egui/src/panels/navigator.rs | 161 ++++++++++++++++-- crates/ui-egui/src/state.rs | 3 +- docs/mcp.md | 20 ++- docs/target-app-parity.md | 1 + 36 files changed, 207 insertions(+), 54 deletions(-) diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index f81ea2f7f9..feca4b0401 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1097,7 +1097,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.navigatorPanelOptions", "Panel Options…", "", - "{color?: #rrggbb or a preset name (Light Red, the default, then the layer colors such as \"Light Blue\"), solidDashes?: bool (Draw Dashed Lines as Solid Lines, off by default: the Navigator's thumbnail draws dashed strokes without their dashes; the canvas, printing and exports keep them)} set the Navigator panel's options, the color its view box is drawn in and solid dashes (kept with the UI state) → {color, solidDashes}; with neither, open its Panel Options (dialog `navigatorPanelOptions`, fields color, solidDashes; OK sets them); an error for a value that is not a color or not true or false, which changes nothing", + "{color?: #rrggbb or a preset name (Light Red, the default, then the layer colors such as \"Light Blue\"), solidDashes?: bool (Draw Dashed Lines as Solid Lines, off by default: the Navigator's thumbnail draws dashed strokes without their dashes; the canvas, printing and exports keep them), viewArtboardContentsOnly?: bool (View Artboard Contents Only in the panel menu, on by default and for UI state saved without it: the thumbnail fits the artboards and draws only the art inside them, cut at each artboard's edges; off, it also shows the art on the pasteboard)} set the Navigator panel's options, the color its view box is drawn in, solid dashes and artboard contents only (kept with the UI state) → {color, solidDashes, viewArtboardContentsOnly}; with none, open its Panel Options (dialog `navigatorPanelOptions`, fields color, solidDashes; OK sets them); an error for a value that is not a color or not true or false, which changes nothing", ), ( "ui.layersExpand", diff --git a/crates/ui-egui/src/dialogs/navigator_panel_options.rs b/crates/ui-egui/src/dialogs/navigator_panel_options.rs index c3582ae59a..c0988ec548 100644 --- a/crates/ui-egui/src/dialogs/navigator_panel_options.rs +++ b/crates/ui-egui/src/dialogs/navigator_panel_options.rs @@ -85,7 +85,7 @@ mod tests { d.fields.insert("solidDashes".into(), json!(solid)); super::super::confirm(app) }; - assert_eq!(set(&mut app, "Green", true).unwrap(), json!({"color": "#4fff4f", "solidDashes": true})); + assert_eq!(set(&mut app, "Green", true).unwrap(), json!({"color": "#4fff4f", "solidDashes": true, "viewArtboardContentsOnly": true})); assert!(app.ui.dialog.is_none()); app.run("ui.navigatorPanelOptions", json!({})).unwrap(); set(&mut app, "#0000FF", true).unwrap(); diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 754ae856bd..14c1d4c773 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -4012,7 +4012,7 @@ digits Malayalam Малаялам Vertical: Вертикално: Very High Много високо View Изглед - View Artboard Only Преглед само на работна област + View Artboard Contents Only Преглед само на съдържанието на работната област View Opacity Mask Преглед на маска за непрозрачност View PDF after saving Преглед на PDF след запазване View {n} Изглед {n} diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 6c741f000f..3883cb7abf 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -2031,7 +2031,7 @@ digits Malayalam Malajalam Stroke: click for swatches, Shift-click for the color mixer Potez: kliknite za uzorke boja, Shift-klik za mikser boja This panel is on the roadmap (see the parity plan). Ovaj panel je u planu (vidi plan usklađenosti). Open a document to navigate it. Otvorite dokument da se krećete kroz njega. - View Artboard Only Prikaži samo radnu ploču + View Artboard Contents Only Prikaži samo sadržaj radne ploče Contextual Alternates Kontekstualne alternative Default Figure Zadane brojke Discretionary Ligatures Diskrecione ligature diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 2f823c2db0..59650406b6 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -5259,7 +5259,7 @@ digits Malayalam Malaiàlam Update While Dragging Actualitza mentre s’arrossega Video Thumbnail 1280×720 Miniatura de vídeo 1280×720 View Visualitza - View Artboard Only Visualitza només el tauler + View Artboard Contents Only Visualitza només el contingut del tauler View Opacity Mask Visualitza la màscara d’opacitat View PDF after saving Visualitza el PDF després de desar View {n} Vista {n} diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 99a475d96d..4bb0696ae2 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -2104,7 +2104,7 @@ digits Malayalam Malajálamské Stroke: click for swatches, Shift-click for the color mixer Tah: kliknutím otevřete vzorník, Shift+kliknutím míchání barev This panel is on the roadmap (see the parity plan). Tento panel je v plánu (viz plán parity). Open a document to navigate it. Otevřete dokument, abyste v něm mohli navigovat. - View Artboard Only Zobrazit jen pracovní plochu + View Artboard Contents Only Zobrazit jen obsah pracovní plochy Contextual Alternates Kontextové alternativy Default Figure Výchozí číslice Discretionary Ligatures Volitelné ligatury diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 85aed446b2..b32939eaba 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -4596,7 +4596,7 @@ digits Malayalam Malayalam Stroke: click for swatches, Shift-click for the color mixer Kontur: klik for farveprøver, Skift-klik for farveblanderen This panel is on the roadmap (see the parity plan). Dette panel er på vejkortet (se paritetsplanen). Open a document to navigate it. Åbn et dokument for at navigere i det. - View Artboard Only Vis kun tegnebræt + View Artboard Contents Only Vis kun tegnebrættets indhold Contextual Alternates Kontekstuelle alternativer Default Figure Standardcifre Discretionary Ligatures Valgfrie ligaturer diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 091114c55d..7f611d2bc0 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -4070,7 +4070,7 @@ effect Points Punkte Vertical: Vertikal: Very High Sehr hoch View Ansicht - View Artboard Only Nur Zeichenfläche anzeigen + View Artboard Contents Only Nur Inhalt der Zeichenfläche anzeigen View Opacity Mask Deckkraftmaske anzeigen View PDF after saving PDF nach dem Speichern anzeigen View {n} Ansicht {n} diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 560c5a91e3..f737049442 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -4626,7 +4626,7 @@ digits Malayalam Μαλαγιάλαμ Vertical Scale % Κατακόρυφη κλίμακα % Vertical Type on a Path Tool Κατακόρυφο κείμενο σε διαδρομή (Vertical Type on a Path Tool) Very High Πολύ υψηλή - View Artboard Only Προβολή μόνο πίνακα σχεδίασης + View Artboard Contents Only Προβολή μόνο του περιεχομένου του πίνακα σχεδίασης View Opacity Mask Προβολή μάσκας αδιαφάνειας View PDF after saving Προβολή PDF μετά την αποθήκευση View {n} Προβολή {n} diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index ed20179e82..a44c36665b 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -4157,7 +4157,7 @@ digits Malayalam Malayálam Vertical: Vertical: Very High Muy alta View Ver - View Artboard Only Ver solo la mesa de trabajo + View Artboard Contents Only Ver solo el contenido de la mesa de trabajo View Opacity Mask Ver máscara de opacidad View PDF after saving Ver PDF después de guardar View {n} Vista {n} diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index f0b4039c83..f23a412336 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -2065,7 +2065,7 @@ digits Malayalam Malajalam Stroke: click for swatches, Shift-click for the color mixer Viiva: napsauta avataksesi värimallit, Vaihto-napsauta avataksesi värisekoittimen This panel is on the roadmap (see the parity plan). Tämä paneeli on suunnitteilla (katso yhdenmukaisuussuunnitelma). Open a document to navigate it. Avaa asiakirja, niin voit liikkua siinä. - View Artboard Only Näytä vain piirtoalusta + View Artboard Contents Only Näytä vain piirtoalustan sisältö Contextual Alternates Kontekstuaaliset vaihtoehdot Default Figure Oletusnumerot Discretionary Ligatures Valinnaiset ligatuurit diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 06a686c9ce..40efa1d794 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -4144,7 +4144,7 @@ digits Malayalam Malayalam Vertical: Vertical : Very High Très élevée View Affichage - View Artboard Only Afficher le plan de travail uniquement + View Artboard Contents Only Afficher uniquement le contenu du plan de travail View Opacity Mask Afficher le masque d’opacité View PDF after saving Afficher le PDF après l’enregistrement View {n} Vue {n} diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index 9bd0977cb5..fe5c4283dd 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -4258,7 +4258,7 @@ Video વિડિયો Video Ruler Pixel Aspect Ratio: વિડિયો રૂલર પિક્સેલ ગુણોત્તર: View વ્યૂ - View Artboard Only માત્ર આર્ટબોર્ડ જુઓ + View Artboard Contents Only માત્ર આર્ટબોર્ડની સામગ્રી જુઓ View Opacity Mask ઓપેસિટી માસ્ક જુઓ View PDF after saving સાચવ્યા પછી PDF જુઓ Viewing Angle: જોવાનો ખૂણો: diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index b977422495..6f66d52d8f 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -5681,7 +5681,7 @@ antiAlias Sharp शार्प Video Thumbnail 1280×720 वीडियो थंबनेल 1280 × 720 View व्यू View {n} {n} - View Artboard Only केवल आर्टबोर्ड देखें + View Artboard Contents Only केवल आर्टबोर्ड की सामग्री देखें View Opacity Mask ओपेसिटी मास्क देखें View PDF after saving सेव करने के बाद PDF देखें View: व्यू: diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 42a4a81a6b..f92e921a6b 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -4891,7 +4891,7 @@ mark-style Japanese Japán Video Banner 2560×1440 Videós szalagcím 2560×1440 Video Thumbnail 1280×720 Videó-bélyegkép 1280×720 View Nézet - View Artboard Only Csak a rajztábla látszik + View Artboard Contents Only Csak a rajztábla tartalma látszik View Opacity Mask Átlátszósági maszk megtekintése View PDF after saving PDF megtekintése mentés után View {n} Nézet {n} diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index ebd1697020..eff9ea17fe 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -1861,7 +1861,7 @@ digits Malayalam Malayalam Stroke: click for swatches, Shift-click for the color mixer Stroke: klik untuk swatch, Shift+klik untuk pencampur warna This panel is on the roadmap (see the parity plan). Panel ini masih dalam roadmap (lihat rencana paritas). Open a document to navigate it. Buka dokumen untuk menjelajahinya. - View Artboard Only Tampilkan artboard saja + View Artboard Contents Only Tampilkan isi artboard saja Contextual Alternates Alternatif kontekstual Default Figure Angka default Discretionary Ligatures Ligatur opsional diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 147e5bfe35..674e41e30d 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -4204,7 +4204,7 @@ digits Malayalam Malayalam Vertical: Verticale: Very High Molto alta View Visualizza - View Artboard Only Visualizza solo tavola da disegno + View Artboard Contents Only Visualizza solo il contenuto della tavola da disegno View Opacity Mask Visualizza maschera di opacità View PDF after saving Visualizza PDF dopo il salvataggio View {n} Vista {n} diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 6db09e8cfe..9e9090a8c2 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -3697,7 +3697,7 @@ mark-style Japanese 日本式 Vertical Type Tool 縦書き文字ツール Vertical Type on a Path Tool 縦書きパス上文字ツール Vertical: 垂直方向: - View Artboard Only アートボードのみ表示 + View Artboard Contents Only アートボードの内容のみ表示 View Opacity Mask 不透明マスクを表示 View PDF after saving 保存後に PDF を表示 Viewing Angle: 視角: diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 858cb6f296..025af83a8d 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -3919,7 +3919,7 @@ digits Malayalam მალაიალამური Stroke: click for swatches, Shift-click for the color mixer კონტური: დაწკაპეთ ფერის ნიმუშებისთვის, Shift-დაწკაპუნებით — ფერის შემრევისთვის This panel is on the roadmap (see the parity plan). ეს პანელი სამომავლო გეგმაშია (იხ. პარიტეტის გეგმა). Open a document to navigate it. გახსენით დოკუმენტი მასში სანავიგაციოდ. - View Artboard Only მხოლოდ სამუშაო დაფის ჩვენება + View Artboard Contents Only მხოლოდ სამუშაო დაფის შიგთავსის ჩვენება Contextual Alternates კონტექსტური ალტერნატივები Default Figure ნაგულისხმევი ციფრები Discretionary Ligatures დამატებითი ლიგატურები diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index fa8686588f..f8db551d73 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -3686,7 +3686,7 @@ mark-style Japanese 일본식 Vertical Type Tool 세로 문자 도구 Vertical Type on a Path Tool 패스 상의 세로 문자 도구 Vertical: 세로: - View Artboard Only 아트보드만 보기 + View Artboard Contents Only 아트보드 내용만 보기 View Opacity Mask 불투명 마스크 보기 View PDF after saving 저장 후 PDF 보기 Viewing Angle: 시야각: diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 88c247c2f1..e4a4295d24 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -2471,7 +2471,7 @@ digits Malayalam Malayalam Stroke: click for swatches, Shift-click for the color mixer Lijn: klik voor stalen, Shift-klik voor de kleurenmixer This panel is on the roadmap (see the parity plan). Dit paneel staat op de roadmap (zie het pariteitsplan). Open a document to navigate it. Open een document om erin te navigeren. - View Artboard Only Alleen tekengebied weergeven + View Artboard Contents Only Alleen inhoud van tekengebied weergeven Contextual Alternates Contextuele alternatieven Default Figure Standaardcijfer Discretionary Ligatures Optionele ligaturen diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 4e36d0249a..0278fefc17 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -2022,7 +2022,7 @@ digits Malayalam Malajalam Stroke: click for swatches, Shift-click for the color mixer Obrys: kliknij, aby wybrać próbkę, z Shift — mikser kolorów This panel is on the roadmap (see the parity plan). Ten panel jest w planach (patrz plan zgodności). Open a document to navigate it. Otwórz dokument, aby się po nim poruszać. - View Artboard Only Pokaż tylko obszar kompozycji + View Artboard Contents Only Pokaż tylko zawartość obszaru kompozycji Contextual Alternates Alternatywy kontekstowe Default Figure Cyfry domyślne Discretionary Ligatures Ligatury opcjonalne diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index b5dc29791e..463e989c3c 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -3370,7 +3370,7 @@ digits Malayalam Malaiala Vertical Type on a Path Tool Ferramenta Texto Vertical em um Caminho Vertical: Vertical: View Exibir - View Artboard Only Exibir Somente a Mesa de Trabalho + View Artboard Contents Only Exibir Somente o Conteúdo da Mesa de Trabalho View Opacity Mask Exibir Máscara de Opacidade View PDF after saving Exibir PDF após salvar Viewing Angle: Ângulo de Visualização: diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 92bf430f65..561d56b820 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -4189,7 +4189,7 @@ digits Malayalam Малаялам Vertical: По вертикали: Very High Очень высокая View Просмотр - View Artboard Only Просмотр только монтажной области + View Artboard Contents Only Просмотр только содержимого монтажной области View Opacity Mask Просмотр непрозрачной маски View PDF after saving Просматривать PDF после сохранения View {n} Вид {n} diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 7e51593cca..2c912de627 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -4074,7 +4074,7 @@ digits Malayalam Malayalam Vertical: Vertikalt: Very High Mycket hög View Visa - View Artboard Only Visa endast rityta + View Artboard Contents Only Visa endast ritytans innehåll View Opacity Mask Visa opacitetsmask View PDF after saving Visa PDF efter sparning View {n} Vy {n} diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index ed4b44b0da..744ae3cedb 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -570,6 +570,20 @@ fn control_bar_panel_menu_labels_are_in_complete_catalogs() { } } +/// The Navigator panel menu's items are in every complete catalog, and no catalog keeps the +/// item's earlier name, View Artboard Only. +#[test] +fn navigator_panel_menu_labels_are_in_complete_catalogs() { + for lang in LANGUAGES.iter().filter(|lang| lang.complete_menus) { + for label in ["View Artboard Contents Only", "Panel Options…"] { + assert!(lang.catalog().plain(label).is_some(), "{} is missing {label}", lang.code); + } + } + for lang in LANGUAGES.iter() { + assert!(lang.catalog().plain("View Artboard Only").is_none(), "{} keeps View Artboard Only", lang.code); + } +} + /// Document Info's labels: every category title, which the panel and its menu show, every count /// label of the Objects category, and the Document category's fixed row labels (the artboard rows /// show artboard names and are left out). diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index e4dfebabc2..67b87d4d67 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -3926,7 +3926,7 @@ digits Malayalam Malayalam Vertical: Dikey: Very High Çok Yüksek View Görünüm - View Artboard Only Yalnızca Çalışma Yüzeyini Görüntüle + View Artboard Contents Only Yalnızca Çalışma Yüzeyi İçeriğini Görüntüle View Opacity Mask Opaklık Maskesini Görüntüle View PDF after saving Kaydettikten sonra PDF'yi görüntüle View {n} {n}'yi görüntüle diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index b7fe29b0f1..88ed1717f7 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -4197,7 +4197,7 @@ effect Points Точки Vertical: По вертикалі: Very High Дуже висока View Перегляд - View Artboard Only Перегляд лише монтажної області + View Artboard Contents Only Перегляд лише вмісту монтажної області View Opacity Mask Перегляд маски непрозорості View PDF after saving Переглядати PDF після збереження View {n} Вигляд {n} diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 8d8a2176aa..04e007a3ae 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -4577,7 +4577,7 @@ mark-style Japanese Kiểu Nhật Very High Rất cao Video Video View Hiển thị - View Artboard Only Chỉ hiển thị bảng vẽ + View Artboard Contents Only Chỉ hiển thị nội dung bảng vẽ View Opacity Mask Hiển thị mặt nạ độ mờ View PDF after saving Xem PDF sau khi lưu View {n} Hiển thị {n} diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 9499ea301b..91511e0823 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -4034,7 +4034,7 @@ digits Malayalam 马拉雅拉姆数字 Vertical: 垂直: Very High 极高 View 视图 - View Artboard Only 仅查看画板 + View Artboard Contents Only 仅查看画板内容 View Opacity Mask 查看不透明度蒙版 View PDF after saving 存储后查看 PDF View {n} 查看 {n} diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 6402da172c..d6f44597fa 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -5350,7 +5350,7 @@ digits Malayalam 馬來亞拉姆數字 Vertical: 垂直: Very High 極高 View 檢視 - View Artboard Only 僅檢視工作區域 + View Artboard Contents Only 僅檢視工作區域內容 View Opacity Mask 檢視不透明度遮色片 View PDF after saving 儲存後檢視 PDF View {n} 檢視 {n} diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 2b285c704b..62caaeb4fe 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1098,7 +1098,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.navigatorPanelOptions", "Panel Options…", "", - "{color?: #rrggbb or a preset name (Light Red, the default, then the layer colors such as \"Light Blue\"), solidDashes?: bool (Draw Dashed Lines as Solid Lines, off by default: the Navigator's thumbnail draws dashed strokes without their dashes; the canvas, printing and exports keep them)} set the Navigator panel's options, the color its view box is drawn in and solid dashes (kept with the UI state) → {color, solidDashes}; with neither, open its Panel Options (dialog `navigatorPanelOptions`, fields color, solidDashes; OK sets them); an error for a value that is not a color or not true or false, which changes nothing", + "{color?: #rrggbb or a preset name (Light Red, the default, then the layer colors such as \"Light Blue\"), solidDashes?: bool (Draw Dashed Lines as Solid Lines, off by default: the Navigator's thumbnail draws dashed strokes without their dashes; the canvas, printing and exports keep them), viewArtboardContentsOnly?: bool (View Artboard Contents Only in the panel menu, on by default and for UI state saved without it: the thumbnail fits the artboards and draws only the art inside them, cut at each artboard's edges; off, it also shows the art on the pasteboard)} set the Navigator panel's options, the color its view box is drawn in, solid dashes and artboard contents only (kept with the UI state) → {color, solidDashes, viewArtboardContentsOnly}; with none, open its Panel Options (dialog `navigatorPanelOptions`, fields color, solidDashes; OK sets them); an error for a value that is not a color or not true or false, which changes nothing", ), ( "ui.layersExpand", diff --git a/crates/ui-egui/src/panels/navigator.rs b/crates/ui-egui/src/panels/navigator.rs index 60eb4c18d0..927c7912ba 100644 --- a/crates/ui-egui/src/panels/navigator.rs +++ b/crates/ui-egui/src/panels/navigator.rs @@ -2,7 +2,8 @@ //! cached by document revision, off the UI thread for heavy documents and not during drags: see //! [`crate::thumb_worker`]) with the view box you drag to pan, zoom out/in buttons, a zoom slider //! and a zoom field. Panel Options… sets the view box's color and whether the thumbnail draws -//! dashed lines as solid lines ([`PanelOptions`]). +//! dashed lines as solid lines, and the panel menu's View Artboard Contents Only (on by default) +//! limits the thumbnail to the art inside the artboards ([`PanelOptions`]). use std::sync::Arc; @@ -13,7 +14,6 @@ use vectorcraft_color::Color; use vectorcraft_doc::LAYER_COLORS; use vectorcraft_geom::{Point, Rect as DRect}; -use super::{pstate, set_pstate}; use crate::VectorcraftApp; use crate::theme::Tokens; use crate::thumb_worker::{Settle, ThumbWorker}; @@ -39,7 +39,8 @@ pub fn resolve(color: &str) -> Option<[u8; 3]> { Some([byte(0)?, byte(2)?, byte(4)?]) } -/// Navigator panel options (≡ › Panel Options…), kept with the UI state. +/// Navigator panel options (≡ › Panel Options… and ≡ › View Artboard Contents Only), kept with the +/// UI state. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(default, rename_all = "camelCase")] pub struct PanelOptions { @@ -48,12 +49,16 @@ pub struct PanelOptions { /// Draw Dashed Lines as Solid Lines (off by default): the thumbnail draws dashed strokes /// without their dashes. The canvas, printing and exports keep the dashes. pub solid_dashes: bool, + /// View Artboard Contents Only (the panel menu; on by default, and on for UI state saved + /// without it): the thumbnail fits the artboards and draws only the art inside them, cut at + /// each artboard's edges. Off, it also fits and draws the art on the pasteboard. + pub view_artboard_contents_only: bool, } impl Default for PanelOptions { fn default() -> Self { let [r, g, b] = VIEW_BOX_RED; - Self { color: Color::rgb8(r, g, b).to_hex(), solid_dashes: false } + Self { color: Color::rgb8(r, g, b).to_hex(), solid_dashes: false, view_artboard_contents_only: true } } } @@ -65,11 +70,11 @@ impl PanelOptions { } } -/// `ui.navigatorPanelOptions {color?, solidDashes?}`: with neither, open Panel Options on the -/// panel's options; otherwise set the ones given and answer the options. +/// `ui.navigatorPanelOptions {color?, solidDashes?, viewArtboardContentsOnly?}`: with none, open +/// Panel Options on the panel's options; otherwise set the ones given and answer the options. pub fn set_options(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> { - let (color, solid) = (p.get("color"), p.get("solidDashes")); - if color.is_none() && solid.is_none() { + let (color, solid, contents_only) = (p.get("color"), p.get("solidDashes"), p.get("viewArtboardContentsOnly")); + if color.is_none() && solid.is_none() && contents_only.is_none() { return crate::dialogs::navigator_panel_options::open(app); } let mut o = app.ui.navigator_panel.clone(); @@ -84,6 +89,10 @@ pub fn set_options(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> let key = "solidDashes"; o.solid_dashes = s.as_bool().ok_or_else(|| format!("`{key}` must be true or false"))?; } + if let Some(v) = contents_only { + let key = "viewArtboardContentsOnly"; + o.view_artboard_contents_only = v.as_bool().ok_or_else(|| format!("`{key}` must be true or false"))?; + } app.ui.navigator_panel = o; Ok(serde_json::to_value(&app.ui.navigator_panel).unwrap_or_default()) } @@ -218,10 +227,17 @@ impl Cache { } /// How the image `key` names is drawn: as exported (template layers and guides left out), -/// transparent, with images far smaller than they are sampling their mip levels, and with Draw -/// Dashed Lines as Solid Lines, dashed strokes without their dashes. +/// transparent, with images far smaller than they are sampling their mip levels, with Draw +/// Dashed Lines as Solid Lines, dashed strokes without their dashes, and with View Artboard +/// Contents Only, the art cut to the artboards (none in the gaps between them). fn image_options(key: ImageKey) -> vectorcraft_render::RenderOptions { - vectorcraft_render::RenderOptions { skip_templates: true, image_mips: true, solid_dashes: key.solid_dashes, ..Default::default() } + vectorcraft_render::RenderOptions { + skip_templates: true, + image_mips: true, + solid_dashes: key.solid_dashes, + trim: key.artboard_only, + ..Default::default() + } } thread_local! { @@ -296,7 +312,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { super::empty_state(ui, "map", tl!("No document"), tl!("Open a document to navigate it.")); return; }; - let artboard_only: bool = pstate(ui.ctx(), "nav-ab-only"); + let artboard_only = app.ui.navigator_panel.view_artboard_contents_only; let doc = st.doc.clone(); let (uid, revision) = (st.uid, st.revision); // A drag in progress: every pointer move makes a new revision. The image waits for its end. @@ -373,9 +389,9 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { } pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { - let ab: bool = pstate(ui.ctx(), "nav-ab-only"); - if menu_item(ui, tl!("View Artboard Only"), true, ab) { - set_pstate(ui.ctx(), "nav-ab-only", !ab); + let ab = app.ui.navigator_panel.view_artboard_contents_only; + if menu_item(ui, tl!("View Artboard Contents Only"), true, ab) { + app.run("ui.navigatorPanelOptions", json!({"viewArtboardContentsOnly": !ab})).ok(); } if menu_item(ui, tl!("Panel Options…"), true, false) { app.run("ui.navigatorPanelOptions", json!({})).ok(); @@ -547,7 +563,7 @@ mod tests { let shown = || CACHE.with(|c| c.borrow().shown.map(|(k, _)| k.solid_dashes)); assert_eq!(shown(), Some(false)); let set = app.run("ui.navigatorPanelOptions", json!({"color": "light blue", "solidDashes": true})).unwrap(); - assert_eq!(set, json!({"color": "#4f80ff", "solidDashes": true})); + assert_eq!(set, json!({"color": "#4f80ff", "solidDashes": true, "viewArtboardContentsOnly": true})); assert_eq!((boxes(&mut app, red), boxes(&mut app, blue)), (0, 1)); for _ in 0..12 { boxes(&mut app, blue); @@ -560,11 +576,15 @@ mod tests { json!({"color": "#f00"}), json!({"color": null}), json!({"color": "Red", "solidDashes": "yes"}), + json!({"color": "Red", "viewArtboardContentsOnly": "no"}), + json!({"solidDashes": false, "viewArtboardContentsOnly": 0}), + json!({"viewArtboardContentsOnly": null}), ]; for bad in bad { assert!(app.run("ui.navigatorPanelOptions", bad.clone()).is_err(), "{bad}"); } - assert_eq!(serde_json::to_value(&app.ui.navigator_panel).unwrap(), json!({"color": "#4f80ff", "solidDashes": true}), "nothing changed"); + let want = json!({"color": "#4f80ff", "solidDashes": true, "viewArtboardContentsOnly": true}); + assert_eq!(serde_json::to_value(&app.ui.navigator_panel).unwrap(), want, "nothing changed"); app.run("ui.navigatorPanelOptions", json!({"color": "#123456"})).unwrap(); assert!(app.ui.navigator_panel.solid_dashes, "an option left out keeps its value"); } @@ -600,6 +620,113 @@ mod tests { assert_eq!(draw(&line(false), on), solid, "a solid stroke draws as it did"); } + /// View Artboard Contents Only is on by default, and on for UI state saved without it, whether + /// the panel's options are missing or saved before the option existed; a saved off stays off. + #[test] + fn view_artboard_contents_only_is_on_by_default_and_a_saved_off_stays_off() { + assert!(PanelOptions::default().view_artboard_contents_only); + let none: crate::UiState = serde_json::from_value(json!({})).unwrap(); + assert!(none.navigator_panel.view_artboard_contents_only, "UI state saved without the panel's options"); + let older: crate::UiState = serde_json::from_value(json!({"navigator_panel": {"color": "#123456", "solidDashes": true}})).unwrap(); + let o = &older.navigator_panel; + assert!(o.view_artboard_contents_only && o.solid_dashes && o.color == "#123456", "options saved before the option existed: {o:?}"); + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + assert!(app.ui.navigator_panel.view_artboard_contents_only); + let set = app.run("ui.navigatorPanelOptions", json!({"viewArtboardContentsOnly": false})).unwrap(); + assert_eq!(set, json!({"color": "#ff3030", "solidDashes": false, "viewArtboardContentsOnly": false})); + let back: crate::UiState = serde_json::from_value(serde_json::to_value(&app.ui).unwrap()).unwrap(); + assert!(!back.navigator_panel.view_artboard_contents_only, "a saved off stays off"); + } + + /// The panel menu's View Artboard Contents Only starts checked, and a click turns it off (the + /// same option `ui.navigatorPanelOptions` sets), then on again. + #[test] + fn view_artboard_contents_only_is_checked_in_the_panel_menu_and_a_click_toggles_it() { + use crate::widgets::accessibility_tests::{named, tree}; + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + named(&tree(|ui| menu(&mut app, ui)), "✓ View Artboard Contents Only"); + let ctx = egui::Context::default(); + let screen = Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(240.0, 400.0))); + let raw = |events| egui::RawInput { events, screen_rect: screen, ..Default::default() }; + let click = |app: &mut VectorcraftApp| { + let mut out = ctx.run_ui(raw(vec![]), |ui| menu(app, ui)); + out.textures_delta.clear(); + let item = out + .shapes + .iter() + .find_map(|c| match &c.shape { + egui::Shape::Text(t) if t.galley.text().ends_with("View Artboard Contents Only") => Some(t.visual_bounding_rect().center()), + _ => None, + }) + .expect("the menu item"); + let button = + |pressed| egui::Event::PointerButton { pos: item, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + ctx.run_ui(raw(vec![egui::Event::PointerMoved(item), button(true), button(false)]), |ui| menu(app, ui)).textures_delta.clear(); + }; + click(&mut app); + assert!(!app.ui.navigator_panel.view_artboard_contents_only, "a click turns it off"); + named(&tree(|ui| menu(&mut app, ui)), " View Artboard Contents Only"); + click(&mut app); + assert!(app.ui.navigator_panel.view_artboard_contents_only, "a second click turns it on"); + } + + /// With View Artboard Contents Only the thumbnail draws only the art inside the artboards: a + /// shape in the gap between two artboards is left out and one that crosses an artboard's edge + /// is cut there. Without it both draw. + #[test] + fn the_thumbnail_draws_only_the_art_inside_the_artboards_with_the_option() { + use vectorcraft_color::Paint; + use vectorcraft_doc::{Appearance, Document, Node}; + let mut d = Document::new(100.0, 100.0); + let mut second = d.artboards[0].clone(); + second.id = d.artboards.iter().map(|a| a.id).max().unwrap_or(0) + 1; + second.rect = DRect::new(150.0, 0.0, 250.0, 100.0); + d.artboards.push(second); + let l = d.layers[0].id; + for (x0, y0, x1, y1) in [(110.0, 20.0, 140.0, 80.0), (20.0, 80.0, 60.0, 130.0)] { + let mut bp = vectorcraft_geom::BezPath::new(); + bp.move_to((x0, y0)); + bp.line_to((x1, y0)); + bp.line_to((x1, y1)); + bp.line_to((x0, y1)); + bp.close_path(); + let id = d.alloc_id(); + let n = Node::path(id, vectorcraft_geom::PathData::from_bezpath(&bp), Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0)); + d.insert(Some(l), 0, n).unwrap(); + } + let alpha = |artboard_only: bool, x: u32, y: u32| { + let key = ImageKey { uid: 1, revision: 1, w: 260, h: 140, artboard_only, solid_dashes: false }; + vectorcraft_render::Renderer::new().render_region_with(&d, DRect::new(0.0, 0.0, 260.0, 140.0), 1.0, &image_options(key)).pixel(x, y)[3] + }; + assert_eq!([alpha(true, 125, 50), alpha(true, 40, 90), alpha(true, 40, 120)], [0, 255, 0], "the gap and below the artboard are empty"); + assert_eq!([alpha(false, 125, 50), alpha(false, 40, 90), alpha(false, 40, 120)], [255, 255, 255], "all the art draws"); + } + + /// Turning View Artboard Contents Only off makes the thumbnail again, fitted to the art on the + /// pasteboard as well as the artboards; turning it on fits it to the artboards again. + #[test] + fn the_thumbnail_is_made_again_when_view_artboard_contents_only_changes() { + use vectorcraft_engine::Session; + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + app.session.execute("shape.rectangle", &json!({"x": 400, "y": 50, "width": 50, "height": 50})).unwrap(); + let ctx = egui::Context::default(); + let frames = |app: &mut VectorcraftApp| { + for _ in 0..12 { + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| show(app, ui)); + out.textures_delta.clear(); + } + CACHE.with(|c| c.borrow().shown.map(|(k, r)| (k.artboard_only, r.x1))) + }; + let Some((true, right)) = frames(&mut app) else { panic!("an image of the artboards only") }; + assert!(right < 300.0, "fitted to the artboard: {right}"); + app.run("ui.navigatorPanelOptions", json!({"viewArtboardContentsOnly": false})).unwrap(); + let Some((false, right)) = frames(&mut app) else { panic!("an image with the pasteboard's art") }; + assert!(right > 450.0, "fitted to the art on the pasteboard too: {right}"); + app.run("ui.navigatorPanelOptions", json!({"viewArtboardContentsOnly": true})).unwrap(); + assert!(matches!(frames(&mut app), Some((true, r)) if r < 300.0)); + } + #[test] fn zoom_slider_roundtrip() { assert!((zoom_to_slider(3.13)).abs() < 1e-9); diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index d3698aaeef..99ffa98b66 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -850,7 +850,8 @@ pub struct UiState { /// Layers panel › Panel Options… (row size, thumbnails, Show Layers Only, Locate Selected Objects). #[serde(default)] pub layers_panel: crate::panels::layers::PanelOptions, - /// Navigator panel › Panel Options… (the view box color, Draw Dashed Lines as Solid Lines). + /// Navigator panel › Panel Options… (the view box color, Draw Dashed Lines as Solid Lines) and + /// the panel menu's View Artboard Contents Only. #[serde(default)] pub navigator_panel: crate::panels::navigator::PanelOptions, /// The Layers panel's Filter (`ui.layersFilter`). It is not saved and lasts the session, as the diff --git a/docs/mcp.md b/docs/mcp.md index bee07110e6..bd288ee597 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3139,16 +3139,26 @@ dropped. ## Navigator panel options The Navigator panel menu's Panel Options… opens the `navigatorPanelOptions` dialog (fields `color`, `solidDashes`), -and `ui.navigatorPanelOptions {color?, solidDashes?}` sets the options without it → `{color, solidDashes}`; with -neither key it opens the dialog. `color` is the color the panel's view box is drawn in: `#rrggbb` or a preset name. +and `ui.navigatorPanelOptions {color?, solidDashes?, viewArtboardContentsOnly?}` sets the options without it → +`{color, solidDashes, viewArtboardContentsOnly}`; with none of the keys it opens the dialog. `color` is the color the +panel's view box is drawn in: `#rrggbb` or a preset name. The presets are VectorCraft's own list: Light Red (`#ff3030`, the default), then the layer colors ("Light Blue", "Red", "Green" and the rest). `solidDashes` (Draw Dashed Lines as Solid Lines, off by default) makes the panel's -thumbnail draw dashed strokes without their dashes; the canvas, printing and exports keep the dashes. Both are kept -with the UI state. A `color` that is not a color, or a `solidDashes` that is not true or false, is an error and -changes neither option. Behavior reference: [View artwork](https://helpx.adobe.com/illustrator/using/viewing-artwork.html). +thumbnail draw dashed strokes without their dashes; the canvas, printing and exports keep the dashes. +`viewArtboardContentsOnly` is the panel menu's View Artboard Contents Only, on by default: the thumbnail fits the +artboards and draws only the art inside them, so art on the pasteboard and in the gaps between artboards is left out +and a shape that crosses an artboard's edge is cut there. Off, the thumbnail also fits and draws the art outside the +artboards. The view box still shows the canvas's view either way. All three are kept with the UI state and apply to +every document; UI state saved without `viewArtboardContentsOnly` reads it as on, and a saved off stays off. Fitting +the thumbnail to the union of the artboards with a small margin, cutting the art at each artboard, and keeping the +choice with the UI state are VectorCraft's own rules. A `color` that is not a color, or a `solidDashes` or +`viewArtboardContentsOnly` that is not true or false, is an error and changes none of the options. Behavior +references: [View artwork](https://helpx.adobe.com/illustrator/using/viewing-artwork.html) and +[Navigate and zoom artwork](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/navigate-and-zoom-artwork.html). ```json {"name":"invoke_menu","arguments":{"command":"ui.navigatorPanelOptions","params":{"color":"Light Blue","solidDashes":true}}} +{"name":"invoke_menu","arguments":{"command":"ui.navigatorPanelOptions","params":{"viewArtboardContentsOnly":false}}} ``` ## Info panel diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f506da06e1..adb77abd09 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1360,6 +1360,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)). +- **Navigator View Artboard Contents Only:** the Navigator panel menu's View Artboard Contents Only is on by default, and the thumbnail then shows only the art inside the artboards, with art on the pasteboard and in the gaps between artboards left out; turning it off shows the art outside the artboards too (`ui.navigatorPanelOptions {viewArtboardContentsOnly}`; kept with the UI state, read as on when it was never saved; the fit to the artboards' union and the cut at each artboard's edge are VectorCraft's own rules; behavior references: [Navigate and zoom artwork](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/navigate-and-zoom-artwork.html), [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). 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. From d00e3b6ecd70da260f6f5fbd6b1a346864a8b721 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Mon, 16 Nov 2026 11:26:11 -0800 Subject: [PATCH 070/176] Packaging Tools: Fold Preview picks the print level by a pixel's longer side and draws the board opaque A print tipped away from the view shrinks up and down but not across, so the level of the print raster is now chosen by the longer of a pixel's two sides in flat terms, not its width alone, and fine print lines no longer alias when the view is tipped. The board's inside and outside colors were premultiplied by their alpha and then drawn with full alpha, so a see-through color drew darker instead. The depth buffer treats every panel as opaque, so the board is now drawn opaque in its colors' RGB and their alpha is not used. The tray test now checks that each wall's print faces away from the base on its own side and that the walls fold below the base. --- .../src/cmd/addons/packaging/fold/tests.rs | 20 +++++++-- crates/three-d/src/fold/raster.rs | 15 ++++--- crates/three-d/src/fold/raster/tests.rs | 43 +++++++++++++++++++ 3 files changed, 69 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/cmd/addons/packaging/fold/tests.rs b/crates/engine/src/cmd/addons/packaging/fold/tests.rs index da7cd6a84e..4c423021f5 100644 --- a/crates/engine/src/cmd/addons/packaging/fold/tests.rs +++ b/crates/engine/src/cmd/addons/packaging/fold/tests.rs @@ -38,6 +38,14 @@ fn vector(v: &Value) -> [f64; 3] { [a[0].as_f64().unwrap(), a[1].as_f64().unwrap(), a[2].as_f64().unwrap()] } +/// The middle of the bounds of the points of SVG path data `d` (absolute moves and lines only). +fn middle(d: &str) -> [f64; 2] { + let n: Vec<f64> = d.split(|c: char| !(c.is_ascii_digit() || c == '.' || c == '-')).filter_map(|t| t.parse().ok()).collect(); + let span = |k: usize| n.iter().skip(k).step_by(2).fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), &t| (lo.min(t), hi.max(t))); + let ((x0, x1), (y0, y1)) = (span(0), span(1)); + [(x0 + x1) / 2.0, (y0 + y1) / 2.0] +} + fn near(a: [f64; 3], b: [f64; 3]) -> bool { a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-9) } @@ -61,9 +69,15 @@ fn a_tray_folds_its_walls_up_round_the_base() { assert!(panels[base]["outline"].as_str().unwrap().starts_with('M'), "SVG path data"); for (i, p) in panels.iter().enumerate().filter(|(i, _)| *i != base) { assert_eq!((p["parent"].as_u64(), p["depth"].as_u64()), (Some(base as u64), Some(1)), "{p}"); - // Each wall stands square to the base, its print facing out. - let z = vector(&p["frame"]["z"]); - assert!(z[2].abs() < 1e-9 && (z[0].hypot(z[1]) - 1.0).abs() < 1e-9, "wall {i}: {z:?}"); + // Each wall stands square to the base, below it (away from the print), its print facing out: + // away from the base's middle (190, 190), toward the side the wall lies on. + let [cx, cy] = middle(p["outline"].as_str().unwrap()); + let (x, y, o) = (vector(&p["frame"]["x"]), vector(&p["frame"]["y"]), vector(&p["frame"]["origin"])); + let placed: [f64; 3] = std::array::from_fn(|k| o[k] + x[k] * cx - y[k] * cy); + let (dx, dy) = (cx - 190.0, 190.0 - cy); + let out = if dx.abs() > dy.abs() { [dx.signum(), 0.0, 0.0] } else { [0.0, dy.signum(), 0.0] }; + assert!(near(vector(&p["frame"]["z"]), out), "wall {i}: {p}"); + assert!((placed[2] + 20.0).abs() < 1e-9, "wall {i}'s middle is 20 pt below the base: {placed:?}"); } let hinges = r["hinges"].as_array().unwrap(); assert_eq!(hinges.len(), 4); diff --git a/crates/three-d/src/fold/raster.rs b/crates/three-d/src/fold/raster.rs index 012a9621de..e481eee15d 100644 --- a/crates/three-d/src/fold/raster.rs +++ b/crates/three-d/src/fold/raster.rs @@ -179,7 +179,8 @@ impl Print { } /// What [`render`] draws: a folded blank, its print (if any), the color of the board's back and of -/// its printed side where the print has no art (straight RGBA), and the view. +/// its printed side where the print has no art (straight RGBA; the board is opaque, so their alpha +/// is not used), and the view. pub struct Scene<'a> { pub blank: &'a Blank, pub folded: &'a Folded, @@ -356,7 +357,9 @@ impl Fill<'_> { if !wins { continue; } - let footprint = self.flat_at(x + 1.0, y).map_or(0.0, |(u2, v2)| (u2 - u).hypot(v2 - v)); + // The print's footprint is the longer of a pixel's two sides in flat terms. + let across = |dx: f64, dy: f64| self.flat_at(x + dx, y + dy).map_or(0.0, |(u2, v2)| (u2 - u).hypot(v2 - v)); + let footprint = across(1.0, 0.0).max(across(0.0, 1.0)); let color = self.color(u, v, footprint); if let Some(px) = target.color.get_mut(i * 4..i * 4 + 4) { for (o, c) in px.iter_mut().zip(color) { @@ -408,9 +411,9 @@ impl Fill<'_> { } } -fn rgba(c: [u8; 4]) -> [f32; 4] { - let a = f32::from(c[3]) / 255.0; - [f32::from(c[0]) * a, f32::from(c[1]) * a, f32::from(c[2]) * a, f32::from(c[3])] +/// The board color `c` as drawn: its RGB, opaque. +fn opaque(c: [u8; 4]) -> [f32; 4] { + [f32::from(c[0]), f32::from(c[1]), f32::from(c[2]), 255.0] } /// The outline rings of `panel` in flat terms (u, v), flattened finely enough for `scale` pixels a @@ -433,7 +436,7 @@ pub fn render(scene: &Scene) -> Option<Image> { let pixels = width * height; let mut target = Target { width, height, color: vec![0; pixels * 4], depth: vec![f64::NEG_INFINITY; pixels], rank: vec![0; pixels], panel: vec![0; pixels] }; - let (inside, outside) = (rgba(scene.inside), rgba(scene.outside)); + let (inside, outside) = (opaque(scene.inside), opaque(scene.outside)); let near = camera.eye().map(|(eye, _)| eye * NEAREST); for (rank, &pi) in scene.folded.order.iter().enumerate() { let (Some(panel), Some(f)) = (scene.blank.panels.get(pi), scene.folded.panels.get(pi)) else { continue }; diff --git a/crates/three-d/src/fold/raster/tests.rs b/crates/three-d/src/fold/raster/tests.rs index 477040b571..551b671625 100644 --- a/crates/three-d/src/fold/raster/tests.rs +++ b/crates/three-d/src/fold/raster/tests.rs @@ -64,6 +64,49 @@ fn a_flat_panel_takes_the_print_s_color_under_each_pixel() { assert_eq!(pixel(&img, 50, 50), [lit(200.0), lit(100.0), lit(50.0), 255]); } +#[test] +fn the_board_is_opaque_whatever_the_alpha_of_its_colors() { + let shade = 0.6 + 0.4 * 0.74; + let lit = |c: f64| (c * shade).round() as u8; + let (b, f) = scene_of(vec![panel(vec![square(0.0, 0.0, 100.0, 100.0)])], vec![Pose::IDENTITY]); + for a in [0, 128] { + let img = render(&Scene { blank: &b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: [200, 100, 50, a], camera: front() }) + .expect("drawn"); + assert_eq!(pixel(&img, 50, 50), [lit(200.0), lit(100.0), lit(50.0), 255], "outside alpha {a}"); + } + // A transparent inside color draws opaque too, on the nearer of two panels seen from the back. + let whole = || panel(vec![square(0.0, 0.0, 100.0, 100.0)]); + let (b, f) = scene_of(vec![whole(), whole()], vec![Pose::IDENTITY, moved(5.0)]); + let camera = Camera { rotate_y: 180.0, ..front() }; + let img = render(&Scene { blank: &b, folded: &f, print: None, inside: [0, 200, 0, 0], outside: WHITE, camera }).expect("drawn"); + let [r, g, bl, a] = pixel(&img, 50, 50); + assert!(r == 0 && bl == 0 && g > 100 && a == 255, "{:?}", [r, g, bl, a]); +} + +#[test] +fn a_print_squeezed_only_up_and_down_on_screen_samples_a_halved_level() { + // 64 × 64, rows alternating black and white: halved, they average to gray. + let mut px = vec![]; + for y in 0..64 { + for _ in 0..64 { + px.extend(if y % 2 == 0 { [0, 0, 0, 255] } else { [255, 255, 255, 255] }); + } + } + let print = Print::new(Rect::new(0.0, 0.0, 100.0, 100.0), 64, 64, px).expect("a print"); + let (b, f) = scene_of(vec![panel(vec![square(0.0, 0.0, 100.0, 100.0)])], vec![Pose::IDENTITY]); + // Tipped 80°: about 5.8 points a pixel up and down, 1 across. + let camera = Camera { rotate_x: 80.0, ..front() }; + let img = render(&Scene { blank: &b, folded: &f, print: Some(&print), inside: [0; 4], outside: WHITE, camera }).expect("drawn"); + let reds: Vec<u8> = (0..img.height) + .flat_map(|y| (0..img.width).map(move |x| (x, y))) + .filter(|&(x, y)| img.panel_at(x, y).is_some()) + .map(|(x, y)| pixel(&img, x, y)[0]) + .collect(); + assert!(!reds.is_empty()); + let (lo, hi) = (reds.iter().min().copied().unwrap_or(0), reds.iter().max().copied().unwrap_or(0)); + assert!(hi - lo <= 2, "an even gray, not black and white rows: {lo} to {hi}"); +} + #[test] fn the_back_of_a_panel_shows_the_inside_color() { let (b, f) = scene_of(vec![panel(vec![square(0.0, 0.0, 100.0, 100.0)])], vec![Pose::IDENTITY]); From 0b8794042155a5e6d6f4175025abab4d2e76e65d Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Mon, 16 Nov 2026 12:26:26 -0800 Subject: [PATCH 071/176] Packaging Tools: Fold Preview halves the print down to one pixel and reads #-named swatches The print raster stopped after two halvings, so a 2,048-pixel print seen far out sampled a 512-pixel level and fine art aliased. It is now halved down to one pixel, and each halving weighs an odd last row or column by the part of the print it covers, so an edge color does not spread across a small level. A swatch whose name starts with # could not be the inside color, and one named like a hex color drew that hex color. The inside is now looked up as a swatch first and read as #rrggbb only when no swatch with a plain color has that name. --- crates/three-d/src/fold/raster.rs | 40 ++++++++++++++----- crates/three-d/src/fold/raster/tests.rs | 37 ++++++++++++++++- .../ui-egui/src/addons/packaging/preview.rs | 12 +++--- .../src/addons/packaging/preview/tests.rs | 11 ++++- docs/mcp.md | 2 +- 5 files changed, 81 insertions(+), 21 deletions(-) diff --git a/crates/three-d/src/fold/raster.rs b/crates/three-d/src/fold/raster.rs index e481eee15d..9cccbaf6d9 100644 --- a/crates/three-d/src/fold/raster.rs +++ b/crates/three-d/src/fold/raster.rs @@ -115,19 +115,35 @@ impl Level { out } - /// This level at half its size, rounded up, each pixel the mean of the four it covers (an odd - /// last row or column with itself). - fn half(&self) -> Option<Level> { + /// This level at half its size, rounded up, each pixel the mean of the pixels it covers weighted + /// by the area of the full print they cover. A pixel of this level is `step` pixels of the full + /// print (`base` pixels across and down) on a side, and fewer in the last column and row when + /// `base` is not a multiple of `step`. + fn half(&self, base: (u32, u32), step: u32) -> Option<Level> { let (w, h) = (self.width.div_ceil(2), self.height.div_ceil(2)); if (w, h) == (self.width, self.height) { return None; } + // The pixels of the full print that column or row `i` of this level covers, or 0 past it. + let covers = |i: u32, side: u32| u64::from(side).saturating_sub(u64::from(i) * u64::from(step)).min(u64::from(step)) as f32; let mut pixels = Vec::with_capacity(w as usize * h as usize * 4); - for y in 0..i64::from(h) { - for x in 0..i64::from(w) { - let px = [self.at(2 * x, 2 * y), self.at(2 * x + 1, 2 * y), self.at(2 * x, 2 * y + 1), self.at(2 * x + 1, 2 * y + 1)]; - for k in 0..4 { - pixels.push((px.iter().map(|p| p[k]).sum::<f32>() / 4.0).round() as u8); + for y in 0..h { + for x in 0..w { + let mut sum = [0.0f32; 4]; + let mut area = 0.0; + for (sx, sy) in [(2 * x, 2 * y), (2 * x + 1, 2 * y), (2 * x, 2 * y + 1), (2 * x + 1, 2 * y + 1)] { + if sx >= self.width || sy >= self.height { + continue; + } + let a = covers(sx, base.0) * covers(sy, base.1); + let p = self.at(i64::from(sx), i64::from(sy)); + for (s, c) in sum.iter_mut().zip(p) { + *s += c * a; + } + area += a; + } + for s in sum { + pixels.push(if area > 0.0 { (s / area).round() as u8 } else { 0 }); } } } @@ -135,7 +151,8 @@ impl Level { } } -/// The flat print: the document rect it covers and its raster at full size and at two halvings. +/// The flat print: the document rect it covers and its raster at full size and halved again and +/// again down to one pixel. #[derive(Clone, Debug)] pub struct Print { pub region: Rect, @@ -152,9 +169,10 @@ impl Print { return None; } let mut levels = vec![Level { width, height, pixels }]; - while levels.len() < 3 { - let Some(next) = levels.last().and_then(Level::half) else { break }; + let mut step = 1; + while let Some(next) = levels.last().and_then(|l| l.half((width, height), step)) { levels.push(next); + step *= 2; } Some(Print { region, levels }) } diff --git a/crates/three-d/src/fold/raster/tests.rs b/crates/three-d/src/fold/raster/tests.rs index 551b671625..8639615a53 100644 --- a/crates/three-d/src/fold/raster/tests.rs +++ b/crates/three-d/src/fold/raster/tests.rs @@ -177,7 +177,7 @@ fn unusable_views_and_prints_are_refused() { assert!(Print::new(region, MAX_SIDE + 1, 1, vec![0; (MAX_SIDE as usize + 1) * 4]).is_none()); assert!(Print::new(Rect::new(0.0, 0.0, 0.0, 10.0), 1, 1, vec![0; 4]).is_none(), "an empty region"); let p = Print::new(region, 8, 4, vec![255; 8 * 4 * 4]).expect("a print"); - assert_eq!(p.levels.iter().map(|l| (l.width, l.height)).collect::<Vec<_>>(), vec![(8, 4), (4, 2), (2, 1)]); + assert_eq!(p.levels.iter().map(|l| (l.width, l.height)).collect::<Vec<_>>(), vec![(8, 4), (4, 2), (2, 1), (1, 1)]); } #[test] @@ -213,6 +213,41 @@ fn a_print_far_smaller_on_screen_samples_a_halved_level() { assert!((80..=150).contains(&r), "gray, not a black or white column: {r}"); } +#[test] +fn a_print_sixteen_times_smaller_on_screen_samples_a_level_halved_four_times() { + // 64 × 64, columns in bands of 4 alternating black and white: halved twice, they still alternate; + // halved four times, they average to gray. + let mut px = vec![]; + for _ in 0..64 { + for x in 0..64 { + px.extend(if (x / 4) % 2 == 0 { [0, 0, 0, 255] } else { [255, 255, 255, 255] }); + } + } + let print = Print::new(Rect::new(0.0, 0.0, 100.0, 100.0), 64, 64, px).expect("a print"); + assert_eq!(print.levels.len(), 7, "64 down to 1"); + let (b, f) = scene_of(vec![panel(vec![square(0.0, 0.0, 100.0, 100.0)])], vec![Pose::IDENTITY]); + // 100 points in 3 pixels: about 21 print pixels a view pixel. + let camera = Camera { width: 3, height: 3, scale: 0.03, ..front() }; + let img = render(&Scene { blank: &b, folded: &f, print: Some(&print), inside: [0; 4], outside: WHITE, camera }).expect("drawn"); + let [r, ..] = pixel(&img, 0, 1); + assert!((90..=140).contains(&r), "gray, not a black or white band: {r}"); +} + +#[test] +fn a_halved_level_weighs_an_odd_last_column_by_the_area_it_covers() { + // 9 × 9, black but for a white last column: a ninth of the print, so the one-pixel level is + // a ninth white (255 / 9 is about 28), not half. + let mut px = vec![]; + for _ in 0..9 { + for x in 0..9 { + px.extend(if x == 8 { [255, 255, 255, 255] } else { [0, 0, 0, 255] }); + } + } + let print = Print::new(Rect::new(0.0, 0.0, 100.0, 100.0), 9, 9, px).expect("a print"); + assert_eq!(print.levels.iter().map(|l| (l.width, l.height)).collect::<Vec<_>>(), vec![(9, 9), (5, 5), (3, 3), (2, 2), (1, 1)]); + assert_eq!(print.levels.last().map(|l| l.pixels.clone()), Some(vec![28, 28, 28, 255])); +} + #[test] fn the_bounds_take_in_every_folded_panel() { let (b, f) = diff --git a/crates/ui-egui/src/addons/packaging/preview.rs b/crates/ui-egui/src/addons/packaging/preview.rs index a85b8650d9..0b0188f44c 100644 --- a/crates/ui-egui/src/addons/packaging/preview.rs +++ b/crates/ui-egui/src/addons/packaging/preview.rs @@ -183,14 +183,12 @@ thread_local! { static RENDERER: std::cell::RefCell<vectorcraft_render::Renderer> = std::cell::RefCell::new(vectorcraft_render::Renderer::new()); } -/// The board's inside color (straight RGBA) for `inside`: `#rrggbb`, or a swatch of `d` with a -/// plain color; `None` for anything else. +/// The board's inside color (straight RGBA) for `inside`: a swatch of `d` with a plain color, or else +/// `#rrggbb`; `None` for anything else. fn inside_color(d: &vectorcraft_engine::doc::Document, inside: &str) -> Option<[u8; 4]> { - if inside.starts_with('#') { - return vectorcraft_color::Color::from_hex(inside).map(|c| c.to_rgba8(1.0)); - } - match &d.swatch(inside)?.paint { - vectorcraft_color::Paint::Solid { color, .. } => Some(color.to_rgba8(1.0)), + match d.swatch(inside).map(|s| &s.paint) { + Some(vectorcraft_color::Paint::Solid { color, .. }) => Some(color.to_rgba8(1.0)), + _ if inside.starts_with('#') => vectorcraft_color::Color::from_hex(inside).map(|c| c.to_rgba8(1.0)), _ => None, } } diff --git a/crates/ui-egui/src/addons/packaging/preview/tests.rs b/crates/ui-egui/src/addons/packaging/preview/tests.rs index 9fdfb1972e..974556032b 100644 --- a/crates/ui-egui/src/addons/packaging/preview/tests.rs +++ b/crates/ui-egui/src/addons/packaging/preview/tests.rs @@ -5,7 +5,7 @@ use std::sync::Arc; use egui::{Event, Modifiers, PointerButton, Pos2, vec2}; -use super::{Cache, ID, PrintKey, Settings, last_image, last_rect, prints_rendered, show, status, work_done}; +use super::{Cache, ID, PrintKey, Settings, inside_color, last_image, last_rect, prints_rendered, show, status, work_done}; use crate::{VectorcraftApp, menus}; /// An app with a tray blank (a 100 pt base at x 140 to 240, y 140 to 240, and a 40 pt wall on each @@ -123,6 +123,15 @@ fn ui_fold_preview_sets_the_window_and_refuses_bad_values() { // A swatch with a plain color names the inside. app.run("ui.foldPreview", json!({"inside": "White"})).unwrap(); assert_eq!(app.ui.fold_preview.inside, "White"); + // So does one whose name starts with #, and a swatch's name comes before a #rrggbb that reads the same. + app.run("swatch.new", json!({"name": "#brand", "color": "#0000ff"})).unwrap(); + app.run("swatch.new", json!({"name": "#00ff00", "color": "#0000ff"})).unwrap(); + app.run("ui.foldPreview", json!({"inside": "#brand"})).unwrap(); + assert_eq!(app.ui.fold_preview.inside, "#brand"); + let doc = &app.session.active().expect("a document").doc; + assert_eq!(inside_color(doc, "#brand"), Some([0, 0, 255, 255])); + assert_eq!(inside_color(doc, "#00ff00"), Some([0, 0, 255, 255])); + assert_eq!(inside_color(doc, "#ff0000"), Some([255, 0, 0, 255])); } #[test] diff --git a/docs/mcp.md b/docs/mcp.md index ac07dd1799..4aa61fb48b 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -13235,7 +13235,7 @@ and the print is a raster whose longest side is 2,048 pixels, rendered again whe perspective?, inside?, showFoldLines?, base?}`) sets the window, shows it and draws it again. A second run leaves the window open. `rotateX` (-180 to 180) tips the top toward the viewer and `rotateY` (-180 to 180) turns the right side toward the viewer, in degrees; `zoom` is 0.1 to 8, where 1 fits the folded blank; `perspective` is the field of view, 0 to -160 degrees, 0 for none; `inside` is `#rrggbb` or the name of a swatch with a plain color; `base` is a point in a panel +160 degrees, 0 for none; `inside` is the name of a swatch with a plain color, or else `#rrggbb`; `base` is a point in a panel of the document's blanks, or null for the largest panel. With perspective, the zoom of 1 keeps the eye at least twice the folded blank's radius from its middle. A value of the wrong kind or out of range is an error and sets nothing. VectorCraft's own defaults are a Three-Quarter view (`rotateX` 25, `rotateY` 35), no perspective, a white inside and the From 79906094b6182aae49020e96544253bf6777d3ef Mon Sep 17 00:00:00 2001 From: datatimp <12644819+datatimp@users.noreply.github.com> Date: Mon, 16 Nov 2026 16:44:20 -0500 Subject: [PATCH 072/176] Layers panel: an Alt-drag copies a row above or below itself (#8237) --- crates/engine/src/cmd/layer.rs | 8 ++-- crates/engine/src/tests/layers.rs | 21 ++++++++++ crates/ui-egui/src/panels/layers.rs | 6 ++- crates/ui-egui/src/panels/layers/rows.rs | 9 +++- crates/ui-egui/src/panels/layers/tests.rs | 51 +++++++++++++++++++++++ docs/mcp.md | 4 +- docs/target-app-parity.md | 4 +- docs/ui-parity.md | 4 +- 8 files changed, 97 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 83f27cdd61..c4ecbf5d49 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -110,7 +110,7 @@ pub fn specs() -> Vec<CommandSpec> { "Move Rows", [], None, - "{ids|id, target, place?: \"above\"|\"below\"|\"inside\" (default inside), copy?: bool} drag rows in the Layers panel: above or below the target row (beside it, in its layer or group), or inside a layer or group (on top of its contents). Layers go only in layers or at the top level, objects in layers and groups; an object placed beside a top-level layer goes inside it. A row never goes into itself; a locked layer or group takes nothing. `copy` (Alt-drag) moves copies. Every selected object left hidden or locked, such as one moved into a hidden layer or group, is deselected (the key object too). One undo step → {ids}", + "{ids|id, target, place?: \"above\"|\"below\"|\"inside\" (default inside), copy?: bool} drag rows in the Layers panel: above or below the target row (beside it, in its layer or group), or inside a layer or group (on top of its contents). Layers go only in layers or at the top level, objects in layers and groups; an object placed beside a top-level layer goes inside it. A row never goes into itself; a locked layer or group takes nothing. `copy` (Alt-drag) moves copies, which may also go above or below a row they copy (the target among `ids`). Every selected object left hidden or locked, such as one moved into a hidden layer or group, is deselected (the key object too). One undo step → {ids}", has_doc, move_rows ), @@ -773,9 +773,11 @@ fn move_rows(s: &mut Session, p: &Value) -> Result<Value> { if ids.is_empty() { return Err(bad(C, "no such rows")); } - // Never into itself or a row inside it. + // Never into itself or a row inside it. A copy may go above or below one of the rows it + // copies, which a move there would leave where it is (#8237). + let beside_itself = copy && place != Place::Inside && ids.contains(&target); let around = d.ancestry(target).unwrap_or_default(); - if ids.iter().any(|i| around.contains(i)) { + if ids.iter().any(|i| around.contains(i) && !(beside_itself && *i == target)) { return Err(bad(C, "a row can't go into itself")); } let nodes: Vec<&Node> = ids.iter().filter_map(|i| d.node(*i)).collect(); diff --git a/crates/engine/src/tests/layers.rs b/crates/engine/src/tests/layers.rs index f6b35716f6..62eba540d2 100644 --- a/crates/engine/src/tests/layers.rs +++ b/crates/engine/src/tests/layers.rs @@ -643,6 +643,27 @@ fn alt_drag_copies_rows_and_the_selected_art_moves_between_layers() { assert_eq!(s.doc().unwrap().selection.objects, vec![a, g], "it stays selected"); } +/// #8237: a copy may go above or below a row it copies, so a lone layer, the top layer dragged up +/// and the bottom one dragged down can be copied. A move there, or a copy inside the row, is still +/// refused. +#[test] +fn a_copy_goes_above_or_below_a_row_it_copies() { + let mut s = session(); + let layers = |s: &Session| s.doc().unwrap().doc.layers.iter().map(|l| l.id).collect::<Vec<_>>(); + let [only] = layers(&s)[..] else { panic!("one layer") }; + for place in ["above", "below", "inside"] { + assert!(s.execute("layer.move", &json!({"ids": [only.0], "target": only.0, "place": place})).is_err(), "a move {place} itself"); + } + assert!(s.execute("layer.move", &json!({"ids": [only.0], "target": only.0, "place": "inside", "copy": true})).is_err()); + assert_eq!(layers(&s), vec![only], "nothing changed"); + let above = ids(&run(&mut s, "layer.move", json!({"ids": [only.0], "target": only.0, "place": "above", "copy": true}))); + assert_eq!(layers(&s), vec![only, above[0]], "the copy above the original"); + let below = ids(&run(&mut s, "layer.move", json!({"ids": [only.0], "target": only.0, "place": "below", "copy": true}))); + assert_eq!(layers(&s), vec![below[0], only, above[0]], "and one below it"); + run(&mut s, "edit.undo", json!({})); + assert_eq!(layers(&s), vec![only, above[0]], "each copy is one undo step"); +} + /// The selected art in rows dragged into a hidden layer or group is deselected, the key object /// included. Undo puts the rows back and selects the art again. #[test] diff --git a/crates/ui-egui/src/panels/layers.rs b/crates/ui-egui/src/panels/layers.rs index eed20e12cb..48f7a5f624 100644 --- a/crates/ui-egui/src/panels/layers.rs +++ b/crates/ui-egui/src/panels/layers.rs @@ -330,15 +330,17 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { // The column drag: live while it lasts, one undo step when the button is released. let released = ui.input(|i| i.pointer.any_released()); // Layers dragged into the empty space under the last row go below the bottom layer (there is - // no row there to take the drop). + // no row there to take the drop). The bottom layer itself goes there only as an Alt copy, + // which lands below it; moved, it would stay where it is (#8237). let below = list_rect.top() - scrolled.inner.state.clamped_offset().y + list.len() as f32 * view.h; + let alt = ui.input(|i| i.modifiers.alt); if query.is_empty() && !app.ui.layers_filter.is_on() && let Some(drag) = egui::DragAndDrop::payload::<LayersDrag>(ui.ctx()) && let LayersDrag::Rows(ids) = &*drag && let Some(bottom) = doc.layers.first() && !ids.is_empty() - && !ids.contains(&bottom.id) + && (alt || !ids.contains(&bottom.id)) && ids.iter().all(|i| doc.node(*i).is_some_and(Node::is_layer)) && let Some(p) = ui.input(|i| i.pointer.hover_pos()) && list_rect.contains(p) diff --git a/crates/ui-egui/src/panels/layers/rows.rs b/crates/ui-egui/src/panels/layers/rows.rs index 685da495e4..94c3c6c33a 100644 --- a/crates/ui-egui/src/panels/layers/rows.rs +++ b/crates/ui-egui/src/panels/layers/rows.rs @@ -670,15 +670,20 @@ fn drop_target(ui: &Ui, view: &View, n: &Node, r: egui::Rect, indent: f32, open: return; } }; - // Never into itself or a row inside it. + // Never into itself or a row inside it. With Alt, rows held over one of their own rows copy + // beside it, above or below, as `layer.move` places a copy there (#8237). + let alt = ui.input(|i| i.modifiers.alt); + let beside_itself = alt && matches!(&*drag, LayersDrag::Rows(_)) && moving.contains(&n.id); let around = doc.ancestry(n.id).unwrap_or_default(); - if moving.is_empty() || moving.iter().any(|m| around.contains(m)) { + if moving.is_empty() || moving.iter().any(|m| around.contains(m) && !(beside_itself && *m == n.id)) { return; } let Some(p) = ui.input(|i| i.pointer.hover_pos()) else { return }; let rel = (p.y - r.top()) / r.height().max(1.0); let inside = takes(n, &drag, doc); let place = match &*drag { + LayersDrag::Rows(_) if beside_itself && rel < 0.5 => Place::Above, + LayersDrag::Rows(_) if beside_itself => Place::Below, LayersDrag::Art if inside => Place::Inside, LayersDrag::Art => Place::Above, LayersDrag::Rows(_) if inside && rel >= 0.25 && (rel <= 0.75 || open) => Place::Inside, diff --git a/crates/ui-egui/src/panels/layers/tests.rs b/crates/ui-egui/src/panels/layers/tests.rs index a4cd26ac50..69423e68d8 100644 --- a/crates/ui-egui/src/panels/layers/tests.rs +++ b/crates/ui-egui/src/panels/layers/tests.rs @@ -1462,6 +1462,57 @@ fn dragging_a_layer_into_the_empty_space_under_the_rows_moves_it_to_the_bottom() assert_eq!(ids(&app), vec![top, bottom], "the top layer is now the bottom one"); } +/// #8237: with Alt, the top layer dropped on the top edge of its own row copies above itself, and +/// the bottom layer dropped in the empty space under the list copies below itself. Without Alt, +/// neither drop changes anything. +#[test] +fn alt_dragging_the_top_layer_up_or_the_bottom_layer_down_copies_it() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + app.session.execute("layer.new", &json!({"top": true})).unwrap(); + let ids = |app: &VectorcraftApp| app.session.active().unwrap().doc.layers.iter().map(|l| l.id).collect::<Vec<_>>(); + let [bottom, top] = ids(&app)[..] else { panic!("two layers") }; + let ctx = egui::Context::default(); + // Rows: the top layer, the bottom layer, then empty space. + let (circles, _) = frame(&mut app, &ctx, vec![], false); + assert_eq!(circles.len(), 2); + let row = |y: f32| egui::pos2(150.0, y); + let top_edge = |y: f32| egui::pos2(150.0, y - ROW_MEDIUM * 0.4); + let under = |y: f32| egui::pos2(150.0, y + 3.0 * ROW_MEDIUM); + drag(&mut app, &ctx, row(circles[0].y), top_edge(circles[0].y), false); + drag(&mut app, &ctx, row(circles[1].y), under(circles[1].y), false); + assert_eq!(ids(&app), vec![bottom, top], "moved onto their own places, nothing changes"); + drag(&mut app, &ctx, row(circles[0].y), top_edge(circles[0].y), true); + let after = ids(&app); + assert_eq!((after.len(), &after[..2]), (3, &[bottom, top][..]), "a copy above the top layer"); + // Rows: the copy, the top layer, the bottom layer, then empty space. + let (circles, _) = frame(&mut app, &ctx, vec![], false); + assert_eq!(circles.len(), 3); + drag(&mut app, &ctx, row(circles[2].y), under(circles[2].y), true); + let after = ids(&app); + assert_eq!((after.len(), after[1]), (4, bottom), "a copy below the bottom layer"); +} + +/// #8237: a document's only layer, Alt-dragged up onto its own row or down into the empty space, +/// is copied above or below itself. +#[test] +fn a_lone_layer_alt_dragged_up_or_down_is_copied() { + for (up, at) in [(true, 0), (false, 1)] { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 200, "height": 200})).unwrap(); + let ids = |app: &VectorcraftApp| app.session.active().unwrap().doc.layers.iter().map(|l| l.id).collect::<Vec<_>>(); + let [only] = ids(&app)[..] else { panic!("one layer") }; + let ctx = egui::Context::default(); + let (circles, _) = frame(&mut app, &ctx, vec![], false); + assert_eq!(circles.len(), 1); + let y = circles[0].y; + let to = if up { y - ROW_MEDIUM * 0.4 } else { y + 3.0 * ROW_MEDIUM }; + drag(&mut app, &ctx, egui::pos2(150.0, y), egui::pos2(150.0, to), true); + let after = ids(&app); + assert_eq!((after.len(), after[at]), (2, only), "up: {up}"); + } +} + #[test] fn dragging_rows_moves_them_into_other_layers_and_alt_copies() { let (mut app, [layer, sub, g, _, a, c]) = nested(); diff --git a/docs/mcp.md b/docs/mcp.md index bee07110e6..e814470e91 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5372,7 +5372,9 @@ and `layerRows`, the rows highlighted in the panel. - **Dragging rows**: `layer.move {ids, target, place?: above|below|inside, copy?}` moves rows beside a row or into a layer or group (on top of its contents), keeping their stacking order; `copy` (Alt-drag) moves copies. Layers go only in layers or at the top level and objects in layers and groups (an object placed beside a top-level layer goes - inside it); a row never goes into itself or a row inside it, and a locked layer or group takes nothing. Dragging the + inside it); a row never goes into itself or a row inside it, and a locked layer or group takes nothing. With `copy`, + the target may be one of the rows copied: the copies go above or below it, as an Alt-drag onto a row's own row (or a + bottom layer's into the empty space under the list) places them (#8237). Dragging the selected-art square is `layer.move` with the selected objects. `node.move {id, parent?, index}` is the low-level form with the same nesting rules; unlike `layer.move`, it also moves a row into a locked layer or group. - **Buttons**: `layer.new {name?, top?, below?, …options}` (above the current layer at its level; `top` with diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f506da06e1..8397a31f83 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1,6 +1,6 @@ # Parity with Adobe Illustrator -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-16 · **Change:** minor (Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Paragraph composers (#4935): the Paragraph panel menu and paragraph styles offer four composers, the Middle Eastern & South Asian Single-line and Every-line (how all type is set, and the default) and a Standard Single-line and Every-line that set Indic, Arabic and Hebrew type glyph by glyph as the font maps it, for legacy fonts that keep a script on Latin character codes; PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; G5: Neon & Glow joins built-in graphic style libraries (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); scores and estimates unchanged; previously: Pencil ignores Smart Guides and Snap to Point and shows no Smart Guides, #7252; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: G5: Weather Icons joins built-in symbol libraries (Sun, Moon, Cloud, Rain, Thunder, Snow); scores and estimates unchanged; previously: a closed Pencil stroke closes with a straight segment; previously: Snap to Point with Smart Guides off draws no Smart Guides labels or lines, #7250; previously: 3D: the seams of Extrude & Bevel, Inflate and Rotate under a white light, and of the faces of Extrude & Bevel (Classic), Revolve (Classic) and Rotate (Classic), went from miter to round joins, so white-light 3D output is expected to differ from the 2026-10-17 comparison at facet corners (not measured: the scenes were not exported again); previously: `.ai` and EPS import: in layers that don't draw as the page, art that differs away from an envelope of type no longer costs it its editable type; it keeps its drawn art where, in the pixels it and its drawn art ink, the layers with it differ from the page more than its own check allows, or past the envelopes' share of the page check, #7141; Character panel: the Set Font Height Reference dropdown shows an icon before each reference, #6304; scores and estimates unchanged; previously: Envelopes: a top object's side whose pieces are all one curve split at anchors follows that curve's parameter, so a top object saved with its sides' curves in pieces draws as its `.ai` drawn art, #7097; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously minor: Object › Rasterize with the Grayscale or Bitmap colour model makes a grayscale image, #6969; scores and estimates unchanged; previously minor: `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, miter tips and moved strokes included, after its glyphs grown by half its strokes' weight (#6824; #6617: Swatches panel menu: Show Recent Colors; scores unchanged; previously minor: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Type tool: kerning at a caret at the start of a line moves the character after it, #5111; scores and estimates unchanged; previously minor: Rulers: the zero point dragged out of the rulers' corner snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Envelopes: with Distort Appearance, type's strokes paint along the bent glyph outlines at their own weight, as users' `.ai` files draw them, which changes how VectorCraft's own envelopes of stroked type draw (#6644; scores and estimates unchanged); previously minor: G5: Energy Beams brush library; bundled content ~44% → ~46%; previously minor: G5: Skill Icons symbol library; bundled content ~42% → ~44%; previously minor: `.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art (#6570; scores and estimates unchanged); previously minor: ruler double-click adds a guide at the pointer, #5239; G5: Status Effects graphic style library; bundled content ~40% → ~42%; MCP symbol libraries list UI Frames and Map Markers; previously minor: G5: Inventory Icons built-in symbol library; bundled content ~38% → ~40%; previously minor: `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke (#3179; scores and estimates unchanged); previously minor: `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid where VectorCraft's warp doesn't draw as their drawn art (#3179; scores and estimates unchanged); G5: Game Trails brush library; bundled content ~36% → ~38%; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page (#3179; scores and estimates unchanged); G5: Game HUD graphic style library; bundled content ~34% → ~36%; previously minor: Line Arrow arrowhead (#5421; scores and estimates unchanged); G5: Map Markers built-in symbol library; bundled content ~32% → ~34%; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Canvas: a 3D effect changed on type or a group redraws where its solid was; Fit to Artwork Bounds and per-artboard SVG export build each solid once for all artboards; previously minor: Effect Gallery: a thumbnail for each filter and a preview area inside the dialog, on an original drawing; Raster effects 52% → 55%, hours 1–2 → none; headline numbers unchanged; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: UI Frames built-in symbol library with default 9-slice; bundled content ~32%; previously minor: G5: dynamic symbol part on-canvas opacity/blend/gradient/pattern; strokes remaining no longer lists Overlap/auto corners; symbols ~88%; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: harakat paint fallback clarified; previously minor: current Guides feature-area rows consolidated using existing ruler evidence; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap and Pattern brush auto corners removed from strokes remaining; symbols remaining lists dynamic on-canvas beyond solid and guides outside the art; previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; `.ai` and EPS import: older Art brush objects read; numeric fields step on wheel hover without taking keyboard focus, and a panel wheel turn cannot seed a canvas zoom glide, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; the canvas keeps selection outlines and anchors between frames; Indian-language hyphenation review and license allowlist, #4947; Stroke gradients: an arrowhead aligned to the tip is painted to the corners of its base, #5964; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-16 · **Change:** minor (Layers panel: an Alt-drag copies a row above or below itself, so the top layer dragged up, the bottom layer dragged down and a lone layer are copied, #8237; scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Paragraph composers (#4935): the Paragraph panel menu and paragraph styles offer four composers, the Middle Eastern & South Asian Single-line and Every-line (how all type is set, and the default) and a Standard Single-line and Every-line that set Indic, Arabic and Hebrew type glyph by glyph as the font maps it, for legacy fonts that keep a script on Latin character codes; PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; G5: Neon & Glow joins built-in graphic style libraries (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); scores and estimates unchanged; previously: Pencil ignores Smart Guides and Snap to Point and shows no Smart Guides, #7252; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: G5: Weather Icons joins built-in symbol libraries (Sun, Moon, Cloud, Rain, Thunder, Snow); scores and estimates unchanged; previously: a closed Pencil stroke closes with a straight segment; previously: Snap to Point with Smart Guides off draws no Smart Guides labels or lines, #7250; previously: 3D: the seams of Extrude & Bevel, Inflate and Rotate under a white light, and of the faces of Extrude & Bevel (Classic), Revolve (Classic) and Rotate (Classic), went from miter to round joins, so white-light 3D output is expected to differ from the 2026-10-17 comparison at facet corners (not measured: the scenes were not exported again); previously: `.ai` and EPS import: in layers that don't draw as the page, art that differs away from an envelope of type no longer costs it its editable type; it keeps its drawn art where, in the pixels it and its drawn art ink, the layers with it differ from the page more than its own check allows, or past the envelopes' share of the page check, #7141; Character panel: the Set Font Height Reference dropdown shows an icon before each reference, #6304; scores and estimates unchanged; previously: Envelopes: a top object's side whose pieces are all one curve split at anchors follows that curve's parameter, so a top object saved with its sides' curves in pieces draws as its `.ai` drawn art, #7097; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously minor: Object › Rasterize with the Grayscale or Bitmap colour model makes a grayscale image, #6969; scores and estimates unchanged; previously minor: `.ai` and EPS import: type in an envelope with Distort Appearance is also tried mapped from the box of what it paints, miter tips and moved strokes included, after its glyphs grown by half its strokes' weight (#6824; #6617: Swatches panel menu: Show Recent Colors; scores unchanged; previously minor: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Type tool: kerning at a caret at the start of a line moves the character after it, #5111; scores and estimates unchanged; previously minor: Rulers: the zero point dragged out of the rulers' corner snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Envelopes: with Distort Appearance, type's strokes paint along the bent glyph outlines at their own weight, as users' `.ai` files draw them, which changes how VectorCraft's own envelopes of stroked type draw (#6644; scores and estimates unchanged); previously minor: G5: Energy Beams brush library; bundled content ~44% → ~46%; previously minor: G5: Skill Icons symbol library; bundled content ~42% → ~44%; previously minor: `.ai` and EPS import: an envelope saved in Edit Contents whose mesh lies away from its drawn art by a move opens live on that art (#6570; scores and estimates unchanged); previously minor: ruler double-click adds a guide at the pointer, #5239; G5: Status Effects graphic style library; bundled content ~40% → ~42%; MCP symbol libraries list UI Frames and Map Markers; previously minor: G5: Inventory Icons built-in symbol library; bundled content ~38% → ~40%; previously minor: `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke (#3179; scores and estimates unchanged); previously minor: `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid where VectorCraft's warp doesn't draw as their drawn art (#3179; scores and estimates unchanged); G5: Game Trails brush library; bundled content ~36% → ~38%; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: `.ai` and EPS import: envelopes of type open live where they draw as their drawn art and the layers with them draw as the page (#3179; scores and estimates unchanged); G5: Game HUD graphic style library; bundled content ~34% → ~36%; previously minor: Line Arrow arrowhead (#5421; scores and estimates unchanged); G5: Map Markers built-in symbol library; bundled content ~32% → ~34%; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Canvas: a 3D effect changed on type or a group redraws where its solid was; Fit to Artwork Bounds and per-artboard SVG export build each solid once for all artboards; previously minor: Effect Gallery: a thumbnail for each filter and a preview area inside the dialog, on an original drawing; Raster effects 52% → 55%, hours 1–2 → none; headline numbers unchanged; Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; G5: UI Frames built-in symbol library with default 9-slice; bundled content ~32%; previously minor: G5: dynamic symbol part on-canvas opacity/blend/gradient/pattern; strokes remaining no longer lists Overlap/auto corners; symbols ~88%; previously minor: interim macOS cursor delivery, #2292; native validation pending; scores and estimates unchanged; previously minor: harakat paint fallback clarified; previously minor: current Guides feature-area rows consolidated using existing ruler evidence; scores and estimates unchanged; previously minor: Control bar › Snapping includes the existing Snap to Glyph and Alignment Guides toggles (#6164); scores and estimates unchanged; previously minor: G5 docs: Art brush Overlap and Pattern brush auto corners removed from strokes remaining; symbols remaining lists dynamic on-canvas beyond solid and guides outside the art; previously minor: custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: EPS import: embedded fonts (composite, Type 42, CID-keyed, Type 1, CFF FontSet) draw their glyphs; spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; `.ai`/EPS type keeps its tab stops, and right-aligned lines with tabs lay out as the file's page, #6147; `.ai`/EPS type from the text document lays its lines out closer to the file's page, within limits, #6137; `.ai` and EPS import: older Art brush objects read; numeric fields step on wheel hover without taking keyboard focus, and a panel wheel turn cannot seed a canvas zoom glide, #5949; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen; Tools stays beside the canvas with left-side panels; new gradients follow document color mode; Selection QoL: marquee modes and visible feedback, #5313; SVG CSS classes survive export and repeated import in all four styling modes (#2480); current-main integration retains event attributes and scripts; #3380 deletion-only review follow-up: independent survivors keep gradient placement, owned subpaths avoid discarded copies, and contracts/status/evidence are clarified; endpoint highlighting remains open; scores and estimates unchanged; the canvas keeps selection outlines and anchors between frames; Indian-language hyphenation review and license allowlist, #4947; Stroke gradients: an arrowhead aligned to the tip is painted to the corners of its base, #5964; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Hindi catalog and contributor loanword preferences; full wording review in progress; Properties in Edit Artboards: a Transform section with the reference point above the Artboards section, #5219; the Control bar's Stroke: and Opacity: links scrub their fields, #4088; an image zoomed in on is separated, colorized or proofed only where it shows (#4155); a document's first frame renders on the render worker, so opening a heavy file no longer freezes the window, #4155; Control bar Paragraph section with type selected, #5372; translating unchanged type reuses its glyph and character-stroke outlines; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; public release notes through 30.7, August 2026; Units › East Asian Type acts, with Q and Ha units; scores unchanged) > > Tech Circuit update (2026-11-14): three original procedural brushes; ten built-in brush libraries (G5). > @@ -960,6 +960,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Screen readers get the value of the color and channel sliders that panels and dialogs draw (the Color panel, the Color Picker, Swatch Options, the Navigator's Zoom, the Character panel's variable font axes, the Perspective Grid and flattener options, and the sliders of the effect, tool option and transform dialogs): the number and text of the field beside each one, such as 128 for G or 50% for an opacity, with the slider's range, which extends to include a number past the slider's end. The harmony wheel's Brightness slider, which has no field, reports its brightness in percent. - A layer whose Layer Options › Print is off shows its name italic in the Layers panel, and while its row is dragged, as the reference application shows non-printing layers (#5739); a printing layer stays upright and ticking Print again restores the upright name (`panels::layers` test `a_layer_that_does_not_print_has_its_name_italic`). - In the Layers panel only the primary mouse button drags. A drag with the right or middle button on a row, a guide row, the selection square, the eye or lock column or a target circle moves, copies, hides, locks and transfers nothing and records no undo step, and a right-click still opens the row's menu (`panels::layers` test `only_the_primary_button_drags_rows_guides_art_columns_and_appearances`). + - An Alt-drag in the Layers panel copies rows above or below one of their own rows (`layer.move` with `copy` and that row as the target), and the bottom layer Alt-dragged into the empty space under the list is copied below itself. So the top layer dragged up, the bottom layer dragged down and a document's only layer are copied, as any other row is. A move onto its own place, and a copy inside itself, still change nothing (#8237; `panels::layers` tests `alt_dragging_the_top_layer_up_or_the_bottom_layer_down_copies_it` and `a_lone_layer_alt_dragged_up_or_down_is_copied`; engine test `a_copy_goes_above_or_below_a_row_it_copies`). - Rows dragged in the Layers panel and held within 28 points of the list's top or bottom edge scroll a long list that way, faster nearer the edge (60 points a second at the band's inner side, 340 at the edge, at every frame rate), and keep scrolling while the pointer stays still, so a row out of view can take the drop (a move, or a copy with Alt); the Libraries panel's list scrolls by the same rule. In a list view shorter than 56 points each band is half the view, so a pointer in the top half scrolls up, one in the bottom half scrolls down, and a pointer just outside the view does not scroll it toward the far edge. A pointer beside the list, a drag of the eye or lock column and a release stop the scrolling, and scrolling changes nothing in the document. The band and speeds are VectorCraft's own (`panels::layers` tests `rows_held_near_the_bottom_or_top_edge_scroll_the_list_to_a_row_out_of_view`, `a_held_row_scrolls_the_list_as_far_in_the_same_time_at_any_frame_rate` and `the_list_scrolls_only_for_rows_held_over_it`; `panels` test `drag_scrolling_in_a_short_list_goes_toward_the_nearer_edge`). - The other panels' item drags start only with the primary mouse button too: swatches and color groups, brushes, symbols, graphic styles, library items and groups, character and paragraph styles, Appearance rows and its thumbnail, the Fill and Stroke squares, Recent Colors and the Gradient panel's thumbnail. A right or middle drag on one carries nothing, moves, copies, deletes and applies nothing and records no undo step; right-click menus and the Graphic Styles panel's held right-button preview stay as they were (`panels::swatches` test `only_a_primary_drag_moves_swatches_and_groups`, `panels::text_styles` test `only_a_primary_drag_carries_a_style_row`, `panels::tests_symbol_libraries` test `only_a_primary_drag_carries_a_library_symbol_out`, `panels::tests_effectedit` test `only_a_primary_drag_carries_the_thumbnail_or_a_row`). - Panels undock (#495): a dock tab, a panel icon or a popped-out panel's title dragged out of the dock floats that panel (in an OS window of its own on the desktop, #4135), and the strip right of the dock's tabs floats the whole tabbed group. A floating group moves by its title bar, a tab dragged out of it floats on its own, and dropped on another group's title bar or tabs it stacks with that group; dropped on a dock group's tabs, which light up under the pointer, its panels join that group, and on the group's upper or lower half they make a new group above or below it (`window.panel.dock {anchor, zone}`); dropped on the icon column they become icons there, the tabbed group's panels too (`window.panel.dock {icon: true}`); dropped anywhere else on the dock, which lights up, they go back where they live (the tabbed group or the icon column), as its × and the panel menus' Float Panel / Dock Panel do (`window.panel.float`, `window.panel.dock`). The Tools panel floats by its title bar and docks again on the window's left edge. Floating groups stack into sets: dropped on the upper or lower half of another group (a line shows where), a group joins it right above or below it, and the set's groups stack top to bottom, each showing one panel, moving together by the top group's title bar, whose × docks them all; a group dragged by its tab strip leaves the set (`window.panel.float {below, above}`). A double-click on a tab collapses a floating group to its tabs (`collapsed`), and a dock group too, a group below it moving up into the room; a second double-click, or a click on another of its tabs, expands it (`window.panel.collapse`, kept with the preferences and in saved workspaces). Sets dropped on the left edge of the icon column or of another dock column dock as dock columns (a multi-column dock, `window.panel.dock {column}`), whose groups stack, tab and tear out as a floating set's do, and whose top strip floats the column again. Floating panels, their sets and the Tools panel's position are kept with the preferences and in user workspaces, and clamped into a smaller window. Not done: panels in separate OS windows, reordering tabs by dragging, collapsing a set or dock column to icons, dock columns right of the default dock, resizing floating panels and the groups of a set. @@ -2709,6 +2710,7 @@ Edit › Copy and Cut put the selected ruler guides on the clipboard, with the s | Date | Change | Summary | |---|---|---| +| 2026-11-16 | minor | Layers panel: an Alt-drag copies a row above or below its own place (`layer.move` with `copy` and that row as the target), so the top layer dragged up, the bottom layer dragged down and a document's only layer are copied (#8237). Scores and estimates unchanged. | | 2026-11-16 | minor | Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged. | | 2026-11-16 | minor | Color panel: the spectrum fills the vertical space of a resized panel, with options shown or hidden (#8005). Compact auto-fit flyouts and embedded mixers keep their existing size. Evidence: panels::color::tests::the_spectrum_grows_with_the_color_panel. Scores and estimates unchanged. | | 2026-11-14 | minor | Paragraph composers (#4935): `text.setFormat {composer}` and paragraph styles take `singleLine` and `everyLine` (the Middle Eastern & South Asian composers, what all type used and the default) and `standardSingleLine` and `standardEveryLine`, which break lines the same way and set a complex script (Indic, Arabic, Hebrew) glyph by glyph as the font maps its characters, with no conjuncts, reordering, marks placed or joining forms. The choice is per paragraph, saved in the native file only when it is not Every-line, and not written to `.ai`, EPS or PDF files, whose composer setting this app has no recorded format for. Scores and estimates unchanged. Tests `tests::composers`. | diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 17a00368b5..99fa13d48f 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI and interaction parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-16 · **Change:** minor (Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Remove Background in the Contextual Task Bar, Properties › Quick Actions and the Control bar; previously minor: Ruler origin: the corner drag snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Outline view: images and gradient meshes are picked on what Outline draws, so a click inside them reaches the path behind, #6437; previously minor: a middle-click on a document tab closes it, #6506; previously minor: Blob Brush: a round tip's preview is the outline of the area it adds, round at both ends, as the stroke it commits (#4343); scores and estimates unchanged; previously:; ruler double-click adds a guide at the pointer, #5239; G5: Inventory Icons built-in symbol library (four built-ins); previously minor: files that record no units open in Preferences › Units › General, #5820; previously minor: 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; floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; 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; #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; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Layers: Rename (`ui.rename`) opens the name field of the selected layer, group or object, #5324; Properties in Edit Artboards: Transform section above the Artboards section, #5219; scrubby labels: the Control bar's Stroke: and Opacity: links and the Properties panel's Stroke link scrub their fields, #4088; Properties: Quick Actions has Repeat Options for one selected repeat, #5181; Direct Selection: Shift-click picks several blend spine points, which drag together, #5285; Direct Selection: Cmd/Ctrl held lends the Selection tool and shows its bounding box, #3901; Join tool trims two crossing open paths and joins them at the crossing, #5844; Control bar: Paragraph: link and Align left/center/right while type is selected, #5372; shape tools: a press on the selection's centre point moves it and one in the rotate zone outside a box corner turns it, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-16 · **Change:** minor (Layers panel: an Alt-drag copies a row above or below itself, so the top layer dragged up, the bottom layer dragged down and a lone layer are copied, #8237; scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: Pencil continuation, straight-line and closing cursors; scores and estimates unchanged; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: macOS: the canvas cursor stays after the pointer moves, #6362; scores and estimates unchanged; previously minor: Remove Background in the Contextual Task Bar, Properties › Quick Actions and the Control bar; previously minor: Ruler origin: the corner drag snaps as a drawn point does; previously minor: Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: Outline view: images and gradient meshes are picked on what Outline draws, so a click inside them reaches the path behind, #6437; previously minor: a middle-click on a document tab closes it, #6506; previously minor: Blob Brush: a round tip's preview is the outline of the area it adds, round at both ends, as the stroke it commits (#4343); scores and estimates unchanged; previously:; ruler double-click adds a guide at the pointer, #5239; G5: Inventory Icons built-in symbol library (four built-ins); previously minor: files that record no units open in Preferences › Units › General, #5820; previously minor: 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; floating tab groups collapse into the side icon rail and opened rail panels fold back into it, #5925 in part; 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; #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; Drop Shadow and glow dialogs: spinner arrows, #5367, #5368; Stroke Weight Up and Down shortcuts, #5797; Layers: Rename (`ui.rename`) opens the name field of the selected layer, group or object, #5324; Properties in Edit Artboards: Transform section above the Artboards section, #5219; scrubby labels: the Control bar's Stroke: and Opacity: links and the Properties panel's Stroke link scrub their fields, #4088; Properties: Quick Actions has Repeat Options for one selected repeat, #5181; Direct Selection: Shift-click picks several blend spine points, which drag together, #5285; Direct Selection: Cmd/Ctrl held lends the Selection tool and shows its bounding box, #3901; Join tool trims two crossing open paths and joins them at the crossing, #5844; Control bar: Paragraph: link and Align left/center/right while type is selected, #5372; shape tools: a press on the selection's centre point moves it and one in the rotate zone outside a box corner turns it, #5477; scores and estimates unchanged) · **Target:** Adobe Illustrator 2026 (30.x; Units › East Asian Type acts, with Q and Ha units; scores unchanged) > > Tech Circuit update (2026-11-14): three original procedural brushes; ten built-in brush libraries (G5). > @@ -56,6 +56,7 @@ Artboard Options forwards the active Artboard tool's Scale Artwork with Artboard | 2026-11-09 | minor | Document Setup and Character panel Language lists: Nepali, Konkani and Sindhi complete #4943; Assamese and Sanskrit are already present from #5946. Names in all 27 catalogs come from [CLDR locale language-name data](https://github.com/unicode-org/cldr/tree/main/common/main). The public [language assignment documentation](https://helpx.adobe.com/illustrator/using/spelling-language-dictionaries.html) describes the Character panel Language menu, but does not establish that these five languages are listed there; inclusion and a single Sindhi entry remain maintainer decisions. Scores unchanged | | 2026-11-14 | minor | G5: Tech Circuit adds three original procedural brushes (Circuit Trace, Bus Lines, Terminal Nodes); ten built-in brush libraries. G5 remaining estimate 3–13 h (estimated); parity scores and headline totals unchanged. | | 2026-11-14 | minor | Layers panel: right-clicking a layer/group/object row shows a context menu with Options…, Duplicate, Delete, Lock/Hide Others, Locate Object, and Collect for Export — matching standard desktop layer panel conventions. Scores unchanged. | +| 2026-11-16 | minor | Layers panel: an Alt-drag copies a row above or below its own place, so the top layer dragged up, the bottom layer dragged down and a document's only layer are copied (#8237). Scores and estimates unchanged. | | 2026-11-13 | minor | Pencil cursors: the continuation cursor (a short rising line) shows over an open end of a selected path before any press, freehand too, and while a continuing stroke nears another selected path's open end it connects to; the straight-line cursor is a short level line; a continued path, a straight line too, shows the closing cursor and closes within Close Paths When Ends Are Within of its other end, and with Alt at the release. Scores and estimates unchanged. | | 2026-11-15 | minor | G12: Swatches item menus validated in all five views: 39 focused tests passed, regression fails without the menu hooks, rendered list/thumbnail layouts inspected, and fresh local deep CodeRabbit review found zero issues. Full workspace CI passed on Linux/WSL on the merged branch (all 13 gates), including the test-helper correction for the upstream compile error tracked in #7727; native Windows full CI has two unchanged engine-test failures. Scores and estimates unchanged. | | 2026-11-13 | minor | Graphic Styles: in a panel made taller the list fills the space above the footer instead of stopping at 220 pt (#2992; `the_list_fills_a_tall_panel_above_its_footer` in `crates/ui-egui/src/panels/graphic_styles.rs`). Scores and estimates unchanged. | @@ -182,6 +183,7 @@ tools, never checked side by side) isn't captured row by row. | Swatches list fills a taller panel (#1638) | done | Docked, floating or in a resized flyout, the swatch list takes the height above the panel's footer, as the Artboards list does; outside a sized panel it stays 150 pt (200 pt for large thumbnails); `the_list_fills_a_tall_panel_above_its_footer` in `panels/swatches/tests.rs` | | 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` | +| Layers panel: Alt-drag copies a row beside itself (#8237) | done | with Alt, rows held over one of their own rows copy above or below it, and the bottom layer dropped in the empty space under the list copies below itself, so the top layer dragged up, the bottom one dragged down and a document's only layer are copied; a move onto its own place, or a copy inside itself, still does nothing; `panels::layers` tests `alt_dragging_the_top_layer_up_or_the_bottom_layer_down_copies_it`, `a_lone_layer_alt_dragged_up_or_down_is_copied`; engine test `a_copy_goes_above_or_below_a_row_it_copies` | | 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 | | Several blend spine points picked and dragged together (#5285) | done | with Direct Selection, Shift-click picks more points of a selected blend's spine or takes one away, as on a path; dragging any picked point moves them all, and the key objects on them, in one undo step (`object.blend.spine.moveAnchor {with}`); a marquee picks the spine points inside it on the topmost selected blend, and with Shift adds or takes them away | | Add/Delete/Anchor Point tools; Anchor Point tool drags segments to reshape | done | #2267: a click on a handle end retracts that handle and leaves the anchor a corner with the other one; Shift held at the press on an anchor moves it, handles and all (Shift kept down: at 45° steps) instead of pulling out handles | From ea69ba0b97bb71d3d59ceb94c2bfd2ac918fa4a1 Mon Sep 17 00:00:00 2001 From: datatimp <12644819+datatimp@users.noreply.github.com> Date: Mon, 16 Nov 2026 17:52:20 -0500 Subject: [PATCH 073/176] Layers: a c opy never goes inside a top-level layer it copies; roadmap row (#8237) --- crates/engine/src/cmd/layer.rs | 5 +++++ crates/engine/src/tests/layers.rs | 18 ++++++++++++++++++ docs/roadmap.md | 3 ++- 3 files changed, 25 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index c4ecbf5d49..66a115e91c 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -789,6 +789,11 @@ fn move_rows(s: &mut Session, p: &Value) -> Result<Value> { parent => (parent, Some(target)), }, }; + // A copy beside a top-level layer it copies, with objects among the rows, would go inside + // that layer: into itself. + if parent.is_some_and(|p| ids.contains(&p)) { + return Err(bad(C, "a row can't go into itself")); + } if let Some(n) = nodes.iter().find(|n| !accepts(d, parent, n)) { let into = parent.and_then(|p| d.node(p)).map_or("the top level", |p| if p.is_layer() { "a layer" } else { p.kind_label() }); return Err(bad(C, format!("{} can't go into {into}", n.display_name()))); diff --git a/crates/engine/src/tests/layers.rs b/crates/engine/src/tests/layers.rs index 62eba540d2..ba1d0a5140 100644 --- a/crates/engine/src/tests/layers.rs +++ b/crates/engine/src/tests/layers.rs @@ -664,6 +664,24 @@ fn a_copy_goes_above_or_below_a_row_it_copies() { assert_eq!(layers(&s), vec![only, above[0]], "each copy is one undo step"); } +/// #8237 review: rows that hold an object can't sit beside a top-level layer, so copied beside a +/// top-level layer among them they would go inside it: a copy of that layer inside itself. Refused, +/// and nothing changes. +#[test] +fn a_copy_with_objects_beside_a_copied_top_level_layer_is_refused() { + let mut s = session(); + let bottom = s.doc().unwrap().doc.layers[0].id; + let other = id(&run(&mut s, "layer.new", json!({}))); + let r = rect(&mut s, 0.0); + assert_eq!(s.doc().unwrap().doc.parent_of(r), Some(other), "the rectangle is in the other layer"); + let count = s.doc().unwrap().doc.node_count(); + for place in ["above", "below"] { + let p = json!({"ids": [bottom.0, r.0], "target": bottom.0, "place": place, "copy": true}); + assert!(s.execute("layer.move", &p).is_err(), "{place}: the layer's copy would go inside it"); + } + assert_eq!(s.doc().unwrap().doc.node_count(), count, "nothing copied"); +} + /// The selected art in rows dragged into a hidden layer or group is deselected, the key object /// included. Undo puts the rows back and selects the art again. #[test] diff --git a/docs/roadmap.md b/docs/roadmap.md index e10e3adae2..8cbe973719 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-16 · **Change:** minor (Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: M7: Check Spelling modal dialog (Edit › Spelling › Check Spelling…), #4936; spell check complete; previously: PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; M10/G5: Neon & Glow built-in graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); previously: Tech Circuit brush library, G5; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: M10/G5: Energy Beams brush library; MCP docs list Energy Beams; previously minor: M10/G5: Skill Icons symbol library; MCP docs list Skill Icons; previously minor: M10/G5: Status Effects graphic style library; MCP docs catch-up for symbol libraries; previously minor: M10/G5: Inventory Icons built-in symbol library; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously 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) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-16 · **Change:** minor (M1: an Alt-drag in the Layers panel copies a row above or below its own place, #8237; scores and estimates unchanged; previously: Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged; previously: #8005: the Color spectrum fills a resized panel; scores and estimates unchanged; previously: M7: Check Spelling modal dialog (Edit › Spelling › Check Spelling…), #4936; spell check complete; previously: PDF import: stroked type keeps the line cap, line join and miter limit the file strokes it with, a glyph stroked otherwise than the run it joins coming in as a run of its own, #7741; M10/G5: Neon & Glow built-in graphic style library (Cyan Neon, Magenta Laser, Amber Tube, Electric Lime, Pulse Violet, Cobalt Phosphor); previously: Tech Circuit brush library, G5; previously: Graphic Styles list fills a taller panel, #2992; scores and estimates unchanged; previously: PDF import: glyphs in a span with an empty ActualText come in as outlines, #6971; scores and estimates unchanged; previously: library panels' lists fill a taller panel, #2992; scores and estimates unchanged; previously: Swatches list fills a taller panel, #1638; scores and estimates unchanged; previously: icon-strip flyouts also resize from the top edge and the canvas-side top corner, keeping the moved top in workspaces (storytold/craft-libs#1094); scores and estimates unchanged; previously: #6865: explicitly requested oversized editing artboard; Live Paint Bucket fills faces crossed in one drag (#6373); previously: #6404: transform-aware Eyedropper character copying; scores and estimates unchanged; previously: M10/G5: Energy Beams brush library; MCP docs list Energy Beams; previously minor: M10/G5: Skill Icons symbol library; MCP docs list Skill Icons; previously minor: M10/G5: Status Effects graphic style library; MCP docs catch-up for symbol libraries; previously minor: M10/G5: Inventory Icons built-in symbol library; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously 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) > > Oversized artboard import update (2026-11-12): Explicit editing-data import retains a single artboard beyond a capped 14,400 pt PDF page (#6865). > @@ -212,6 +212,7 @@ not take the artwork yet. Overflow-menu drag remains separate. Scores and hours | Date | Change | Summary | |---|---|---| +| 2026-11-16 | minor | M1: an Alt-drag in the Layers panel copies a row above or below its own place (`layer.move` with `copy` and that row as the target), so the top layer dragged up, the bottom layer dragged down and a document's only layer are copied (#8237). Scores and estimates unchanged. | | 2026-11-16 | minor | Recolor Artwork follow-up (#8031, remaining #4028): native Lab input, picker swatch libraries and Assign-row menus; UI interaction regression coverage; scores and estimates unchanged. | | 2026-11-16 | minor | Color panel: the spectrum fills the vertical space of a resized panel, with options shown or hidden (#8005). Compact auto-fit flyouts and embedded mixers keep their existing size. Evidence: panels::color::tests::the_spectrum_grows_with_the_color_panel. Scores and estimates unchanged. | | 2026-11-15 | minor | PDF import: stroked type (text rendering modes 1, 2, 5 and 6, and glyphs under `ActualText`) keeps the line cap, line join and miter limit of the graphics state it is stroked with, as paths do, instead of butt caps, miter joins and a miter limit of 10; a glyph filled and then stroked otherwise than the run its fill joined comes in as a run of its own, so the glyphs before it keep their stroke (#7741; `imported_stroked_type_keeps_the_files_cap_join_and_miter_limit` in `crates/pdf/src/tests/textstroke.rs`). Scores and estimates unchanged. | From b33409d1a5470ea886052951b4e129a661e39bfe Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Mon, 16 Nov 2026 15:56:02 -0800 Subject: [PATCH 074/176] MCP: the headless UI catalog lists ui.foldPreview Regenerated crates/mcp/src/ui_catalog.rs with `cargo xtask ui-commands` so it matches the ui.foldPreview row in crates/ui-egui/src/menus/ui_commands.rs. --- crates/mcp/src/ui_catalog.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index f81ea2f7f9..784ebbf11b 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1147,6 +1147,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{highlight?: none|rasterizedRegions|transparentObjects|allAffected|expandedPatterns|outlinedStrokes|outlinedText|allRasterized, overprints?: preserve|simulate|discard, preset?: name (loads its options), options?: {option keys, over the preset's}, showOptions?} set the Flattener Preview panel (ui.inspect: ui.flattener_preview), show it and refresh its snapshot → what flattener.preview answers for it", ), + ( + "ui.foldPreview", + "Fold Preview", + "", + "{amount?: 0..1 (how far the blank is folded), view?: front|back|left|right|top|bottom|threeQuarter, rotateX?: deg -180..180 (the top toward the viewer), rotateY?: deg -180..180 (the right side toward the viewer), zoom?: 0.1..8 (1 fits the folded blank), perspective?: deg 0..160 (field of view; 0 for none), inside?: #rrggbb or the name of a swatch with a plain color (the board's inside), showFoldLines?: bool, base?: [x, y] (the panel under this point stays in place; an error when it is in no panel) or null (the largest panel)} set the Fold Preview window (ui.inspect: ui.fold_preview), which folds the blank that the document's shown fold lines make (addon.packaging.fold) with the document's art printed on the outside, show it and draw it again; view and zoom also center the view. A value of the wrong kind or out of range is an error and sets nothing → the window's settings and frame: the last frame's {width, height (pixels), foldMs, drawMs} or null", + ), ( "ui.copyScriptConsole", "Copy Script Console", From 54c415468b30cc6351f081bd368ad787d7c8e6b9 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Mon, 16 Nov 2026 16:40:36 -0800 Subject: [PATCH 075/176] i18n: dialog labels use the language's colon MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Dialogs and the toolbar editors added a plain ":" after a translated label, so French showed "Points isolés:" without the no-break space before the colon. A new `i18n::colon` helper appends the catalog's ":" row instead. French writes U+00A0 before the colon, Chinese and Japanese write a full-width colon, and English and the other languages are unchanged. - Field labels: the generic parameter dialogs, Text Flow, Radial Blur's Horizontal and Vertical, the graph type dialog, and the headings of the toolbar drawer and the Add Tool menu. - A label followed by a value: Radial Blur's Blur Center value for screen readers, the Simplify point count, the Dimension preview, the Revolve reset tooltip, Smart Punctuation's report, the PDF and print option summaries, the PSD import layer count, the Recolor color share tooltip, the Revolve light names and the script check's problems. - The style dialogs' attribute list showed two colons ("Font Size:: 12"). It now shows one. Part of #7991 (reported by bortekfr). --- crates/ui-egui/src/custom_toolbars.rs | 4 +- .../ui-egui/src/dialogs/char_style_options.rs | 2 +- crates/ui-egui/src/dialogs/command.rs | 2 +- crates/ui-egui/src/dialogs/dimension.rs | 2 +- crates/ui-egui/src/dialogs/effect.rs | 12 +++- crates/ui-egui/src/dialogs/form.rs | 10 +++- crates/ui-egui/src/dialogs/graph_type.rs | 20 ++++++- crates/ui-egui/src/dialogs/new_text_style.rs | 2 +- .../ui-egui/src/dialogs/para_style_options.rs | 2 +- crates/ui-egui/src/dialogs/path_ops.rs | 2 +- crates/ui-egui/src/dialogs/psd_import.rs | 2 +- crates/ui-egui/src/dialogs/recolor.rs | 3 +- crates/ui-egui/src/dialogs/revolve.rs | 2 +- crates/ui-egui/src/dialogs/revolve_lights.rs | 3 +- crates/ui-egui/src/dialogs/save_pdf.rs | 2 +- crates/ui-egui/src/dialogs/script_check.rs | 2 +- .../ui-egui/src/dialogs/smart_punctuation.rs | 2 +- crates/ui-egui/src/dialogs/tests.rs | 58 +++++++++++++++++++ crates/ui-egui/src/dialogs/tests_modal.rs | 8 +++ crates/ui-egui/src/edit_toolbar.rs | 2 +- crates/ui-egui/src/edit_toolbar/tests.rs | 30 ++++++++++ crates/ui-egui/src/i18n.rs | 7 +++ crates/ui-egui/src/i18n/tests.rs | 11 ++++ 23 files changed, 167 insertions(+), 23 deletions(-) diff --git a/crates/ui-egui/src/custom_toolbars.rs b/crates/ui-egui/src/custom_toolbars.rs index f8c3033a5e..e54085e304 100644 --- a/crates/ui-egui/src/custom_toolbars.rs +++ b/crates/ui-egui/src/custom_toolbars.rs @@ -1382,7 +1382,7 @@ fn add_menu(button: &egui::Response, t: &Tokens, bar: &CustomToolbar, actions: & let held: Vec<&'static str> = bar.slots.iter().flatten().filter_map(|id| tool_info(id).map(|t| t.id)).collect(); let heading = |ui: &mut egui::Ui, text: &str| ui.label(egui::RichText::new(text).size(12.0).color(t.text_strong)); if !held.is_empty() { - heading(ui, &format!("{}:", tl!("Remove Tool"))); + heading(ui, &crate::i18n::colon(tl!("Remove Tool"))); for tool in held.iter().filter_map(|id| tool_info(id)) { if widgets::menu_item(ui, tool.label, true, false) { actions.push(Action::RemoveTool(bar.name.clone(), tool.id)); @@ -1391,7 +1391,7 @@ fn add_menu(button: &egui::Response, t: &Tokens, bar: &CustomToolbar, actions: & ui.separator(); } for (cat, tools) in crate::edit_toolbar::sections() { - heading(ui, &format!("{}:", tl!(cat))); + heading(ui, &crate::i18n::colon(tl!(cat))); for tool in tools { if widgets::menu_item(ui, tool.label, !held.contains(&tool.id), false) { actions.push(Action::AddTool(bar.name.clone(), tool.id)); diff --git a/crates/ui-egui/src/dialogs/char_style_options.rs b/crates/ui-egui/src/dialogs/char_style_options.rs index 02515a3b89..b4abf8c6e2 100644 --- a/crates/ui-egui/src/dialogs/char_style_options.rs +++ b/crates/ui-egui/src/dialogs/char_style_options.rs @@ -1073,7 +1073,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { ui.separator(); if let Ok(attrs) = edited_attrs(d) { for (key, value) in attrs { - ui.label(format!("{}: {}", super::humanize(&key), value)); + ui.label(super::form::attribute_line(&key, &value)); } } } diff --git a/crates/ui-egui/src/dialogs/command.rs b/crates/ui-egui/src/dialogs/command.rs index f5215092e8..052eb030d0 100644 --- a/crates/ui-egui/src/dialogs/command.rs +++ b/crates/ui-egui/src/dialogs/command.rs @@ -36,7 +36,7 @@ pub(super) const SPEC: DialogSpec = DialogSpec { let mut rows = v.as_str() == Some("rows"); ui.add_space(4.0); egui::Grid::new("text-flow").num_columns(2).spacing([12.0, 8.0]).show(ui, |ui| { - let row = ui.label(egui::RichText::new(format!("{}:", tl!("Text Flow"))).color(Tokens::get(ui.ctx()).text)); + let row = ui.label(egui::RichText::new(crate::i18n::colon(tl!("Text Flow"))).color(Tokens::get(ui.ctx()).text)); ui.label_inputs_by(row.id, |ui| { ui.horizontal(|ui| { if widgets::radio(ui, tl!("By Rows"), rows, true) { diff --git a/crates/ui-egui/src/dialogs/dimension.rs b/crates/ui-egui/src/dialogs/dimension.rs index 140ace0fde..1a08c4d377 100644 --- a/crates/ui-egui/src/dialogs/dimension.rs +++ b/crates/ui-egui/src/dialogs/dimension.rs @@ -211,7 +211,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog) -> bool { Ok(o) => { let sample = o.label(72.0, false).unwrap_or_default(); let t = Tokens::get(ui.ctx()); - ui.label(RichText::new(format!("{}: {sample}", tl!("Preview (1 inch on the page)"))).color(t.text)); + ui.label(RichText::new(format!("{} {sample}", crate::i18n::colon(tl!("Preview (1 inch on the page)")))).color(t.text)); } Err(e) => { ui.colored_label(Tokens::get(ui.ctx()).text, e); diff --git a/crates/ui-egui/src/dialogs/effect.rs b/crates/ui-egui/src/dialogs/effect.rs index ac2798ec40..2ac68d5b9c 100644 --- a/crates/ui-egui/src/dialogs/effect.rs +++ b/crates/ui-egui/src/dialogs/effect.rs @@ -317,6 +317,13 @@ fn center_round(x: f64) -> f64 { (x * 1e4).round() / 1e4 } +/// The value screen readers give Blur Center at `c` (0 to 1 of the bounds): Horizontal and +/// Vertical in percent, each label followed by the UI language's colon. +pub(super) fn blur_center_value(c: [f64; 2]) -> String { + let percent = |v: f64| (v * 1000.0).round() / 10.0; + format!("{} {}%, {} {}%", crate::i18n::colon(tl!("Horizontal")), percent(c[0]), crate::i18n::colon(tl!("Vertical")), percent(c[1])) +} + /// Radial Blur's Blur Center: a box standing for the object's bounds, with the blur's pattern (rays /// for Zoom, rings for Spin) drawn about the center. A press or a drag in the box puts the center /// there; with the keyboard focus the arrow keys move it 1 % of the box (10 % with Shift). The @@ -334,9 +341,8 @@ fn blur_center(ui: &mut egui::Ui, d: &mut Dialog) { let (rect, _) = ui.allocate_exact_size(egui::vec2(CENTER_BOX, CENTER_BOX), Sense::hover()); let id = ui.scope_id().with("radial-blur-center"); let resp = ui.interact(rect, id, Sense::click_and_drag()); - let percent = |v: f64| (v * 1000.0).round() / 10.0; let name = tl!("Blur Center").to_string(); - let value = format!("{}: {}%, {}: {}%", tl!("Horizontal"), percent(c[0]), tl!("Vertical"), percent(c[1])); + let value = blur_center_value(c); let enabled = ui.is_enabled(); resp.widget_info(|| egui::WidgetInfo { current_text_value: Some(value.clone()), @@ -391,7 +397,7 @@ fn blur_center(ui: &mut egui::Ui, d: &mut Dialog) { ui.vertical(|ui| { egui::Grid::new("blur-center-fields").num_columns(2).spacing([8.0, 8.0]).show(ui, |ui| { for (i, label) in ["Horizontal", "Vertical"].into_iter().enumerate() { - let row = ui.label(egui::RichText::new(format!("{}:", tl!(label))).color(t.text)); + let row = ui.label(egui::RichText::new(crate::i18n::colon(tl!(label))).color(t.text)); ui.label_inputs_by(row.id, |ui| { if let Some(x) = widgets::range_field_named(ui, ("blur-center", i), None, c[i] * 100.0, 0.0..=100.0, &form::unit_suffix("%"), 1, 72.0) diff --git a/crates/ui-egui/src/dialogs/form.rs b/crates/ui-egui/src/dialogs/form.rs index d386c1f028..6a99f4abed 100644 --- a/crates/ui-egui/src/dialogs/form.rs +++ b/crates/ui-egui/src/dialogs/form.rs @@ -832,11 +832,17 @@ pub(crate) fn humanize(k: &str) -> String { } } -/// [`humanize`] translated where it is painted: the ":" stays outside the translated text. +/// A style attribute as the style dialogs list it: the [`humanized`] key, then its value. +pub(super) fn attribute_line(key: &str, value: &Value) -> String { + format!("{} {value}", humanized(key)) +} + +/// [`humanize`] translated where it is painted: the ":" stays outside the translated text and is +/// written as the UI language writes a label's colon ([`crate::i18n::colon`]). pub(super) fn humanized(k: &str) -> String { let h = humanize(k); match h.strip_suffix(':') { - Some(base) => format!("{}:", tl!(base)), + Some(base) => crate::i18n::colon(tl!(base)), None => tl!(&h).to_string(), } } diff --git a/crates/ui-egui/src/dialogs/graph_type.rs b/crates/ui-egui/src/dialogs/graph_type.rs index 838ba066d9..766ae898ee 100644 --- a/crates/ui-egui/src/dialogs/graph_type.rs +++ b/crates/ui-egui/src/dialogs/graph_type.rs @@ -577,9 +577,9 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { false } -/// `text` with the colon of a field label. +/// `text` with the colon of a field label, as the UI language writes it. fn colon(text: &str) -> String { - format!("{text}:") + crate::i18n::colon(text) } /// A checkbox bound to `d.fields[key]`, dimmed while the type picked has no use for it. @@ -977,6 +977,22 @@ mod tests { assert!(app.ui.dialog.is_none()); } + /// Field labels end in the UI language's colon: in French a no-break space and a colon (#7991). + #[test] + fn field_labels_use_the_language_colon() { + let mut app = app_with_graph("column"); + crate::menus::invoke(&mut app, COMMAND, json!({})); + set(&mut app, PAGE, json!("valueAxis")); + let fr = crate::i18n::Lang::from_code("fr").unwrap(); + crate::i18n::set_current(fr); + let mut h = harness(app); + h.run_steps(3); + let want = format!("{}\u{a0}:", crate::i18n::tr(fr, "Suffix")); + let found = h.query_by_role_and_label(Role::TextInput, &want).is_some(); + crate::i18n::set_current(crate::i18n::Lang::EN); + assert!(found, "a text field named {want:?}"); + } + /// A Type button changes the graph's type and keeps its data. #[test] fn a_type_button_changes_the_graph_type_and_keeps_its_data() { diff --git a/crates/ui-egui/src/dialogs/new_text_style.rs b/crates/ui-egui/src/dialogs/new_text_style.rs index 4978a6a1f6..82f0c7d78b 100644 --- a/crates/ui-egui/src/dialogs/new_text_style.rs +++ b/crates/ui-egui/src/dialogs/new_text_style.rs @@ -77,7 +77,7 @@ fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { }); if let Ok(attrs) = super::char_style_options::edited_attrs(d) { for (key, value) in attrs { - ui.label(format!("{}: {}", super::humanize(&key), value)); + ui.label(super::form::attribute_line(&key, &value)); } } }); diff --git a/crates/ui-egui/src/dialogs/para_style_options.rs b/crates/ui-egui/src/dialogs/para_style_options.rs index d63d43be89..9a9da0c164 100644 --- a/crates/ui-egui/src/dialogs/para_style_options.rs +++ b/crates/ui-egui/src/dialogs/para_style_options.rs @@ -952,7 +952,7 @@ pub(crate) fn general_body(ui: &mut egui::Ui, d: &mut Dialog) { ui.separator(); if let Ok(attrs) = edited_attrs(d) { for (key, value) in attrs { - ui.label(format!("{}: {}", super::humanize(&key), value)); + ui.label(super::form::attribute_line(&key, &value)); } } } diff --git a/crates/ui-egui/src/dialogs/path_ops.rs b/crates/ui-egui/src/dialogs/path_ops.rs index 3a62eae1f4..3ffc496dd6 100644 --- a/crates/ui-egui/src/dialogs/path_ops.rs +++ b/crates/ui-egui/src/dialogs/path_ops.rs @@ -198,7 +198,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { && let Some(counts) = d.fields.get("__counts") && let (Some(before), Some(after)) = (counts["before"].as_u64(), counts["after"].as_u64()) { - ui.label(format!("{}: {before} → {after}", tl!("Anchor Points"))); + ui.label(format!("{} {before} → {after}", crate::i18n::colon(tl!("Anchor Points")))); } } false diff --git a/crates/ui-egui/src/dialogs/psd_import.rs b/crates/ui-egui/src/dialogs/psd_import.rs index 950b15c763..c5a4c905a0 100644 --- a/crates/ui-egui/src/dialogs/psd_import.rs +++ b/crates/ui-egui/src/dialogs/psd_import.rs @@ -167,7 +167,7 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> { fn body(_: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { let count = |k: &str| d.fields.get(k).and_then(Value::as_u64).unwrap_or(0); - widgets::dim_label(ui, &format!("{} × {} px · {}: {}", count("width"), count("height"), tl!("Layers"), count("layers"))); + widgets::dim_label(ui, &format!("{} × {} px · {} {}", count("width"), count("height"), crate::i18n::colon(tl!("Layers")), count("layers"))); // Offered only for a file with slices, with either conversion. let sliced = count("slices") > 0; ui.add_space(8.0); diff --git a/crates/ui-egui/src/dialogs/recolor.rs b/crates/ui-egui/src/dialogs/recolor.rs index e3829f92b5..024de90241 100644 --- a/crates/ui-egui/src/dialogs/recolor.rs +++ b/crates/ui-egui/src/dialogs/recolor.rs @@ -357,7 +357,8 @@ fn prominent_bar(ui: &mut Ui, d: &mut Dialog, rows: &[Value]) { let c = to_color(&rows[*i]).or_else(|| from_colors(&rows[*i]).first().copied()).unwrap_or_default(); chip(ui, r, c, false); let share = (widths[n] * 100.0).round(); - ui.interact(r, egui::Id::unique((PROMINENT_PART, n)), Sense::hover()).on_hover_text(format!("{} {}: {share}%", tl!("Color"), i + 1)); + ui.interact(r, egui::Id::unique((PROMINENT_PART, n)), Sense::hover()) + .on_hover_text(format!("{} {share}%", crate::i18n::colon(&format!("{} {}", tl!("Color"), i + 1)))); left = right; } let mut ended = false; diff --git a/crates/ui-egui/src/dialogs/revolve.rs b/crates/ui-egui/src/dialogs/revolve.rs index 77c5980ec0..c7c98a5de0 100644 --- a/crates/ui-egui/src/dialogs/revolve.rs +++ b/crates/ui-egui/src/dialogs/revolve.rs @@ -733,7 +733,7 @@ pub(super) fn reset_dot(ui: &mut egui::Ui, key: &str, changed: bool, default: &s ui.painter().rect_filled(r, 3.0, Tokens::get(ui.ctx()).hover); } dot(ui, r.center(), changed); - response.on_hover_text(format!("{}: {default}", tl!("Reset to default"))).clicked() + response.on_hover_text(format!("{} {default}", crate::i18n::colon(tl!("Reset to default")))).clicked() } #[cfg(test)] diff --git a/crates/ui-egui/src/dialogs/revolve_lights.rs b/crates/ui-egui/src/dialogs/revolve_lights.rs index 3d522b624a..dadab71c70 100644 --- a/crates/ui-egui/src/dialogs/revolve_lights.rs +++ b/crates/ui-egui/src/dialogs/revolve_lights.rs @@ -75,7 +75,8 @@ impl Light { /// The name screen readers give the light at `index`: its number, Rotation, Height and side. fn name(self, index: usize) -> String { let side = if self.behind { format!(", {}", tl!("Light behind the object")) } else { String::new() }; - format!("{} {}: {} {:.1}°, {} {:.1}°{side}", c3("Light"), index + 1, tl!("Rotation"), self.rotation, tl!("Height"), self.height) + let light = crate::i18n::colon(&format!("{} {}", c3("Light"), index + 1)); + format!("{light} {} {:.1}°, {} {:.1}°{side}", tl!("Rotation"), self.rotation, tl!("Height"), self.height) } } diff --git a/crates/ui-egui/src/dialogs/save_pdf.rs b/crates/ui-egui/src/dialogs/save_pdf.rs index 4f8bdf7667..d4fb4a8937 100644 --- a/crates/ui-egui/src/dialogs/save_pdf.rs +++ b/crates/ui-egui/src/dialogs/save_pdf.rs @@ -871,7 +871,7 @@ pub(super) fn option_rows<'a>(ui: &mut egui::Ui, changed: impl IntoIterator<Item Value::String(s) => s.clone(), other => other.to_string(), }; - ui.label(egui::RichText::new(format!("{}: {value}", label(c["option"].as_str().unwrap_or_default()))).color(t.text)); + ui.label(egui::RichText::new(format!("{} {value}", crate::i18n::colon(&label(c["option"].as_str().unwrap_or_default())))).color(t.text)); } } diff --git a/crates/ui-egui/src/dialogs/script_check.rs b/crates/ui-egui/src/dialogs/script_check.rs index 257227cc6f..e134cf1b39 100644 --- a/crates/ui-egui/src/dialogs/script_check.rs +++ b/crates/ui-egui/src/dialogs/script_check.rs @@ -271,7 +271,7 @@ fn report(ui: &mut egui::Ui, r: &Value, t: &Tokens) { for p in problems { let Some(label) = p["code"].as_str().and_then(problem_label) else { continue }; let label = match p["detail"].as_str() { - Some(detail) => format!("{label}: {detail}"), + Some(detail) => format!("{} {detail}", crate::i18n::colon(label)), None => label.to_string(), }; row(ui, t, &label, false, &place(p)); diff --git a/crates/ui-egui/src/dialogs/smart_punctuation.rs b/crates/ui-egui/src/dialogs/smart_punctuation.rs index 1ebe084e02..ce6f62c6a2 100644 --- a/crates/ui-egui/src/dialogs/smart_punctuation.rs +++ b/crates/ui-egui/src/dialogs/smart_punctuation.rs @@ -98,7 +98,7 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> DialogResult { let lines: Vec<String> = options() .into_iter() .filter(|(key, ..)| d.bool(key)) - .map(|(_, count, label)| format!("{label}: {}", r["replaced"][count].as_u64().unwrap_or(0))) + .map(|(_, count, label)| format!("{} {}", crate::i18n::colon(label), r["replaced"][count].as_u64().unwrap_or(0))) .collect(); super::confirm::tell(app, tl!("Smart Punctuation"), &lines.join("\n")); } diff --git a/crates/ui-egui/src/dialogs/tests.rs b/crates/ui-egui/src/dialogs/tests.rs index 201b34171d..e01668155f 100644 --- a/crates/ui-egui/src/dialogs/tests.rs +++ b/crates/ui-egui/src/dialogs/tests.rs @@ -178,6 +178,64 @@ fn effect_preview_is_kept_as_one_undo_step() { assert_eq!(app.session.doc().unwrap().doc, before); } +/// A field label's colon is written as the UI language writes it, in the generic parameter +/// dialogs and the effect dialogs alike (#7991): French puts a no-break space before it, Chinese +/// writes a full-width colon, and English is unchanged. +#[test] +fn field_label_colons_follow_the_ui_language() { + let mut app = app(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap(); + let text = + app.run("text.create", json!({"x": 20, "y": 80, "text": "Hello", "area": {"width": 100, "height": 100}})).unwrap()["id"].as_u64().unwrap(); + // Each dialog, opened the way its menu item opens it, and the label it shows. + let entries = crate::menus::menu_entries(&app); + let clean_up = entries.iter().find(|e| e.path == ["Object", "Path"] && e.label == "Clean Up…").expect("listed"); + let clean_up = crate::menus::click_target(&clean_up.label, clean_up.command.as_deref().unwrap(), &clean_up.params); + let dialogs = [ + (clean_up.0, clean_up.1, "Stray Points"), + ("effect.dialog".to_string(), json!({"effect": "blur.radial"}), "Horizontal"), + ("text.areaOptions".to_string(), json!({}), "Text Flow"), + ]; + for (command, params, label) in dialogs { + app.run("select.set", json!({"ids": [text]})).unwrap(); + if command != "text.areaOptions" { + app.run("select.all", json!({})).unwrap(); + } + crate::menus::invoke(&mut app, &command, params); + assert!(app.ui.dialog.is_some(), "{command} opened no dialog"); + for (code, colon) in [("fr", "\u{a0}:"), ("zh-hans", ":"), ("en", ":")] { + let lang = crate::i18n::Lang::from_code(code).unwrap(); + crate::i18n::set_current(lang); + let shown = crate::tests_labels::painted_text(&mut app, |app, ui| show(app, ui.ctx())); + crate::i18n::set_current(crate::i18n::Lang::EN); + let want = format!("{}{colon}", crate::i18n::tr(lang, label)); + assert!(shown.lines().any(|l| l.trim() == want), "{command}, {code}: {want:?} in {shown}"); + if code == "fr" { + let bare: Vec<_> = shown.lines().map(str::trim).filter(|l| l.ends_with(':') && !l.ends_with("\u{a0}:")).collect(); + assert!(bare.is_empty(), "{command}: French labels with a bare colon: {bare:?}"); + } + } + app.ui.dialog = None; + } + assert_eq!(super::form::humanized("strayPoints"), "Stray Points:", "English is unchanged"); +} + +/// A label followed by its value takes the UI language's colon too (#7991): Blur Center's value for +/// screen readers, and a style's attribute list, which no longer shows a second colon. +#[test] +fn label_and_value_colons_follow_the_ui_language() { + let fr = crate::i18n::Lang::from_code("fr").unwrap(); + crate::i18n::set_current(fr); + let center = super::effect::blur_center_value([0.5, 0.25]); + let attribute = super::form::attribute_line("fontSize", &json!(12)); + crate::i18n::set_current(crate::i18n::Lang::EN); + let (h, v) = (crate::i18n::tr(fr, "Horizontal"), crate::i18n::tr(fr, "Vertical")); + assert_eq!(center, format!("{h}\u{a0}: 50%, {v}\u{a0}: 25%")); + assert_eq!(attribute, format!("{}\u{a0}: 12", crate::i18n::tr(fr, "Font Size"))); + assert_eq!(super::effect::blur_center_value([0.5, 0.25]), "Horizontal: 50%, Vertical: 25%"); + assert_eq!(super::form::attribute_line("fontSize", &json!(12)), "Font Size: 12"); +} + /// Drop Shadow's Color typed as text the effect can't draw: OK returns the error and keeps the /// dialog open, with Preview on or off, and the document stays as it was. #[test] diff --git a/crates/ui-egui/src/dialogs/tests_modal.rs b/crates/ui-egui/src/dialogs/tests_modal.rs index 06eef4d2c6..29a37ac4ad 100644 --- a/crates/ui-egui/src/dialogs/tests_modal.rs +++ b/crates/ui-egui/src/dialogs/tests_modal.rs @@ -678,6 +678,14 @@ fn simplify_dialog_preview_counts_and_cancel_restore_the_original() { let texts = frame(&ctx, &mut app, vec![]); let preview = texts.iter().find(|(t, _)| t == "Preview").map(|(_, r)| *r).expect("a Preview checkbox"); assert!(texts.iter().any(|(t, _)| t == "Anchor Points: 20 → 2"), "the reduction is visible: {texts:?}"); + // In French the label ends in a no-break space and a colon (#7991). + let fr = crate::i18n::Lang::from_code("fr").unwrap(); + crate::i18n::set_current(fr); + let french = frame(&ctx, &mut app, vec![]); + crate::i18n::set_current(crate::i18n::Lang::EN); + let want = format!("{}\u{a0}: 20 → 2", crate::i18n::tr(fr, "Anchor Points")); + assert!(french.iter().any(|(t, _)| *t == want), "{want:?} in {french:?}"); + frame(&ctx, &mut app, vec![]); assert!(app.session.in_interaction()); assert!(app.session.doc().unwrap().selection.anchors.is_empty()); assert_eq!(app.session.doc().unwrap().history.undo.len(), undo_len); diff --git a/crates/ui-egui/src/edit_toolbar.rs b/crates/ui-egui/src/edit_toolbar.rs index d58351ac21..51155e710f 100644 --- a/crates/ui-egui/src/edit_toolbar.rs +++ b/crates/ui-egui/src/edit_toolbar.rs @@ -532,7 +532,7 @@ pub(crate) fn drawer(app: &mut VectorcraftApp, ctx: &egui::Context) { let inner = ui.available_width() - 10.0; for (cat, gs) in groups() { ui.add_space(6.0); - ui.label(egui::RichText::new(format!("{}:", tl!(cat))).size(12.0).color(t.text_strong)); + ui.label(egui::RichText::new(crate::i18n::colon(tl!(cat))).size(12.0).color(t.text_strong)); ui.add_space(4.0); for g in gs { // A flyout group: its tools framed together, as one toolbar button holds them. diff --git a/crates/ui-egui/src/edit_toolbar/tests.rs b/crates/ui-egui/src/edit_toolbar/tests.rs index fedfe9dcfd..ad6061e041 100644 --- a/crates/ui-egui/src/edit_toolbar/tests.rs +++ b/crates/ui-egui/src/edit_toolbar/tests.rs @@ -319,6 +319,25 @@ fn tools_in_the_toolbar_are_dimmed_in_the_drawer() { assert_eq!(cell_at(&shown, drawer, "Artboard Tool").1, dim); } +/// The drawer's headings end in the UI language's colon: in French a no-break space and a colon +/// (#7991), in English a plain colon. +#[test] +fn drawer_headings_use_the_language_colon() { + let mut app = app(); + let ctx = ctx(); + app.run("window.editToolbar", json!({"open": true})).unwrap(); + for (code, colon) in [("fr", "\u{a0}:"), ("en", ":")] { + let lang = crate::i18n::Lang::from_code(code).unwrap(); + crate::i18n::set_current(lang); + frame(&mut app, &ctx, 0.0, vec![]); + let shown = frame(&mut app, &ctx, 0.1, vec![]); + crate::i18n::set_current(crate::i18n::Lang::EN); + let drawer = drawer_rect(&ctx).unwrap(); + let want = format!("{}{colon}", crate::i18n::tr(lang, "Select")); + assert!(shown.iter().any(|(s, p, _)| s.trim() == want && drawer.contains(*p)), "{code}: {want:?}"); + } +} + /// #1018: tools drag from the drawer onto the toolbar (between two tools, or onto one to join /// its group), from the toolbar into the drawer, and within the toolbar, only while the drawer /// is open. @@ -543,6 +562,17 @@ fn the_add_tool_menu_fills_a_new_toolbar_without_a_drag() { click(&mut app, &ctx, 40.0, items(&shown, "Lasso Tool")[0].0); assert_eq!(mine(&app), [["magicWand"]]); assert_eq!(slots(&app), shipped); + // In French the menu's headings end in a no-break space and a colon (#7991). + open(&mut app, 49.0); + let fr = crate::i18n::Lang::from_code("fr").unwrap(); + crate::i18n::set_current(fr); + frame(&mut app, &ctx, 49.7, vec![]); + let french = frame(&mut app, &ctx, 49.8, vec![]); + crate::i18n::set_current(crate::i18n::Lang::EN); + for heading in ["Remove Tool", "Select"] { + let want = format!("{}\u{a0}:", crate::i18n::tr(fr, heading)); + assert_eq!(items(&french, &want).len(), 1, "{want:?}"); + } } /// New Toolbar… in the drawer's menu opens the New Toolbar dialog, which asks for a name. diff --git a/crates/ui-egui/src/i18n.rs b/crates/ui-egui/src/i18n.rs index d54ea0178a..34a3773510 100644 --- a/crates/ui-egui/src/i18n.rs +++ b/crates/ui-egui/src/i18n.rs @@ -623,6 +623,13 @@ pub fn t(s: &str) -> &str { tr(current(), s) } +/// `label`, already in the current language, followed by a field label's colon as the current +/// language writes it (its catalog row for ":"): French puts a no-break space before the colon, and +/// Chinese and Japanese write a full-width colon. +pub fn colon(label: &str) -> String { + format!("{label}{}", t(":")) +} + /// Translate an English UI string; unknown strings come back unchanged. pub fn tr(lang: Lang, s: &str) -> &str { lang.catalog().plain(s).unwrap_or(s) diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index ed4b44b0da..8a64501801 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -2041,6 +2041,17 @@ fn georgian_rows_have_no_mtavruli() { assert!(caps.is_empty(), "Mtavruli in ka.tsv: {caps:?}"); } +/// A field label's colon follows the catalog's ":" row: French puts a no-break space before it, +/// Chinese and Japanese write a full-width colon, and English and German write a plain colon. +#[test] +fn label_colons_follow_the_language() { + for (code, want) in [("fr", "X\u{a0}:"), ("zh-hans", "X:"), ("zh-hant", "X:"), ("ja", "X:"), ("de", "X:"), ("en", "X:")] { + set_current(Lang::from_code(code).expect("registered")); + assert_eq!(colon("X"), want, "{code}"); + } + set_current(Lang::EN); +} + /// French rows follow the typography fr.tsv's header sets: a no-break space before : ; ? ! and inside /// « », and the typographic apostrophe ’ in elisions. Text in backticks is code and is not checked, and /// a straight apostrophe inside double quotes is a literal value. From f84fc7a6aea429a425e50e841323e3e597b88566 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Mon, 16 Nov 2026 17:44:20 -0800 Subject: [PATCH 076/176] Packaging Tools: Fold Preview's White inside stays white beside a swatch named #ffffff The built-in White inside is stored as an empty value instead of #ffffff, so a swatch named #ffffff no longer replaces it. ui.foldPreview takes an empty inside for white; a swatch's name still comes before a #rrggbb that reads the same. --- crates/mcp/src/ui_catalog.rs | 2 +- .../ui-egui/src/addons/packaging/preview.rs | 29 +++++++++++-------- .../src/addons/packaging/preview/tests.rs | 7 +++++ crates/ui-egui/src/menus/ui_commands.rs | 2 +- docs/mcp.md | 2 +- 5 files changed, 27 insertions(+), 15 deletions(-) diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index 784ebbf11b..bda3464573 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -1151,7 +1151,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.foldPreview", "Fold Preview", "", - "{amount?: 0..1 (how far the blank is folded), view?: front|back|left|right|top|bottom|threeQuarter, rotateX?: deg -180..180 (the top toward the viewer), rotateY?: deg -180..180 (the right side toward the viewer), zoom?: 0.1..8 (1 fits the folded blank), perspective?: deg 0..160 (field of view; 0 for none), inside?: #rrggbb or the name of a swatch with a plain color (the board's inside), showFoldLines?: bool, base?: [x, y] (the panel under this point stays in place; an error when it is in no panel) or null (the largest panel)} set the Fold Preview window (ui.inspect: ui.fold_preview), which folds the blank that the document's shown fold lines make (addon.packaging.fold) with the document's art printed on the outside, show it and draw it again; view and zoom also center the view. A value of the wrong kind or out of range is an error and sets nothing → the window's settings and frame: the last frame's {width, height (pixels), foldMs, drawMs} or null", + "{amount?: 0..1 (how far the blank is folded), view?: front|back|left|right|top|bottom|threeQuarter, rotateX?: deg -180..180 (the top toward the viewer), rotateY?: deg -180..180 (the right side toward the viewer), zoom?: 0.1..8 (1 fits the folded blank), perspective?: deg 0..160 (field of view; 0 for none), inside?: #rrggbb, the name of a swatch with a plain color, or empty for white (the board's inside), showFoldLines?: bool, base?: [x, y] (the panel under this point stays in place; an error when it is in no panel) or null (the largest panel)} set the Fold Preview window (ui.inspect: ui.fold_preview), which folds the blank that the document's shown fold lines make (addon.packaging.fold) with the document's art printed on the outside, show it and draw it again; view and zoom also center the view. A value of the wrong kind or out of range is an error and sets nothing → the window's settings and frame: the last frame's {width, height (pixels), foldMs, drawMs} or null", ), ( "ui.copyScriptConsole", diff --git a/crates/ui-egui/src/addons/packaging/preview.rs b/crates/ui-egui/src/addons/packaging/preview.rs index 0b0188f44c..97a8ebd988 100644 --- a/crates/ui-egui/src/addons/packaging/preview.rs +++ b/crates/ui-egui/src/addons/packaging/preview.rs @@ -64,7 +64,7 @@ pub struct Settings { pub pan: [f64; 2], /// The field of view in degrees; 0 for none. pub perspective: f64, - /// The board's inside color: `#rrggbb` or the name of a swatch. + /// The board's inside color: `#rrggbb`, the name of a swatch, or empty for white. pub inside: String, /// Draw the fold lines on the print. pub show_fold_lines: bool, @@ -82,7 +82,7 @@ impl Default for Settings { zoom: 1.0, pan: [0.0; 2], perspective: 0.0, - inside: "#ffffff".into(), + inside: String::new(), show_fold_lines: false, base: None, } @@ -183,9 +183,12 @@ thread_local! { static RENDERER: std::cell::RefCell<vectorcraft_render::Renderer> = std::cell::RefCell::new(vectorcraft_render::Renderer::new()); } -/// The board's inside color (straight RGBA) for `inside`: a swatch of `d` with a plain color, or else -/// `#rrggbb`; `None` for anything else. +/// The board's inside color (straight RGBA) for `inside`: white when it is empty, a swatch of `d` +/// with a plain color, or else `#rrggbb`; `None` for anything else. fn inside_color(d: &vectorcraft_engine::doc::Document, inside: &str) -> Option<[u8; 4]> { + if inside.is_empty() { + return Some([255; 4]); + } match d.swatch(inside).map(|s| &s.paint) { Some(vectorcraft_color::Paint::Solid { color, .. }) => Some(color.to_rgba8(1.0)), _ if inside.starts_with('#') => vectorcraft_color::Color::from_hex(inside).map(|c| c.to_rgba8(1.0)), @@ -347,12 +350,14 @@ pub(crate) fn command(app: &mut VectorcraftApp, p: &Value) -> Result<Value, Stri match p.get("inside") { None | Some(Value::Null) => {} Some(v) => { - let inside = v.as_str().unwrap_or_default(); - let known = app.session.active().and_then(|st| inside_color(&st.doc, inside)).is_some() - || (inside.starts_with('#') && vectorcraft_color::Color::from_hex(inside).is_some()); - if !known { - return Err(format!("`inside` must be #rrggbb or the name of a swatch with a plain color, not {v}")); - } + let inside = v.as_str().filter(|inside| { + inside.is_empty() + || app.session.active().and_then(|st| inside_color(&st.doc, inside)).is_some() + || (inside.starts_with('#') && vectorcraft_color::Color::from_hex(inside).is_some()) + }); + let Some(inside) = inside else { + return Err(format!("`inside` must be #rrggbb, the name of a swatch with a plain color, or empty for white, not {v}")); + }; set.inside = inside.to_string(); } } @@ -413,10 +418,10 @@ fn toolbar(app: &VectorcraftApp, ui: &mut Ui, set: &mut Settings) { }); let mut names: Vec<&str> = vec![tl!("White")]; names.extend(swatches.iter().map(String::as_str)); - let shown = if set.inside == "#ffffff" { tl!("White") } else { set.inside.as_str() }; + let shown = if set.inside.is_empty() { tl!("White") } else { set.inside.as_str() }; ui.label(tl!("Inside")); if let Some(i) = widgets::dropdown_names_named(ui, "fold-preview-inside", Some(tl!("Inside")), shown, &names, 110.0) { - set.inside = swatches.get(i.wrapping_sub(1)).cloned().unwrap_or_else(|| "#ffffff".into()); + set.inside = swatches.get(i.wrapping_sub(1)).cloned().unwrap_or_default(); } if widgets::check(ui, tl!("Show Fold Lines"), set.show_fold_lines, true) { set.show_fold_lines = !set.show_fold_lines; diff --git a/crates/ui-egui/src/addons/packaging/preview/tests.rs b/crates/ui-egui/src/addons/packaging/preview/tests.rs index 974556032b..c3c69c3f31 100644 --- a/crates/ui-egui/src/addons/packaging/preview/tests.rs +++ b/crates/ui-egui/src/addons/packaging/preview/tests.rs @@ -132,6 +132,13 @@ fn ui_fold_preview_sets_the_window_and_refuses_bad_values() { assert_eq!(inside_color(doc, "#brand"), Some([0, 0, 255, 255])); assert_eq!(inside_color(doc, "#00ff00"), Some([0, 0, 255, 255])); assert_eq!(inside_color(doc, "#ff0000"), Some([255, 0, 0, 255])); + // White, the default, stays white beside a swatch named #ffffff. + app.run("swatch.new", json!({"name": "#ffffff", "color": "#0000ff"})).unwrap(); + let doc = &app.session.active().expect("a document").doc; + assert_eq!(inside_color(doc, &Settings::default().inside), Some([255; 4])); + assert_eq!(inside_color(doc, "#ffffff"), Some([0, 0, 255, 255])); + app.run("ui.foldPreview", json!({"inside": ""})).unwrap(); + assert_eq!(app.ui.fold_preview.inside, ""); } #[test] diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index af7f870f83..4b5cb8b95d 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -1152,7 +1152,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "ui.foldPreview", "Fold Preview", "", - "{amount?: 0..1 (how far the blank is folded), view?: front|back|left|right|top|bottom|threeQuarter, rotateX?: deg -180..180 (the top toward the viewer), rotateY?: deg -180..180 (the right side toward the viewer), zoom?: 0.1..8 (1 fits the folded blank), perspective?: deg 0..160 (field of view; 0 for none), inside?: #rrggbb or the name of a swatch with a plain color (the board's inside), showFoldLines?: bool, base?: [x, y] (the panel under this point stays in place; an error when it is in no panel) or null (the largest panel)} set the Fold Preview window (ui.inspect: ui.fold_preview), which folds the blank that the document's shown fold lines make (addon.packaging.fold) with the document's art printed on the outside, show it and draw it again; view and zoom also center the view. A value of the wrong kind or out of range is an error and sets nothing → the window's settings and frame: the last frame's {width, height (pixels), foldMs, drawMs} or null", + "{amount?: 0..1 (how far the blank is folded), view?: front|back|left|right|top|bottom|threeQuarter, rotateX?: deg -180..180 (the top toward the viewer), rotateY?: deg -180..180 (the right side toward the viewer), zoom?: 0.1..8 (1 fits the folded blank), perspective?: deg 0..160 (field of view; 0 for none), inside?: #rrggbb, the name of a swatch with a plain color, or empty for white (the board's inside), showFoldLines?: bool, base?: [x, y] (the panel under this point stays in place; an error when it is in no panel) or null (the largest panel)} set the Fold Preview window (ui.inspect: ui.fold_preview), which folds the blank that the document's shown fold lines make (addon.packaging.fold) with the document's art printed on the outside, show it and draw it again; view and zoom also center the view. A value of the wrong kind or out of range is an error and sets nothing → the window's settings and frame: the last frame's {width, height (pixels), foldMs, drawMs} or null", ), ( "ui.copyScriptConsole", diff --git a/docs/mcp.md b/docs/mcp.md index 657c6f2e35..e915486698 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -13251,7 +13251,7 @@ and the print is a raster whose longest side is 2,048 pixels, rendered again whe perspective?, inside?, showFoldLines?, base?}`) sets the window, shows it and draws it again. A second run leaves the window open. `rotateX` (-180 to 180) tips the top toward the viewer and `rotateY` (-180 to 180) turns the right side toward the viewer, in degrees; `zoom` is 0.1 to 8, where 1 fits the folded blank; `perspective` is the field of view, 0 to -160 degrees, 0 for none; `inside` is the name of a swatch with a plain color, or else `#rrggbb`; `base` is a point in a panel +160 degrees, 0 for none; `inside` is the name of a swatch with a plain color, or else `#rrggbb`, or `""` for white; `base` is a point in a panel of the document's blanks, or null for the largest panel. With perspective, the zoom of 1 keeps the eye at least twice the folded blank's radius from its middle. A value of the wrong kind or out of range is an error and sets nothing. VectorCraft's own defaults are a Three-Quarter view (`rotateX` 25, `rotateY` 35), no perspective, a white inside and the From e38bfffad7dbc4a23ea4b7755109f5ce7ab0180b Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 17 Nov 2026 04:14:41 -0800 Subject: [PATCH 077/176] i18n: French messages use the narrow no-break space before colons The five French script file messages added on this branch put an ordinary space before ":" and ";". They now use U+202F, which french_catalog_uses_nonbreaking_prose_punctuation accepts. --- crates/ui-egui/src/i18n/fr.tsv | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 4ca3b9a58a..4234ce6876 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -4590,7 +4590,7 @@ liquify-list-end {0}, {1} {0} et {1} @msg `answers` is only for a run with nobody to ask: in the app, the person answers each dialog `answers` est réservé à une exécution sans personne à qui demander : dans l’application, la personne répond à chaque boîte de dialogue @msg Running a script Exécution d’un script @msg Copied the script report Rapport du script copié -@msg Script file access denied: {path} Accès du script aux fichiers refusé : {path} +@msg Script file access denied: {path} Accès du script aux fichiers refusé : {path} @msg Script file access to the app's own folders is not allowed L’accès du script aux dossiers propres à l’application n’est pas autorisé @msg Script file cannot encode the text Le fichier du script ne peut pas encoder le texte @msg Script file could not be written Le fichier du script n’a pas pu être écrit @@ -4603,14 +4603,14 @@ liquify-list-end {0}, {1} {0} et {1} @msg Script folder is not empty Le dossier du script n’est pas vide @msg Script files cannot make aliases Les fichiers du script ne peuvent pas créer d’alias @msg Script file hidden setting cannot be changed Le réglage masqué du fichier du script ne peut pas être modifié -@msg {name}: a file dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name} : une boîte de dialogue de fichiers ne peut pas s’ouvrir dans un rappel d’une fonction intégrée, d’un accesseur, d’une conversion ou d’un fichier exécuté par $.evalFile ; appelez-la depuis le propre code du script +@msg {name}: a file dialog cannot open inside a callback of a built-in function, a getter, a conversion or a file $.evalFile runs; call it from the script's own code {name} : une boîte de dialogue de fichiers ne peut pas s’ouvrir dans un rappel d’une fonction intégrée, d’un accesseur, d’une conversion ou d’un fichier exécuté par $.evalFile ; appelez-la depuis le propre code du script @msg the script wrote more file data than one run may write (32 MiB) le script a écrit plus de données de fichiers qu’une exécution ne peut en écrire (32 Mio) -@msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` pour la boîte de dialogue de fichiers d’un script doit être l’une des valeurs : once, always, deny, stop +@msg `answer` for a script's file dialog must be one of: once, always, deny, stop `answer` pour la boîte de dialogue de fichiers d’un script doit être l’une des valeurs : once, always, deny, stop @msg choose a file or folder first, or deny choisissez d’abord un fichier ou un dossier, ou refusez -@msg the script file permissions could not be saved: {e} les autorisations d’accès aux fichiers des scripts n’ont pas pu être enregistrées : {e} +@msg the script file permissions could not be saved: {e} les autorisations d’accès aux fichiers des scripts n’ont pas pu être enregistrées : {e} @msg this script's file access can be allowed only once l’accès aux fichiers de ce script ne peut être autorisé qu’une fois @msg Only the person at the keyboard can allow a script's file access Seule la personne au clavier peut autoriser l’accès aux fichiers d’un script -@msg A script is given at most 2,048 files: the files picked after them were left out Un script reçoit au plus 2 048 fichiers : les fichiers choisis après eux ont été laissés de côté +@msg A script is given at most 2,048 files: the files picked after them were left out Un script reçoit au plus 2 048 fichiers : les fichiers choisis après eux ont été laissés de côté @msg Copied the link info Informations sur le lien copiées @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} From 5434635e4965be1b9fce77543955a1559a4dda2d Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 17 Nov 2026 05:15:15 -0800 Subject: [PATCH 078/176] Clipping: a stroked clipping type does not widen the box a clip group's gradient follows Free Distort and the Warp effects move a group's placed gradient from the group's bounds before the effect to its bounds after it. A clip group whose clipping type strokes is measured as that clip group, so the stroke outside the clip no longer changes how its gradient follows the effect. --- crates/effects/src/reshape.rs | 5 +++- crates/effects/src/tests/clipfx.rs | 47 ++++++++++++++++++++++++++++++ 2 files changed, 51 insertions(+), 1 deletion(-) diff --git a/crates/effects/src/reshape.rs b/crates/effects/src/reshape.rs index 109f66beb5..704ec0da71 100644 --- a/crates/effects/src/reshape.rs +++ b/crates/effects/src/reshape.rs @@ -2941,6 +2941,9 @@ fn group_marks( NodeKind::Image(_) => (images.map_or_else(|| n.geometric_bounds(), |w| w.image_bounds(n)), false), NodeKind::Group { children, clip } | NodeKind::Layer { children, clip, .. } if !n.extras().type_outlines => { let layer = matches!(n.kind, NodeKind::Layer { .. }); + // A clip group whose clipping type's strokes paint around it is measured as that clip + // group: the strokes outside the clip do not widen it ([`clip_bounds`]). + let clip = *clip || painted_clip_inner(n).is_some(); let skip = children.len().saturating_sub(n.editing_children().len()); let (mut bounds, mut held) = (None, false); for (i, c) in children.iter().enumerate() { @@ -2951,7 +2954,7 @@ fn group_marks( } at.pop(); // Only members measured in the bounds hold the group's gradients in place. - let counts = if *clip { i == 0 } else { i >= skip && (c.visible || !layer) }; + let counts = if clip { i == 0 } else { i >= skip && (c.visible || !layer) }; if counts { bounds = vectorcraft_geom::union_opt(bounds, b); held |= h; diff --git a/crates/effects/src/tests/clipfx.rs b/crates/effects/src/tests/clipfx.rs index 40c8b570c6..0f6ccc5ea6 100644 --- a/crates/effects/src/tests/clipfx.rs +++ b/crates/effects/src/tests/clipfx.rs @@ -827,3 +827,50 @@ fn a_groups_own_fill_paints_only_the_clip_of_clipping_type_whose_stroke_moves() } } } + +#[test] +fn a_clip_groups_placed_gradient_follows_free_distort_by_the_clip_when_its_clipping_type_strokes() { + // A clip group with a placed linear gradient fill of its own, in a group with Free Distort, + // clipped by type whose stroke has a Transform effect moving it 60 pt right, outside the clip: + // the gradient moves and scales from the clip's bounds, as for the same clip group whose type + // does not stroke. The moved stroke adds nothing to those bounds. + use vectorcraft_color::{Gradient, GradientGeom, GradientKind, GradientPaint, GradientStop}; + let stops = vec![GradientStop::new(0.0, Color::BLACK), GradientStop::new(1.0, Color::WHITE)]; + let ramp = GradientPaint::new(Gradient::new(GradientKind::Linear, stops)); + let geom = GradientGeom { start: (10.0, 45.0).into(), end: (30.0, 45.0).into(), aspect: 1.0, focal: None }; + let placed = Paint::Gradient(Box::new(GradientPaint { geom: Some(geom), ..ramp })); + fn placed_geom(n: &Node) -> Option<vectorcraft_color::GradientGeom> { + if let Paint::Gradient(g) = n.appearance.fill_paint() + && g.geom.is_some() + { + return g.geom; + } + n.children().into_iter().flatten().find_map(|c| placed_geom(c)) + } + let ends = |stroke: bool| { + let mut ty = painted_type(3, false, false); + if stroke { + ty.appearance = Appearance::basic(Paint::None, green(), 2.0).into(); + for item in &mut ty.appearance.items { + if let vectorcraft_doc::AppearanceItem::Stroke(s) = item { + s.effects.push(fx("distort.transform", json!({"moveH": 60}))); + } + } + } + let mut group = clip_group(2, ty); + group.appearance = Appearance::basic(placed.clone(), Paint::None, 0.0).into(); + let mut outer = Node::group(NodeId(1), vec![Arc::new(group)]); + let corners = json!({"corners": [[1.0 / 3.0, 0.0], [4.0 / 3.0, 0.0], [1.0, 1.0], [0.0, 1.0]]}); + outer.appearance.effects.push(fx("distort.freeDistort", corners)); + let canvas = crate::evaluate_container(None, &outer).unwrap(); + if stroke { + assert!(stroke_wrapper(&canvas).is_some(), "the type's stroke paints around the clip: {canvas:?}"); + } + placed_geom(&canvas).unwrap_or_else(|| panic!("no placed gradient: {canvas:?}")) + }; + let (plain, stroked) = (ends(false), ends(true)); + assert!( + plain.start.distance(stroked.start) < 0.5 && plain.end.distance(stroked.end) < 0.5, + "the gradient {stroked:?} follows the clip as {plain:?} does" + ); +} From 9e8b6ef76809d163bb7fb7b93e28c886bb249b4f Mon Sep 17 00:00:00 2001 From: yoriswind <yoriswind@yahoo.com> Date: Tue, 17 Nov 2026 05:19:31 -0800 Subject: [PATCH 079/176] Fix #6430: validate MCP path effects before creating text --- crates/mcp/src/tests.rs | 21 +++++++++++++++++++++ crates/mcp/src/tools/handlers.rs | 14 ++++++++++++-- docs/mcp.md | 2 +- 3 files changed, 34 insertions(+), 3 deletions(-) diff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rs index 865adcc282..d836ddeb1d 100644 --- a/crates/mcp/src/tests.rs +++ b/crates/mcp/src/tests.rs @@ -1624,6 +1624,27 @@ fn doc_json(s: &mut Server) -> Value { serde_json::from_str(&text_of(&r)).unwrap() } +#[test] +fn add_text_rejects_invalid_path_effects_before_editing() { + let mut s = server(); + let path = id_of(&call(&mut s, 1, "draw_path", json!({"d": "M40 400 C150 300 250 500 360 400 Z"}))); + let before = call(&mut s, 2, "doc_inspect", json!({})); + for (args, message) in [ + (json!({"text": "Type", "path": path, "pathEffect": "not-an-effect"}), "not-an-effect"), + (json!({"text": "Type", "path": path, "pathEffect": 42}), "must be a string"), + (json!({"text": "Type", "path": path, "mode": "area", "pathEffect": "skew"}), "requires type on a path"), + (json!({"text": "Type", "x": 10, "y": 20, "pathEffect": "skew"}), "requires type on a path"), + ] { + let reply = call(&mut s, 3, "add_text", args); + assert_eq!(reply["isError"], true, "{reply}"); + assert!(text_of(&reply).contains(message), "{reply}"); + assert_eq!(call(&mut s, 4, "doc_inspect", json!({})), before, "path, selection and history must stay intact"); + } + let made = call(&mut s, 5, "add_text", json!({"text": "Type", "path": path, "pathEffect": "skew"})); + assert_eq!(made["isError"], false, "{made}"); + assert!(doc_json(&mut s).to_string().contains("\"pathEffect\":\"skew\"")); +} + #[test] fn text_effect_pathfinder_transform_graph_and_wrap_tools() { let mut s = server(); diff --git a/crates/mcp/src/tools/handlers.rs b/crates/mcp/src/tools/handlers.rs index 717c641e19..8841c050ee 100644 --- a/crates/mcp/src/tools/handlers.rs +++ b/crates/mcp/src/tools/handlers.rs @@ -247,6 +247,16 @@ pub(super) fn select_ids(b: &mut dyn Backend, a: &Args) -> Result<(), String> { pub(super) fn add_text(b: &mut dyn Backend, a: &Args) -> Result<Value, String> { let text = a.get("text").and_then(Value::as_str).ok_or("missing string argument `text`")?; + // Creating type on a path replaces the path. Refuse an invalid effect before editing. + let path_effect = match a.get("pathEffect") { + None | Some(Value::Null) => None, + Some(Value::String(effect)) if vectorcraft_doc::PathEffect::parse(effect).is_some() => Some(effect), + Some(Value::String(effect)) => return Err(format!("unknown path effect `{effect}`")), + Some(_) => return Err("`pathEffect` must be a string".into()), + }; + if path_effect.is_some() && (!a.contains_key("path") || a.get("mode").is_some_and(|m| !matches!(m.as_str(), Some("onPath" | "path")))) { + return Err("`pathEffect` requires type on a path".into()); + } let mut style = json!({}); for k in ["size", "font", "color", "justify", "vertical"] { if let Some(v) = a.get(k) { @@ -276,12 +286,12 @@ pub(super) fn add_text(b: &mut dyn Backend, a: &Args) -> Result<Value, String> { } exec(b, "text.create", p)? }; - if let Some(e) = a.get("pathEffect").and_then(Value::as_str) { + if let Some(e) = path_effect { exec(b, "type.pathOptions", json!({"effect": e}))?; } let mut made = json!({"id": r.get("id")}); // A path effect is applied after the text is made: ask again how it fits then. - let overflow = match r.get("id").filter(|_| a.get("pathEffect").is_some()) { + let overflow = match r.get("id").filter(|_| path_effect.is_some()) { Some(id) => exec(b, "document.node", json!({"id": id, "summary": true}))?.get("overflow").and_then(Value::as_bool) == Some(true), None => r.get("overflow").is_some(), }; diff --git a/docs/mcp.md b/docs/mcp.md index a27f99feba..e8815eaec6 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -693,7 +693,7 @@ ends the wait, so the sampler can be shown again. The BSDs and headless sessions | `open_file` | `{path, importer?, params?}` | Opens any readable file as a new active document: `.vectorcraft`/`.drawcraft`, `.vctemplate`, `.svg`/`.svgz`, `.pdf`/`.ai`, `.ait`, `.eps`/`.epsf`, `.ps`, `.dxf`, `.emf`, `.wmf`, PICT (`.pct`/`.pic`/`.pict`, and a version 2 picture of any extension), HP-GL (`.plt`/`.hpgl`/`.hgl`/`.hpg`, and a file of an extension no other format reads that starts with plotter instructions), PNG (`.png`/`.pns`), JPEG, GIF, WebP, TIFF, BMP (`.bmp`/`.dib`/`.rle`), Targa (`.tga`/`.vda`/`.icb`/`.vst`), PCX, Pixar (`.pxr`), JPEG 2000 (`.jpf`/`.jpx`/`.jp2`/`.j2k`/`.j2c`/`.jpc`), HEIC/HEIF (`.heic`/`.heif`), JPEG XL (`.jxl`), PSD (`.psd`/`.pdd`)/PSB (an image opens as a document of its pixel size; a PSD or PSB file with its layers as layers, or as its merged image through `run_command document.open` with `layers: false`; a JPEG XL file as its first frame). Templates (`.vctemplate`, `.ait`) open as a new untitled document. PDF, `.ai` and SVG files saved with Preserve Editing reopen as the document they carry. The reply is `document.open`'s: its `warnings` say what didn't come in as it was (an EPS whose PostScript can't be read opens as its preview, and the warning names the PostScript error, the operator and the procedure). A file of an extension only an installed importer plug-in lists opens with that importer ([Plug-ins](#plug-ins)); `importer: "plugin.<id>"` opens the file with the importer it names, which must list the file's extension, also one a built-in format reads (in the app, as File › Open With does), and `params` gives that importer's parameters (their defaults when omitted). `run_command document.formats` lists the formats. | | `save_file` | `{path?, compress?, version?, preview?, precision?, options?}` | Runs `document.save`: the document's own file in its own format (native `.vectorcraft` unless it was opened from or saved as SVG, PDF or a restorable `.ai`; then `warnings` say what that format loses). A path's extension picks the format (`.vectorcraft`, `.vctemplate`, `.pdf`, `.svg`, `.svgz`, `.ai`: a PDF carrying the native document, which reopens editable; `.eps`: by default one file whose bounding box fits the visible art, the first artboard when no art shows; `options.useArtboards: true` makes the chosen artboard the page and, with two or more chosen, the file at the path is the central file of the visible art and each artboard is also written to `<name>_<artboard>.eps` beside it, listed in the reply's `files`). For a native file, `compress: true` gzips it (default: the `useCompression` preference, Preferences › File Handling › Use Compression), `version` (1 to 4) writes it for an older VectorCraft (1 and 2 are never compressed, and `version: 2` with `compress: true` is an error), `preview: true` embeds a PNG of the first artboard, and `precision` (0 to 9) rounds path anchors and handles to that many decimal places for that save only (colors, transforms and type stay exact). `options` passes the format's save options as `run_command document.formats` lists them. When `compress`, `version`, `preview` or `precision` is given both at the top level and in `options` with different values, the call is an error (`` `compress: true` and `options.compress: false` disagree: give the option once ``) and nothing is written. A key in `options` that no save format takes is an error, and nothing is written (see Parameter keys). The save drops each option the written format doesn't read. The reply's `warnings` then name each such option given (for example `` `compress` was not used: SVG files don't read it `` for an `.svg` path, and `` `options.preview` was not used: … `` for a key in `options`; a PDF-compatible `.ai` file reads `compress` but not `version`, `preview`, `precision`, `outlineText`, `hiddenObjects`, `transparentImages` or `preserveEditing`, and a legacy `.ai` file reads only its own options). For a `.ai` file, these warnings name the kind of `.ai` written: a legacy .ai (version 7) for `aiVersion: "7"`, a non-PDF-compatible .ai for `pdfCompatible: false`, and a PDF-compatible .ai otherwise, including a save that reuses the options the document was last saved with. `run_command document.save` and the other save commands refuse any option given beside the path and in `options` with different values, and give the same warnings for each key given beside the path or in `options` that the file doesn't read. The headless session and the app receive the same `app.save` params, and the app is also sent `wait: true`: the call returns once the file is written, or with the error (such as a path outside the write root), even with Background Save on. When the save asks first (the question before replacing a file that opened with losses, or on macOS and Linux the file dialog for an untitled document without `path`), the reply is `{pending}` or `"cancelled"` as before, and the save that runs after the answer uses the Background Save preference. Location refusals return `READ_ONLY_LOCATION: <reason>` without a fallback panel for automation; see [Save location errors](#save-location-errors). | | `export` | `{path?, format?, scale?, artboard?, range?, selection?, outlineText?, options?}` | `svg`, `svgz`, `pdf`, `ai` (the PDF-compatible `.ai` that Save writes, which carries the document when every artboard is written in order), `eps`, `dxf`, `emf`, `wmf`, `hpgl` (a `.plt` plot file for plotters and cutters), `png`, `jpg`, `webp`, `gif`, `png8` (an indexed `.png`), `tiff`, `bmp`, `tga`, `psd` (layered), `txt` (the document's text), `vectorcraft` or `template` (a native template). The tool's `format` enum and `document.formats` list them, generated from the engine's format table. When `format` is omitted, it comes from the path's extension. PDF and `.ai` write one page per artboard: all of them, or `artboard` (0-based) / `range` (`"1-3, 5"`, 1-based). SVG and SVGZ write one file per chosen artboard. EPS writes one file of the visible art; with `artboard`, `range`, `options.artboards` or `options: {"useArtboards": true}` it writes one file per chosen artboard, after a central file of the visible art when there are two or more, and `useArtboards: false` keeps the one file. Rasters, DXF, EMF, WMF and HP-GL write one artboard, or one file per chosen artboard with `options: {"useArtboards": true}`. Rasters also take `options: {"rect": [x, y, width, height]}` (page points, y down): that area of the page at the given `ppi`/`scale`, without an artboard and without changing the document; it is refused with `artboard`, `artboards`, `range` or `useArtboards`, with a non-positive or non-finite size, and for non-raster formats. `options` carries more format options (e.g. `{"quality": 80}` for JPEG). `selection: true` exports the selected objects cropped to their bounds (the reply adds their `bounds`, and reports `format` and the encoder's `warnings` as a whole-document export does); `outlineText: true` writes SVG text as paths. Template layers are left out, live effects are kept, and exporting `vectorcraft` never changes the document's path. Without `path` the bytes come back as `dataBase64`. Both backends run the same `document.export` call. | -| `add_text` | `{text, x?, y?, width?, height?, fit?, fitMinPercent?, path?, mode?, pathEffect?, size?, font?, color?, justify?, vertical?}` | Point type at (x, y) (`justify`: `left`, `center` or `right` starts, centres or ends each line on x); area type with `width`/`height` (`fit`: `none`, `autoHeight`, `shrinkText`, as `text.areaOptions`); or `path` + `mode` (`area`/`onPath`) to flow text in or along a path, with `pathEffect` (`rainbow`, `skew`, `3dRibbon`, `stairStep`, `gravity`; SVG export writes type on a path with any effect other than `rainbow` as outlines, with a warning); `justify` (also `auto`, `justifyAll`) aligns the paragraphs of every kind, as `text.setStyle` does later. `vertical: true` uses the existing vertical writing mode for every kind (default `false`, horizontal). Returns `{id}`, with `overflow: true` when the text doesn't fit its frame or path. | +| `add_text` | `{text, x?, y?, width?, height?, fit?, fitMinPercent?, path?, mode?, pathEffect?, size?, font?, color?, justify?, vertical?}` | Point type at (x, y) (`justify`: `left`, `center` or `right` starts, centres or ends each line on x); area type with `width`/`height` (`fit`: `none`, `autoHeight`, `shrinkText`, as `text.areaOptions`); or `path` + `mode` (`area`/`onPath`) to flow text in or along a path, with `pathEffect` for type on a path (`rainbow`, `skew`, `3dRibbon`, `stairStep`, `gravity`; SVG export writes type on a path with any effect other than `rainbow` as outlines, with a warning). An invalid effect is rejected before editing. `justify` (also `auto`, `justifyAll`) aligns the paragraphs of every kind, as `text.setStyle` does later. `vertical: true` uses the existing vertical writing mode for every kind (default `false`, horizontal). Returns `{id}`, with `overflow: true` when the text doesn't fit its frame or path. | | `apply_effect` | `{effect?, params?, ids?}` | Appends a live effect. Without `effect`, returns the effect catalogue with parameters and defaults. | | `pathfinder` | `{operation, ids?}` | `unite`, `minusFront`, `intersect`, `exclude`, `divide`, `trim`, `merge`, `crop`, `outline`, `minusBack`. For a live version, apply the `pathfinder.*` effect to a group (`effect.apply` groups several loose selected objects first). In remote desktop mode, `run_command` and `invoke_menu` can both call `pathfinder.repeat` with `{}`. Successful panel operations, direct `object.pathfinder.*` commands, and `command.batch` steps (including Actions panel playback) set its history. Repeat applies it to the current selection using current Pathfinder Options. Trap, compound-shape edits, live effects and `action.batch` do not set history. With no history it returns "no Pathfinder operation applied yet". | | `transform` | `{ids?, dx?, dy?, rotate?, scale?, scaleX?, scaleY?, reflect?, shear?, origin?, copy?}` | Runs move, rotate, scale, reflect, shear in that order. `rotate` is in degrees counter-clockwise; a positive `shear` moves the top to the right. With `copy`, the first step duplicates. | From 3d7a66fdbdb5cde9749203bba691c3f1520513e4 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 17 Nov 2026 06:47:38 -0800 Subject: [PATCH 080/176] Fix #8324: retain supplied raster export controls --- crates/ui-egui/src/dialogs.rs | 2 + crates/ui-egui/src/dialogs/png_options.rs | 9 +++- .../dialogs/tests_raster_supplied_options.rs | 54 +++++++++++++++++++ crates/ui-egui/src/menus/ui_commands.rs | 7 ++- docs/mcp.md | 4 ++ docs/target-app-parity.md | 1 + docs/ui-parity.md | 1 + 7 files changed, 75 insertions(+), 3 deletions(-) create mode 100644 crates/ui-egui/src/dialogs/tests_raster_supplied_options.rs diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 9e54eb12f6..252b700951 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -997,6 +997,8 @@ mod tests_plugin_import; #[cfg(test)] mod tests_raster_formats; #[cfg(test)] +mod tests_raster_supplied_options; +#[cfg(test)] mod tests_svg_options_range; #[cfg(test)] diff --git a/crates/ui-egui/src/dialogs/png_options.rs b/crates/ui-egui/src/dialogs/png_options.rs index 8965564430..a990ea4d35 100644 --- a/crates/ui-egui/src/dialogs/png_options.rs +++ b/crates/ui-egui/src/dialogs/png_options.rs @@ -63,8 +63,13 @@ pub fn open(app: &mut VectorcraftApp, f: &Format, mut params: Value) { false => export_size(&st.doc, ¶ms), }); if let Some(o) = params.as_object_mut() { - o.insert("ppi".into(), json!(72)); - o.extend(defaults(app, f)); + let mut initial = defaults(app, f); + initial.insert("ppi".into(), json!(72)); + for (key, value) in initial { + if o.get(&key).is_none_or(Value::is_null) { + o.insert(key, value); + } + } if let Some((w, h)) = size { o.insert("__size".into(), json!([w, h])); } diff --git a/crates/ui-egui/src/dialogs/tests_raster_supplied_options.rs b/crates/ui-egui/src/dialogs/tests_raster_supplied_options.rs new file mode 100644 index 0000000000..a1c22e2db0 --- /dev/null +++ b/crates/ui-egui/src/dialogs/tests_raster_supplied_options.rs @@ -0,0 +1,54 @@ +use serde_json::json; +use vectorcraft_engine::cmd::fileio; + +use super::tests_export::{app, frame, kind}; +use super::{confirm, png_options}; + +#[test] +fn raster_options_preserve_supplied_values_through_the_png_command() { + let (mut app, written) = app(1); + app.run("file.export.png", json!({"ppi": 300, "background": "#204080", "antiAlias": "type", "interlaced": true})).unwrap(); + assert_eq!(kind(&app), Some("pngOptions")); + let fields = &app.ui.dialog.as_ref().unwrap().fields; + assert_eq!(fields["ppi"], 300); + assert_eq!(fields["background"], "#204080"); + assert_eq!(fields["antiAlias"], "type"); + assert_eq!(fields["interlaced"], true); + frame(&mut app); + confirm(&mut app).unwrap(); + { + let output = written.borrow(); + assert_eq!(output.len(), 1); + let png = &output[0].1; + assert_eq!(png[28], 1); + let physical = png.windows(4).position(|w| w == b"pHYs").unwrap(); + assert_eq!(&png[physical + 4..physical + 8], ((300.0f64 / 0.0254).round() as u32).to_be_bytes()); + let decoded = craft_image_codecs::decode(png).unwrap(); + assert_eq!(decoded.dimensions(), (250, 167)); + assert_eq!(&decoded.to_rgba8()[..4], &[0x20, 0x40, 0x80, 255]); + } + + png_options::open(&mut app, fileio::format("jpg").unwrap(), json!({"format": "jpg", "path": "/out/supplied.jpg", "ppi": 144, "quality": 40})); + let fields = &app.ui.dialog.as_ref().unwrap().fields; + assert_eq!(fields["quality"], 40); + assert_eq!(fields["ppi"], 144); + assert_eq!(fields["background"], "white"); + frame(&mut app); + confirm(&mut app).unwrap(); + assert_eq!(written.borrow().len(), 2); + + for omitted in [json!({}), json!({"ppi": null, "background": null, "antiAlias": null, "interlaced": null})] { + app.run("file.export.png", omitted).unwrap(); + let fields = &app.ui.dialog.as_ref().unwrap().fields; + assert_eq!(fields["ppi"], 72); + assert_eq!(fields["background"], "transparent"); + assert_eq!(fields["antiAlias"], "art"); + assert_eq!(fields["interlaced"], false); + app.ui.dialog = None; + } + + app.run("file.export.png", json!({"ppi": 0})).unwrap(); + assert_eq!(app.ui.dialog.as_ref().unwrap().fields["ppi"], 0); + assert!(confirm(&mut app).unwrap_err().contains("ppi must be a positive number")); + assert_eq!(written.borrow().len(), 2); +} diff --git a/crates/ui-egui/src/menus/ui_commands.rs b/crates/ui-egui/src/menus/ui_commands.rs index 677b804720..f4d127cfb0 100644 --- a/crates/ui-egui/src/menus/ui_commands.rs +++ b/crates/ui-egui/src/menus/ui_commands.rs @@ -144,7 +144,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{} opens SVG Options; with params = document.export {path?, svg?: {…SVG options}, range?…} (a .svgz path writes it gzipped)", ), - ("file.export.png", "Export As PNG…", "", "{path?, …document.export options}; no path: pick the file, then PNG Options"), + ( + "file.export.png", + "Export As PNG…", + "", + "{path?, …document.export options}; no path: pick the file, then PNG Options with supplied options retained and defaults for omitted options", + ), ( "file.exportForScreens", "Export for Screens…", diff --git a/docs/mcp.md b/docs/mcp.md index 092faabc4c..a77f9926a6 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1231,6 +1231,10 @@ Draw, look, export: {"name":"export","arguments":{"path":"/tmp/icon.png","range":"1-3","options":{"useArtboards":true}}} ``` +The desktop command `file.export.png` accepts `document.export` options. Without `path`, it asks for a destination +and opens PNG Options with supplied values such as `ppi`, `background`, `antiAlias`, and `interlaced` retained. +Omitted options use the dialog defaults. Nonpositive resolutions are rejected when the export is confirmed. + Export As goes through `options` too: for PNG, JPEG and WebP `useArtboards: true` writes one file per artboard (all, or `range`), named `<file>-<artboard>.<ext>`, and returns `{path, files}` (a PDF keeps them as pages of one file; an SVG writes one file per artboard of a `range`); `useArtboards: false` exports the bounds of the visible art with what diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index eb8aae5389..4252d1eb61 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1994,6 +1994,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur 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); a PDF 1.5 file with such a page is written as PDF 1.6 with PDF 1.5's encryption, PDF/X files and PDF 1.3 and 1.4 files write it in points (in PDF 1.3 and 1.4, a page past 32,767 pt that needs a real number past 32,767 is refused with an error naming it), a page whose short side is 3 pt or longer but would be under 3 units at that `UserUnit` gets a smaller one that keeps the short side at 3 units, and the export's warnings give each such page's size and how it is written (#6382). The Save PDF dialog's "Write pages longer than 200 in at full size in points" (`longPagesInPoints`, on by default; `.ai` saves leave it off) writes such pages in points without a `UserUnit` at every PDF version, in files without a PDF/X or PDF/A standard, so readers that ignore `UserUnit` show them at full size. + Raster export dialogs retain supplied values for their controls, including PNG resolution, background, anti-aliasing and interlacing, and JPEG quality. Omitted values use the dialog defaults; a nonpositive resolution is rejected on confirmation (#8324; `crates/ui-egui/src/dialogs/tests_raster_supplied_options.rs`). Export As PDF with Use Artboards off also opens the Save PDF dialog, without its Artboards section, and writes one page of the visible art's bounds with the dialog's options (`document.exportPdf {useArtboards: false}`; `crates/ui-egui/src/dialogs/tests_export.rs`, `crates/engine/src/cmd/fileio/tests_pdf.rs`). While Alt (Option on macOS) is held, the Save PDF dialog's Cancel button reads Reset, which puts every option back to the chosen preset's settings, passwords included, and leaves the dialog open; letting the key go shows Cancel again (`ui.dialogReset`). [The help page](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=283) says that holding Alt or Option and clicking Reset returns the options to their defaults. Resetting to the chosen preset's settings, and keeping the preset, path, artboard range and section, are VectorCraft's own rules (`crates/ui-egui/src/dialogs/save_pdf/tests.rs`, `crates/ui-egui/src/dialogs/tests.rs`). `document.exportSelection` run without params (a shortcut) takes the same route after its save panel: a picked PDF opens the Save PDF dialog without its Artboards section, and SVG, the raster formats, EPS, DXF, text and exporter plug-ins with parameters open their options, whose OK writes the selection alone, cropped to it, with the chosen options (`crates/ui-egui/src/dialogs/tests_export_selection.rs`). diff --git a/docs/ui-parity.md b/docs/ui-parity.md index b312abae1b..42a8988f24 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -472,6 +472,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Status bar: a click on the info field opens a Show menu that chooses its readout: Artboard Name, Current Tool (the default), Date and Time, Number of Undos (undo and redo counts) or Document Color Profile; kept with the UI state | done | `view.statusBarShow`; [public behavior reference](https://web.archive.org/web/2014/https://helpx.adobe.com/illustrator/using/workspace-basics.html); `the_status_bar_info_field_shows_the_chosen_readout`, `a_click_on_the_info_field_opens_the_show_menu`, `the_status_bar_show_choice_is_checked_and_saved`. The menu labels are VectorCraft's own | | Background Export: a progress dialog with the file name, the artboard count and a bar (busy for one artboard and for formats made in one go), Cancel (Esc) and Continue in Background; it opens after 0.4 s and never over another dialog. A cancelled export writes no file | done | #2564; on the shared `vectorcraft_doc::cancel` token (#2546), so a cancelled render keeps no half-drawn pattern tile or effect raster. The bar moves between artboards, not within one. Save As, Export for Screens and Export Selection don't show it yet | | Swatch, graphic style and symbol library panels: each library opens in a panel of its own, several at once, that floats, groups, docks and closes like any panel; opening an open library brings its panel forward; Previous / Next Library change the library in place; the panel menu's Persistent reopens the panel at startup with its view and find field (a library loaded from a file is read again; when its file is missing the panel reopens showing the file's path with Locate Library…, and the status bar names the file) | done | #2603; panel ids `library:<kind>:<id>`, `ui.libraryPanel {panel, library?, view?, showFind?, persistent?}`, `ui.libraryPanel.locate {panel, path?}`; the library panels have no sort option, as before | +| Raster export dialogs retain supplied values for their controls and apply defaults only to omitted values | done | #8324; `tests_raster_supplied_options` checks PNG resolution, background, anti-aliasing and interlacing through `file.export.png`, JPEG quality, omitted defaults, and invalid resolution rejection | | DXF export/import preserves intended curve closure | done | #1299; R13–2018 closed SPLINE bit set/read; an open curve ending at its start stays open; knots and control points unchanged; circular cubic paths export as native CIRCLE/ARC where stroke semantics permit; DXF Options' Preset menu and `document.exportDxf`'s `dxfPreset: "cnc"` set the CNC / CAM options (#5500) | | macOS save sheet: choose the format from a menu | done | #866; the save panel is VectorCraft's own `NSSavePanel` with its Format menu set before the sheet opens (`apps/vectorcraft/src/mac_save_format.rs`); #1855 had withdrawn the menu that was added after the sheet began, which made Save As, Save a Copy and the first Save show no sheet | | Preferences: every option acts | partial | 2 stored but unused (#394, audited 2026-10-30): Scratch Disks, Legacy vector clipboard; the rest act (Units › East Asian Type since 2026-10-31; Open Documents As Tabs: cleared, new documents open in floating windows). General › Corner Radius drives the Rounded Rectangle tool and follows its ↑/↓ (2026-10-24) | From 64028bceb2e336af3f21c06004d3bc90105ec725 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 17 Nov 2026 06:48:45 -0800 Subject: [PATCH 081/176] Effects: the painted clipping type test checks the region Offset Path grows The Offset Path case of painted_clipping_type_survives_enclosing_geometry_effect now also checks the clip region against the type's own outline grown by 1 pt, so a clip region that skips the effect fails the test even when the fill and stroke art skip it too. --- crates/effects/src/tests/clipfx.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/crates/effects/src/tests/clipfx.rs b/crates/effects/src/tests/clipfx.rs index 0f6ccc5ea6..d13c59f229 100644 --- a/crates/effects/src/tests/clipfx.rs +++ b/crates/effects/src/tests/clipfx.rs @@ -636,6 +636,9 @@ fn painted_clipping_type_survives_enclosing_geometry_effect() { let (region, fills, strokes, inside) = found.unwrap_or_else(|| panic!("{case}: no clip group")); if effect.id == "distort.transform" { assert!((region.y0 - plain.y0 - 10.0).abs() < 0.5 && (region.x0 - plain.x0).abs() < 0.5, "{case}: {region:?} from {plain:?}"); + } else { + let grown = Rect::new(plain.x0 - 1.0, plain.y0 - 1.0, plain.x1 + 1.0, plain.y1 + 1.0); + assert!(near_rect(region, grown), "{case}: {region:?} is {plain:?} offset by 1 pt"); } assert_eq!(fills.is_some(), fill, "{case}: fill art {fills:?}"); assert_eq!(strokes.is_some(), stroke, "{case}: stroke art {strokes:?}"); From 7cabf5647137d5ca7c2cf9984f0f2c4a412a4ce5 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 17 Nov 2026 06:50:42 -0800 Subject: [PATCH 082/176] Scripts: the app idles while a run waits at its file dialog While a script waited at File.openDialog, File.saveDialog or Folder.selectDialog, the frame logic asked for a new frame on every frame. It now skips that request while a file dialog waits, as it does for alert, confirm and prompt; picks::poll still looks for the dialog's answer. --- crates/ui-egui/src/app.rs | 9 +++++++-- crates/ui-egui/src/tests/script_run.rs | 26 ++++++++++++++++++++++++++ 2 files changed, 33 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 5319defaa2..f8c608cc28 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -356,8 +356,13 @@ impl VectorcraftApp { // A panel's, a dialog's or the text input's commit journaled in the frame before. crate::panels::actions::after_journaled_edit(self); crate::scripts_menu::poll(self, ctx); - if self.session.script_running() && !self.session.script_waiting() && self.session.script_dialog().is_none() { - // A script in `$.sleep` goes on when its time is up; until then the app can idle. + if self.session.script_running() + && !self.session.script_waiting() + && self.session.script_dialog().is_none() + && self.session.script_picker().is_none() + { + // A script in `$.sleep` goes on when its time is up; until then the app can idle. A + // script at a file dialog goes on when the dialog answers, and `picks::poll` looks for that. match self.session.script_sleep_left() { Some(left) => ctx.request_repaint_after(left), None => ctx.request_repaint(), diff --git a/crates/ui-egui/src/tests/script_run.rs b/crates/ui-egui/src/tests/script_run.rs index 882799385e..fee27caa13 100644 --- a/crates/ui-egui/src/tests/script_run.rs +++ b/crates/ui-egui/src/tests/script_run.rs @@ -281,6 +281,32 @@ fn a_stop_names_the_files_the_run_left_written() { let _ = std::fs::remove_dir_all(&dir); } +/// While a run waits at its file dialog, the app's frame logic does not ask for a frame on every +/// frame. +#[test] +fn a_run_waiting_at_its_file_dialog_lets_the_app_idle() { + let mut app = app(); + app.session.prefs.show_external_script_warning = false; + menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": "Folder.selectDialog('Folder');" })).unwrap().unwrap(); + script_runs::poll(&mut app); + assert!(app.session.script_picker().is_some(), "the run waits at its folder dialog"); + let ctx = egui::Context::default(); + let mut wait = std::time::Duration::ZERO; + for frame in 0..4 { + let time = f64::from(frame); + app.now_override = Some(time); + let screen_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0))); + let raw = egui::RawInput { screen_rect, time: Some(time), ..Default::default() }; + let mut out = ctx.run_ui(raw, |ui| app.logic(ui.ctx())); + out.textures_delta.clear(); + wait = out.viewport_output.get(&egui::ViewportId::ROOT).map_or(std::time::Duration::MAX, |v| v.repaint_delay); + } + assert!(app.session.script_picker().is_some(), "the run still waits"); + assert!(wait > std::time::Duration::from_millis(100), "{wait:?}: {:?}", ctx.repaint_causes()); + assert!(app.session.script_request_stop()); + finish(&mut app); +} + /// A script's open dialog with `multiSelect` shows the host's dialog for several files, with the /// file types of the script's filter, and the script gets every file picked. #[test] From af09fc206449a8d49400e0efeb9f9a775bcd5e7d Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 17 Nov 2026 07:14:42 -0800 Subject: [PATCH 083/176] Scripts: open files are written in the order they were opened When two File objects held changes to the same file, copy, length, a new open of the file and a withdrawn grant wrote them in no fixed order, so the copy or the file could end up with the older object's bytes. They now write them in the order the objects were opened, as the end of the run does. --- crates/engine/src/script/files.rs | 21 +++++++---- crates/engine/src/tests/script_io.rs | 54 ++++++++++++++++++++++++++++ 2 files changed, 68 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/script/files.rs b/crates/engine/src/script/files.rs index 05f148e714..6eecfeabf8 100644 --- a/crates/engine/src/script/files.rs +++ b/crates/engine/src/script/files.rs @@ -407,8 +407,10 @@ impl Disk { self.writes.remove(&g.path, g.folder); } } - let ids: Vec<u32> = + let mut ids: Vec<u32> = self.open.iter().filter(|(_, o)| o.target.as_deref().is_some_and(|t| !self.writes.allows(t))).map(|(id, _)| *id).collect(); + // In the order the files were opened, as `flush_all` writes them. + ids.sort_unstable(); for id in ids { let written = self.flush(id).is_ok(); if let Some(o) = self.open.get_mut(&id) { @@ -701,8 +703,9 @@ impl Disk { return fail(NOT_FOUND); } // Changes other open objects hold for the file are written before it is opened again, so - // they do not later replace what this one writes. - let ids: Vec<u32> = self.open.iter().filter(|(_, o)| o.target.as_deref() == Some(real.as_path())).map(|(id, _)| *id).collect(); + // they do not later replace what this one writes, in the order they were opened. + let mut ids: Vec<u32> = self.open.iter().filter(|(_, o)| o.target.as_deref() == Some(real.as_path())).map(|(id, _)| *id).collect(); + ids.sort_unstable(); if let Err(m) = ids.iter().try_for_each(|id| self.flush(*id)) { return fail(m); } @@ -1795,8 +1798,10 @@ fn copy(host: &Host, a: &[Data]) -> Result<Data, HostError> { // its open objects are written, and copying could empty it. let one = |t: &std::fs::Metadata| std::fs::metadata(&source).is_ok_and(|s| same_file((&source, &s), (&target, t))); let itself = real_of(&target).is_some_and(|t| t == source) || std::fs::metadata(&target).is_ok_and(|t| one(&t)); - // The source's open objects write what they hold first, so the copy has it. - let ids: Vec<u32> = disk.open.iter().filter(|(_, o)| o.target.as_deref() == Some(source.as_path())).map(|(id, _)| *id).collect(); + // The source's open objects write what they hold first, in the order they were opened, so the + // copy has it. + let mut ids: Vec<u32> = disk.open.iter().filter(|(_, o)| o.target.as_deref() == Some(source.as_path())).map(|(id, _)| *id).collect(); + ids.sort_unstable(); if let Err(m) = ids.iter().try_for_each(|id| disk.flush(*id)) { return Ok(error(m)); } @@ -1988,8 +1993,10 @@ fn set_length(host: &Host, a: &[Data]) -> Result<Data, HostError> { let len = usize::try_from(n).unwrap_or(usize::MAX); let held = disk.open.values().filter(|o| o.holds(&target)).fold(0usize, |sum, o| sum.saturating_add(len.saturating_sub(o.bytes.len()))); disk.charge_write(usize::try_from(n.saturating_sub(m.len())).unwrap_or(usize::MAX).saturating_add(held))?; - // The file's open objects write what they hold first, and then hold the new length. - let ids: Vec<u32> = disk.open.iter().filter(|(_, o)| o.target.as_deref() == Some(target.as_path())).map(|(id, _)| *id).collect(); + // The file's open objects write what they hold first, in the order they were opened, and + // then hold the new length. + let mut ids: Vec<u32> = disk.open.iter().filter(|(_, o)| o.target.as_deref() == Some(target.as_path())).map(|(id, _)| *id).collect(); + ids.sort_unstable(); ids.iter() .try_for_each(|id| disk.flush(*id)) .and_then(|()| std::fs::OpenOptions::new().write(true).open(&target).and_then(|f| f.set_len(n)).map_err(|_| WRITE_FAILED)) diff --git a/crates/engine/src/tests/script_io.rs b/crates/engine/src/tests/script_io.rs index eca6dd5638..7c8c167527 100644 --- a/crates/engine/src/tests/script_io.rs +++ b/crates/engine/src/tests/script_io.rs @@ -908,6 +908,29 @@ fn script_file_copy_of_an_open_file_has_its_changes() { let _ = std::fs::remove_dir_all(base); } +/// Two objects that changed the same file write it in the order they were opened, so the one opened +/// last is written last, before the file is copied, given a new length or opened again. +#[test] +fn script_files_changed_by_two_objects_are_written_in_the_order_they_were_opened() { + let base = folder("twowriters"); + let r = run( + &base, + "var d = Folder.temp.fsName, out = [];\n\ + function two(name) { var p = d + '/' + name, s = new File(p); s.open('w'); s.write('xx'); s.close();\n\ + var a = new File(p), b = new File(p); a.open('e'); b.open('e'); a.write('A'); b.write('B'); return [a, b, p]; }\n\ + function done(h) { h[0].close(); h[1].close(); }\n\ + function text(p) { var f = new File(p); f.open('r'); var t = f.read(); f.close(); return t; }\n\ + for (var i = 0; i < 24; i++) {\n\ + var h = two('c' + i + '.txt'); h[0].copy(d + '/copy.txt'); out.push(text(d + '/copy.txt')); done(h);\n\ + h = two('l' + i + '.txt'); new File(h[2]).length = 1; done(h); out.push(text(h[2]));\n\ + h = two('o' + i + '.txt'); var c = new File(h[2]); c.open('e'); out.push(c.read()); c.close(); done(h);\n\ + }\n\ + vc.log(out.join(','));", + ); + assert_eq!(r["log"], json!([vec!["Bx,B,Bx"; 24].join(",")]), "{r}"); + let _ = std::fs::remove_dir_all(base); +} + /// An object that has a file open for reading holds what `copy` writes over the file and the length /// `length` sets, as an object open for writing does, also after the file is renamed, and not after /// it is removed. @@ -1995,6 +2018,37 @@ fn script_files_open_under_a_withdrawn_grant_keep_their_unwritten_changes() { let _ = std::fs::remove_dir_all(base); } +/// Files opened for writing under a kept grant that new code withdraws are written in the order +/// they were opened, so the object opened last is written last. +#[test] +fn script_files_open_under_a_withdrawn_grant_are_written_in_the_order_they_were_opened() { + let base = folder("grantwithdrawnorder"); + let dir = base.join("picked"); + std::fs::create_dir_all(&dir).unwrap(); + let out = dir.join("out.txt"); + let text = format!( + "var f = new File({:?});\n\ + if (!f.open('w')) vc.log(['asked', !!Folder.selectDialog('p')]);\n\ + else {{ f.write('x'); var all = [f];\n\ + for (var i = 1; i < 64; i++) {{ var g = new File(f.fsName); g.open('e'); all.push(g); }}\n\ + for (var i = 0; i < 64; i++) all[i].write(('0' + i).slice(-2));\n\ + eval('1'); vc.log(['wrote']); }}", + out.to_string_lossy() + ); + let mut s = with_data(&base); + start_framed(&mut s, &base, &text); + assert!(pump_to_picker(&mut s).is_none()); + assert!(s.script_pick(crate::script::files::PickAnswer::Allow { paths: vec![dir.to_string_lossy().into_owned()], always: true })); + assert_eq!(pump_to_picker(&mut s).unwrap().unwrap()["log"], json!([["asked", true]])); + start_framed(&mut s, &base, &text); + let r = pump_to_picker(&mut s).unwrap(); + let report = s.script_report().unwrap(); + assert!(r.is_ok(), "{report}"); + assert_eq!(report["log"], json!([["wrote"]]), "{report}"); + assert_eq!(std::fs::read(&out).unwrap(), b"63", "{report}"); + let _ = std::fs::remove_dir_all(base); +} + /// A file opened for reading under a kept grant that new code withdraws gives no more of what it /// holds. #[test] From d080f0fb85d1ca38d4092b49b9a78b44eacaeb9e Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 17 Nov 2026 07:00:43 -0800 Subject: [PATCH 084/176] Font menu: Small, Medium and Large set the sample size from inside the menu MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Part of #6889. While the samples are shown, a row under the filters offers Small, Medium and Large, as the font browser overview and the user guide describe the sample size control. With Enable in-menu font previews off, the row is not shown, as the user guide describes. VectorCraft's own rules: a click sets Preferences › Type › Font Preview Size (`fontPreviewSize`), so every font menu takes the new row height, and the host writes the preferences file as it does when Preferences is confirmed. The current size is selected, and a click on it changes nothing. A saved value that is none of the three sizes shows Medium, and a click replaces it. The change adds no undo step and leaves a font previewed on the selected type in place. https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/font-options-overview.html https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=485 Docs: docs/target-app-parity.md evidence line. --- crates/ui-egui/src/app.rs | 1 + crates/ui-egui/src/font_menu.rs | 82 +++++++++++++++++++++---- crates/ui-egui/src/font_menu/tests.rs | 86 +++++++++++++++++++++++++++ docs/target-app-parity.md | 1 + 4 files changed, 158 insertions(+), 12 deletions(-) diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index e3d2a13d64..da6fe02592 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -576,6 +576,7 @@ impl VectorcraftApp { self.ime_caret_rect = None; scrub::begin_frame(self, &ctx); font_menu::end_stale_preview(self, &ctx); + font_menu::apply_preview_size(self, &ctx); tools_float::track(self, &ctx); // A selection move released over a panel ends before any panel sees the release (#2826). canvas::release_over_panel(self, &ctx); diff --git a/crates/ui-egui/src/font_menu.rs b/crates/ui-egui/src/font_menu.rs index d5368d1fa4..5e48887c61 100644 --- a/crates/ui-egui/src/font_menu.rs +++ b/crates/ui-egui/src/font_menu.rs @@ -13,9 +13,11 @@ //! they look to it ([`vectorcraft_text::FontDb::similar_families`]), that family first and without the Recent //! Fonts section, until the ≈ chip under the filters clears it or the menu closes. The Font //! Technology filter's Variable lists only variable font families. Preferences › Type › Enable -//! in-menu font previews and Font Preview Size turn the samples off or size the rows. The menu lays -//! out its filters on the same five rows wherever it opens. However narrow its field, it opens at -//! least wide enough for those rows and for a family name up to 220 points wide with its sample +//! in-menu font previews and Font Preview Size turn the samples off or size the rows. While the +//! samples are shown, a row under the filters sets Font Preview Size to Small, Medium or Large +//! ([`apply_preview_size`]), which sizes the rows of every font menu. The menu lays +//! out its filters on the same five rows wherever it opens, with the size row under them while the +//! samples are shown. However narrow its field, it opens at least wide enough for those rows and for a family name up to 220 points wide with its sample //! beside it, up to 60% of the window; each sample fills its row's height. Recently used families //! appear first, in the order they were last applied, within the same search and filters as the //! remaining families. In the Character and Properties panels and the Control bar, @@ -185,11 +187,7 @@ impl Default for MenuLook<'static> { impl<'a> MenuLook<'a> { pub fn of(app: &'a VectorcraftApp) -> Self { - let row = match app.session.prefs.font_preview_size.as_str() { - "small" => 20.0, - "large" => 32.0, - _ => ROW, - }; + let row = preview_row(&app.session.prefs.font_preview_size); Self { samples: app.session.prefs.font_preview, on_white: app.session.prefs.font_samples_on_white, @@ -211,6 +209,22 @@ impl<'a> MenuLook<'a> { /// Height of a row, in points (Font Preview Size: Medium). const ROW: f32 = 24.0; +/// Font Preview Size's values (Preferences › Type), each with the row height it gives. +const PREVIEW_SIZES: [(&str, f32); 3] = [("small", 20.0), ("medium", ROW), ("large", 32.0)]; + +/// The row height of Font Preview Size `size`: Medium's for a value it does not have. +fn preview_row(size: &str) -> f32 { + PREVIEW_SIZES.iter().find(|(key, _)| *key == size).map_or(ROW, |(_, row)| *row) +} + +/// The label of Font Preview Size `size`, as Preferences names it. +fn preview_size_label(size: &str) -> &'static str { + match size { + "small" => tl!("Small"), + "large" => tl!("Large"), + _ => tl!("Medium"), + } +} /// Width of the star at the end of a family's row. const STAR: f32 = 18.0; /// Width of the Show Similar Fonts button before the star. @@ -1307,7 +1321,7 @@ fn header<'s>(ui: &mut Ui, db: &'s vectorcraft_text::FontDb, state_id: egui::Id, ui.memory_mut(|m| m.request_focus(field.with("edit"))); } let query = widgets::search_field(ui, field, tl!("Search")).to_lowercase(); - let refilter = filters(ui, st, &t, look.document.is_some()); + let refilter = filters(ui, st, &t, look.document.is_some(), look.samples.then_some(look.row)); let added = added_families(db, st, look); // On the system clock, the list is drawn again when a family's 30 days end. if let (Some(at), None) = (added.as_ref().and_then(|a| a.recheck_at), look.clock) @@ -1440,9 +1454,11 @@ fn filter_rows() -> [Vec<Chip>; 5] { } /// The filters on their rows ([`filter_rows`]): a row wraps only where the menu is narrower than -/// it. The Document filter is unavailable without a `document`. Records in `st` the width of the -/// widest row unwrapped; whether a filter changed. -fn filters(ui: &mut Ui, st: &mut MenuState, t: &Tokens, document: bool) -> bool { +/// it. The Document filter is unavailable without a `document`. With `row` (the rows' height while +/// samples are shown), a row under them offers Font Preview Size's values, the one of that height +/// selected; a click on one asks for it ([`apply_preview_size`]). Records in `st` the width of the +/// widest row unwrapped, the size row included; whether a filter changed. +fn filters(ui: &mut Ui, st: &mut MenuState, t: &Tokens, document: bool, row: Option<f32>) -> bool { let mut refilter = false; let mut widest = 0.0_f32; for row in filter_rows() { @@ -1492,6 +1508,23 @@ fn filters(ui: &mut Ui, st: &mut MenuState, t: &Tokens, document: bool) -> bool widest = widest.max(width); }); } + if let Some(row) = row { + ui.horizontal_wrapped(|ui| { + ui.spacing_mut().item_spacing = vec2(4.0, 2.0); + let gap = ui.spacing().item_spacing.x; + let text = |s: &str| egui::RichText::new(s).size(FILTER_SIZE); + let mut width = ui.label(text(tl!("Font Preview Size")).color(t.text_dim)).rect.width(); + for (size, height) in PREVIEW_SIZES { + let on = (height - row).abs() < 0.5; + let resp = ui.selectable_label(on, text(preview_size_label(size))); + width += gap + resp.rect.width(); + if resp.clicked() { + ui.data_mut(|d| d.insert_temp(preview_size_id(), size)); + } + } + widest = widest.max(width); + }); + } st.filters = widest; // While Show Similar Fonts orders the list: the family it orders by, which clears it. Its // width is left out of the widest row: a long name wraps instead of widening the menu. @@ -2027,6 +2060,31 @@ fn open_id() -> egui::Id { egui::Id::unique("font-menu-open") } +/// The id under which a font menu keeps the Font Preview Size its buttons asked for, until +/// [`apply_preview_size`] sets it. +fn preview_size_id() -> egui::Id { + egui::Id::unique("font-menu-preview-size") +} + +/// Set the Font Preview Size (Preferences › Type) that a font menu's Small, Medium or Large button +/// asked for in the last pass, which sizes the rows of every font menu, and have the host write the +/// preferences file as it does when Preferences is confirmed. Nothing runs when it is already that +/// size; a saved value that is none of the sizes is replaced. The shell calls it at the start of +/// each frame. +pub(crate) fn apply_preview_size(app: &mut VectorcraftApp, ctx: &egui::Context) { + let Some(size) = ctx.data_mut(|d| d.remove_temp::<&'static str>(preview_size_id())) else { return }; + if app.session.prefs.font_preview_size == size { + return; + } + match app.run("prefs.set", json!({"key": "fontPreviewSize", "value": size})) { + Ok(_) => { + crate::prefs_dialog::snapshot(app); + app.prefs_changed = true; + } + Err(e) => app.ui.status = e, + } +} + /// Undo a preview whose menu is gone (its panel wasn't drawn: the text was deselected, the panel /// closed) or is closing (Escape, a press outside the menu), before anything else sees this /// frame's input: the canvas must not act inside the preview's interaction (a drag would be diff --git a/crates/ui-egui/src/font_menu/tests.rs b/crates/ui-egui/src/font_menu/tests.rs index 958a6c1af1..2f06f9f41f 100644 --- a/crates/ui-egui/src/font_menu/tests.rs +++ b/crates/ui-egui/src/font_menu/tests.rs @@ -1468,3 +1468,89 @@ fn the_recently_added_filter_lists_a_font_installed_just_now() { assert!(st.rows.is_empty(), "31 days later: {:?}", st.rows); std::fs::remove_dir_all(&dir).unwrap(); } + +/// While the samples are shown, a row under the filters offers Font Preview Size's Small, Medium +/// and Large at every size of the rows: a click on one asks for that size ([`super::apply_preview_size`] +/// leaves the rows' own size as it is). Without samples the row is not drawn. +#[test] +fn the_preview_size_row_asks_for_the_size_clicked() { + // The bundled fonts alone: fonts that tests running alongside add stay out of the rows. + let db = vectorcraft_text::FontDb::with_font_dirs(vec![]); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut st = super::MenuState::default(); + for size in ["small", "medium", "large"] { + let look = super::MenuLook { row: super::preview_row(size), ..Default::default() }; + let shapes = settle_menu_of(&ctx, &db, &mut st, look, vec![]); + assert!(text_at(&shapes, |t| t == "Font Preview Size").is_some(), "the row is drawn at {size}"); + let mut click = |label: &str| { + let shapes = settle_menu_of(&ctx, &db, &mut st, look, vec![]); + let at = text_at(&shapes, |t| t == label).unwrap_or_else(|| panic!("{label} is drawn at {size}")); + let button = + |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + settle_menu_of(&ctx, &db, &mut st, look, vec![egui::Event::PointerMoved(at), button(true)]); + settle_menu_of(&ctx, &db, &mut st, look, vec![button(false)]); + ctx.data_mut(|d| d.remove_temp::<&'static str>(super::preview_size_id())) + }; + assert_eq!(click("Large"), Some("large"), "at {size}"); + assert_eq!(click("Small"), Some("small"), "at {size}"); + assert_eq!(click("Medium"), Some("medium"), "at {size}"); + } + let look = super::MenuLook { row: super::preview_row("medium"), ..Default::default() }; + let shapes = settle_menu_of(&ctx, &db, &mut st, super::MenuLook { samples: false, ..look }, vec![]); + assert!(text_at(&shapes, |t| t == "Font Preview Size").is_none(), "without samples the row is not drawn"); + super::wait_for_samples(&ctx); +} + +/// The size a font menu's button asked for becomes Font Preview Size, which sizes every font +/// menu's rows, and the host is asked to write the preferences file. The document is left as it +/// was: a font previewed on the selected type stays previewed, and the change adds no undo step. +#[test] +fn a_preview_size_asked_for_sets_the_preference_and_keeps_the_preview() { + let ctx = egui::Context::default(); + let mut app = app_with_type(&[]); + let id = app.run("text.create", serde_json::json!({"x": 20, "y": 90, "text": "Size", "font": "Inter"})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", serde_json::json!({"ids": [id]})).unwrap(); + let font = |app: &crate::VectorcraftApp| match &app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().kind { + vectorcraft_doc::NodeKind::Text(t) => t.first_style().font_family, + _ => String::new(), + }; + super::apply(&mut app, &ctx, super::FontPick::Preview("Source Serif 4".into(), None)); + assert_eq!(font(&app), "Source Serif 4"); + assert_eq!(super::MenuLook::of(&app).row, super::preview_row("medium")); + assert!(!app.take_prefs_changed(), "nothing to write yet"); + let undo_depth = |app: &crate::VectorcraftApp| app.session.doc().unwrap().history.undo.len(); + let depth = undo_depth(&app); + // The rows' own size: nothing changes. + ctx.data_mut(|d| d.insert_temp(super::preview_size_id(), "medium")); + super::apply_preview_size(&mut app, &ctx); + assert_eq!(app.session.prefs.font_preview_size, "medium"); + assert!(!app.take_prefs_changed(), "nothing to write for the size the rows have"); + ctx.data_mut(|d| d.insert_temp(super::preview_size_id(), "large")); + super::apply_preview_size(&mut app, &ctx); + assert_eq!(app.session.prefs.font_preview_size, "large"); + assert_eq!(undo_depth(&app), depth, "the size is not an undo step"); + assert_eq!(super::MenuLook::of(&app).row, super::preview_row("large")); + assert!(app.take_prefs_changed(), "the host is asked to write the preferences file"); + assert_eq!(app.ui.engine_prefs["fontPreviewSize"], "large"); + assert!(app.session.in_interaction(), "the preview is still open"); + assert_eq!(font(&app), "Source Serif 4", "the preview stays on the type"); + // Asked for once, applied once. + super::apply_preview_size(&mut app, &ctx); + assert_eq!(app.session.prefs.font_preview_size, "large"); + assert!(!app.take_prefs_changed(), "nothing more to write"); + // A saved value that is none of the sizes draws Medium's rows, and Medium replaces it. + app.session.prefs.font_preview_size = "huge".into(); + assert_eq!(super::MenuLook::of(&app).row, super::preview_row("medium")); + ctx.data_mut(|d| d.insert_temp(super::preview_size_id(), "medium")); + super::apply_preview_size(&mut app, &ctx); + assert_eq!(app.session.prefs.font_preview_size, "medium"); + assert!(app.take_prefs_changed(), "the replaced value is written"); + super::apply(&mut app, &ctx, super::FontPick::EndPreview); + assert_eq!(font(&app), "Inter"); + app.run("edit.undo", serde_json::json!({})).unwrap(); + assert!( + app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id)).is_none(), + "undo takes the type away: no step was added for the size" + ); +} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index db61a96f73..dddfbe44bf 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1882,6 +1882,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur The font menu's Font Technology › Variable (under the kind filter, as [Find, apply, and adjust variable fonts](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/find-apply-and-adjust-variable-fonts.html) places Variable in the classification filter's Font Technology section) lists only the families with variation axes, a family with a variable file beside static ones included, and works together with the script, kind, ★ and search filters; it stays set from one opening to the next. Measured by `font_menu::tests::the_variable_filter_lists_only_variable_families`, `font_menu::tests::the_variable_filter_is_named_as_fonts_are`, `tests_axes::a_family_with_variation_axes_is_variable` and `tests_sysfonts::a_family_with_a_variable_file_beside_static_ones_is_variable`. The font menu's Document filter (beside ★) lists only the families that type in the current document is set in, as the quick filter for fonts used in the document does on the [font browser overview](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/font-options-overview.html). It works together with the search, script, kind, Variable and ★ filters, Recent Fonts and Show Similar Fonts, steers the closed field's wheel, follows edits and undo while the menu is open, and is shared by every font menu for the session like the other filters. VectorCraft's own rules: hidden, locked, masked, symbol, pattern and graph design type counts, styles no type uses do not, a composite font lists under its own name, a family the document names but this computer lacks is not listed (Find Font reports it), a document without available fonts lists nothing with its own message, and with no document open the filter is unavailable. Measured by `font_menu::tests::the_document_filter_lists_the_families_the_documents_type_uses`, `font_menu::tests::the_document_filter_combines_with_the_others_and_follows_edits`, `font_menu::tests::the_document_filter_counts_type_in_graph_designs` and `font_menu::tests::the_document_filter_on_an_empty_document_or_none`. The font menu's Recently Added filter (on its own row under Font Technology) lists only the installed families added in the last 30 days, the newest at the top, as the [user guide](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=486) and the [font browser overview](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/font-options-overview.html) describe it (`vectorcraft_text::FontDb::recently_added`). It works together with the search, script, kind, Variable, ★ and Document filters, lists only the families every active filter matches, steers the closed field's wheel, and is shared by every font menu for the session like the other filters. VectorCraft's own rules: a family is dated by the creation time of its newest font file on this computer (a file the file system keeps no creation time for, or one dated in the future, does not count), the 30th day is included, families added at the same instant are in name order, the recently used families appear in that order without the Recent Fonts section, Show Similar Fonts orders only the families the filter lists, a family leaves the list when its 30 days end while the menu is open, an empty list keeps the filter on and says no fonts match, and fonts bundled with the app or loaded from documents are never listed. Measured by `font_menu::tests::the_recently_added_filter_lists_new_families_newest_first`, `font_menu::tests::the_recently_added_filter_drops_families_as_their_30_days_end`, `font_menu::tests::the_recently_added_filter_lists_a_font_installed_just_now`, `tests::recently_added::families_added_in_the_last_30_days_are_listed_newest_first`, `tests::recently_added::a_family_is_dated_by_its_newest_valid_file` and `tests::sysfonts::installed_fonts_are_recently_added_by_their_files_creation_time`. + While the samples are shown, the font menu's row under the filters sets the sample size to Small, Medium or Large from inside the menu, as the [font browser overview](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/font-options-overview.html) and the [user guide](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=485) describe the sample size control; with Enable in-menu font previews off, the row is not shown, as the user guide describes. VectorCraft's own rules: the row sits under the filters and sets Preferences › Type › Font Preview Size (`fontPreviewSize`), so every font menu takes the new row height, the Composite Fonts and Dimension dialogs' included; the current size is selected and a click on it changes nothing; a saved value that is none of the three sizes shows Medium and a click replaces it; the change adds no undo step and leaves a font previewed on the selected type in place. Measured by `font_menu::tests::the_preview_size_row_asks_for_the_size_clicked` and `font_menu::tests::a_preview_size_asked_for_sets_the_preference_and_keeps_the_preview`. The font database looks up a name that is neither a loaded nor an installed family among the other names of the loaded and installed fonts once for each style it is asked in, and keeps the answer until fonts are added or rescanned. Laying out a story of 1,000 paragraphs set in a font that is not installed, with 400 more fonts loaded, takes a median of 56 to 71 ms instead of 409 to 507 ms on Windows 11 (`CRAFT_FONTS_DIR=<craft-fonts checkout> cargo test --release -p vectorcraft-text --lib missing_font_story_layout_timing -- --ignored --nocapture`). A font family removed while the app runs leaves the font menus when the app scans the font folders again (when its window comes to the front after a font folder changed, or Refresh Font List), also when type had used it: that type then draws in the fallback font and Find Font lists the font as missing, until the font is installed again and the folders are scanned. - **Files (M4):** From 12977ec5439169a2ac3ff335e66a7be3a261c03b Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 17 Nov 2026 05:52:02 -0800 Subject: [PATCH 085/176] Fix #1954: PDF/X CMYK in the output intent's profile is written as DeviceCMYK A PDF/X-3 or PDF/X-4 export tagged every CMYK color with an ICC-based space of the same profile that the output intent embeds. In PDF/X-3 and PDF/X-4, CMYK colors in the profile of a CMYK output intent are now DeviceCMYK, and the profile is written once, as the output intent's DestOutputProfile (ISO 32000-1, 14.11.5: https://opensource.adobe.com/dc-acrobat-sdk-docs/pdfstandards/PDF32000_2008.pdf#page=641). - With output.profiles none and a CMYK output intent, PDF/X-3 and PDF/X-4 write every CMYK color as DeviceCMYK, unless colors are converted to a CMYK destination of another profile, which keeps its tag. Before, those standards tagged every color whatever profiles said. - RGB and gray colors stay tagged, and so do CMYK colors and images in another profile. - A CMYK image that carries the output intent's profile is DeviceCMYK, and so is every CMYK image when none makes CMYK colors DeviceCMYK. A CMYK JPEG then loses its ICC_PROFILE segments. - Transparency groups blend in DeviceCMYK when CMYK colors are DeviceCMYK, also when the file has no ICC-based CMYK space. - Files without a standard keep the tags that profiles asks for. - The Save PDF dialog's note for PDF/X-3 and PDF/X-4 says that CMYK colors in the output intent's profile are written as DeviceCMYK. Docs: docs/mcp.md, docs/target-app-parity.md and the document.exportPdf params text. --- crates/engine/src/cmd/fileio/pdf.rs | 2 +- crates/engine/src/tests/live.rs | 11 ++- crates/engine/tests/it/dimensions.rs | 12 +++- crates/pdf/src/export/writer.rs | 46 ++++++++----- crates/pdf/src/output.rs | 60 +++++++++++++--- crates/pdf/src/pdfx.rs | 8 ++- crates/pdf/src/tests/cmykimages.rs | 46 ++++++++++++- crates/pdf/src/tests/output.rs | 95 ++++++++++++++++++++------ crates/ui-egui/src/dialogs/save_pdf.rs | 7 ++ crates/ui-egui/src/i18n/bg.tsv | 1 + crates/ui-egui/src/i18n/bs.tsv | 1 + crates/ui-egui/src/i18n/ca.tsv | 1 + crates/ui-egui/src/i18n/cs.tsv | 1 + crates/ui-egui/src/i18n/da.tsv | 1 + crates/ui-egui/src/i18n/de.tsv | 1 + crates/ui-egui/src/i18n/el.tsv | 1 + crates/ui-egui/src/i18n/es.tsv | 1 + crates/ui-egui/src/i18n/fi.tsv | 1 + crates/ui-egui/src/i18n/fr.tsv | 1 + crates/ui-egui/src/i18n/gu.tsv | 1 + crates/ui-egui/src/i18n/hi.tsv | 1 + crates/ui-egui/src/i18n/hu.tsv | 1 + crates/ui-egui/src/i18n/id.tsv | 1 + crates/ui-egui/src/i18n/it.tsv | 1 + crates/ui-egui/src/i18n/ja.tsv | 1 + crates/ui-egui/src/i18n/ka.tsv | 1 + crates/ui-egui/src/i18n/ko.tsv | 1 + crates/ui-egui/src/i18n/nl.tsv | 1 + crates/ui-egui/src/i18n/pl.tsv | 1 + crates/ui-egui/src/i18n/pt-br.tsv | 1 + crates/ui-egui/src/i18n/ru.tsv | 1 + crates/ui-egui/src/i18n/sv.tsv | 1 + crates/ui-egui/src/i18n/tr.tsv | 1 + crates/ui-egui/src/i18n/uk.tsv | 1 + crates/ui-egui/src/i18n/vi.tsv | 1 + crates/ui-egui/src/i18n/zh-hans.tsv | 1 + crates/ui-egui/src/i18n/zh-hant.tsv | 1 + docs/mcp.md | 20 ++++-- docs/target-app-parity.md | 6 +- 39 files changed, 275 insertions(+), 66 deletions(-) diff --git a/crates/engine/src/cmd/fileio/pdf.rs b/crates/engine/src/cmd/fileio/pdf.rs index 75e2dba02b..21e6a2a161 100644 --- a/crates/engine/src/cmd/fileio/pdf.rs +++ b/crates/engine/src/cmd/fileio/pdf.rs @@ -128,7 +128,7 @@ pub fn specs() -> Vec<CommandSpec> { "Export PDF", [], None, - "{path?, preset?: \"VectorCraft Default\" (built-in or saved: pdf.preset.list), artboard? | artboards?: [i…] | range?: \"1-3, 5\" (1-based; default all, one page each), useArtboards?: true (false: one page, the bounds of the visible art the page draws (non-printing layers left out unless includeNonPrinting or createLayers keeps them), as document.export writes it; artboard, artboards and range are then ignored, Preserve Editing is left out (with a warning when it is on), and a document with no visible art is refused), standard?: none|pdfA2b|pdfX1a (CMYK, grey and spot colours only: colours and images converted to output.destination or the CMYK output intent, untagged; transparency flattened with flattenerPreset; PDF 1.3)|pdfX3 (colours ICC-tagged; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged; PDF 1.6 at most) (PDF/X: a /GTS_PDFX output intent, by default the CMYK profile in effect, embedded; TrimBox, Trapped, GTS_PDFXVersion, title and dates; fonts embedded or outlined), compatibility?: 1.3 (no transparency: it is flattened with flattenerPreset, without the layers the file leaves out; images keep no see-through pixels)|1.4|1.5|1.6|1.7 (default)|2.0 (choosing a standard sets its version: 1.7 for pdfA2b, 1.6 for pdfX4, 1.3 for pdfX1a and pdfX3, which write 1.4 as 1.3 too; pdfA2b refuses 1.3; in pdfA2b files, and with longPagesInPoints: false, a page with a side longer than 14,400 pt keeps its size with a UserUnit from 1.6 on: 1.5 is then written as 1.6, with 1.5's encryption, and so is 1.4 in pdfA2b files, with a warning; PDF/X files and other 1.3 and 1.4 files write it in points, and 1.3 and 1.4 (pdfX1a and pdfX3 too) refuse a page past 32,767 pt whose size or art needs a real number past 32,767; a page whose short side is 3 pt or longer but would be under 3 units at that UserUnit gets a smaller one that keeps the short side at 3 units; a warning gives each such page's size), longPagesInPoints?: true (such a page is written at its size in points, without a UserUnit, at every version, and 1.5 stays 1.5, in files without a standard (PDF/A files keep the UserUnit); apps that keep to the limit cut it to 200 in; false: the UserUnit as above, with a warning that names this option), preserveEditing? (on in VectorCraft Default: the native document as an embedded file, which document.open restores; choosing a standard turns it off, a standard refuses it), thumbnails? (each page drawn as a /Thumb image, 106 px on its long side), fastWebView? (a linearised file: the first page shows while the rest downloads; it stays linearised when encrypted), viewAfterSaving? (the app opens the written file), createLayers? (each layer and sublayer but template layers as a PDF layer, an optional content group listed under its layer's: hidden layers off, non-printing ones /PrintState /OFF, locked ones locked; needs 1.5 or later; they reopen as layers; choosing pdfX1a or pdfX3 turns it off; they refuse it), includeNonPrinting? (keep layers whose Print option is off; left out by default unless createLayers), flattenerPreset?: \"\" (High Resolution) | high | medium | low | a saved preset (flattener.presets.list): what PDF 1.3 files flatten transparency with, flattener?: {object.flattenTransparency options over it}, compression?: {color?, gray?: {downsample: none|average|subsample|bicubic, ppi: 300, abovePpi: 450, compression: none|zip|jpeg|jpeg2000|auto, quality: minimum|low|medium|high|maximum}, mono?: {downsample, ppi: 1200, abovePpi: 1800, compression: none|ccittG3|ccittG4|zip|runLength} (black-and-white images), compressText?: true} (images above abovePpi are resampled to ppi; auto keeps JPEGs JPEG, the others lossless; JPEG needs opaque images; none, jpeg2000, CCITT and runLength are written as ZIP with a warning), marks?: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25 (trim marks and targets), offset: 6 (pt from the artboard, at least the bleed)} (printer's marks in [Registration], every plate: trim marks, registration targets mid-side, CMYK/spot/black-tint colour bars on top, page information (title, artboard, date UTC) below), bleed?: {useDocument (the document's bleed, document.setup), top, bottom, left, right} (pt; art in the bleed is kept; a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning). Each page: TrimBox = artboard, BleedBox = artboard + bleed, MediaBox = that + the marks' room (art clipped to the BleedBox), output?: {conversion: none (default)|destination (every colour into the destination profile's model, CMYK or RGB, also colours of that model in another profile)|preserveNumbers (only colours of the other model and Lab; those in the destination's model keep their numbers) (grey stays grey; images are converted too, and with destination and an sRGB destination a gray or RGB image tagged with an ICC profile is converted from it and written untagged; with destination and a CMYK destination, or another RGB one images are converted to (not when colours are ICC-tagged), an RGB image tagged with one is converted from it through sRGB; with preserveNumbers (and pdfX1a) only untagged images keep their numbers: an RGB image tagged with one is converted from it to sRGB or through sRGB to the destination, and a gray one is converted from it in an sRGB destination; any other image whose colors are converted (a CMYK image, an RGB one going to a CMYK destination, or with destination to an RGB one other than sRGB) but whose pixels can't be decoded or written that way is left out with a warning; printer's marks are not), destination: profile name (edit.colorSettings lists them; default: the document's profile for its colour mode), profiles: none (device colours; images are written without the ICC profiles they carry, a JPEG without its ICC_PROFILE segments, but in PDF/A, pdfX3 and pdfX4)|all|destination|taggedSource (documents assigned a profile: edit.assignProfile)|default (not set, the default; \"default\" unsets a preset's value, null keeps it: device colours, and gray and RGB images keep the profiles they carry, but in pdfX1a) (ICC-based colours: CMYK with the destination or document CMYK profile, RGB as sRGB, grey with the sRGB tone curve; PDF/A, pdfX3 and pdfX4 always, whatever profiles says; a CMYK image that keeps its numbers carries the CMYK profile it embeds with all and taggedSource, and in PDF/A, pdfX3 and pdfX4 unless destination, never in pdfX1a), outputIntent: profile name (embedded as the catalog's /GTS_PDFX output intent; a name that isn't a profile is only named, which pdfX1a and pdfX3 allow only with a registry and pdfX4 refuses; pdfX1a needs a CMYK one), outputCondition, outputConditionId (default: outputIntent), registry, trapped (/Trapped /True; /False when an output intent is written)} (PDF/A files keep their own output intent), advanced?: {fontSubsetPercent: 100 (below 100 is accepted with a warning: fonts are always embedded as subsets), outlineText: false (type as real, selectable and searchable text in embedded subset fonts with a ToUnicode map; fonts whose licence forbids embedding, or allows only whole fonts, stay outlines with a warning; true: every glyph as an outline), overprint: preserve (overprinting fills and strokes set /OP /op true, /OPM 1; white ones knock out with document.setup discardWhiteOverprint)|discard (they knock out)}, security?: {openPassword, permissionsPassword, printing: none|low|high, changes: none|pages|forms|comments|any, copy, screenReader, plaintextMetadata}, acknowledgeLoss?: bool (write over the file the document was read from although reading it left things out), format?: \"pdf\"} → {path, bytes, warnings}; no path → {dataBase64, bytes, warnings}. The options apply over the preset (null keeps its value); options accepted but not applied yet come back as warnings; a standard with a PDF version it doesn't allow and a password with a standard are refused, and so is a PDF/X file that would still break its standard (transparency the flattener left, RGB in pdfX1a, a font not embedded) or a PDF 1.3 file with transparency left. document.export {format: pdf} takes the same options. A key PDF doesn't take, and an unknown key inside one of the option objects, are refused. Under automation read roots, a PDF that carries the native document (preserveEditing on, every artboard, useArtboards not false) is refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked)", + "{path?, preset?: \"VectorCraft Default\" (built-in or saved: pdf.preset.list), artboard? | artboards?: [i…] | range?: \"1-3, 5\" (1-based; default all, one page each), useArtboards?: true (false: one page, the bounds of the visible art the page draws (non-printing layers left out unless includeNonPrinting or createLayers keeps them), as document.export writes it; artboard, artboards and range are then ignored, Preserve Editing is left out (with a warning when it is on), and a document with no visible art is refused), standard?: none|pdfA2b|pdfX1a (CMYK, grey and spot colours only: colours and images converted to output.destination or the CMYK output intent, untagged; transparency flattened with flattenerPreset; PDF 1.3)|pdfX3 (colours ICC-tagged, CMYK in the output intent's profile as DeviceCMYK; transparency flattened; PDF 1.3)|pdfX4 (transparency and layers kept; colours ICC-tagged, CMYK in the output intent's profile as DeviceCMYK; PDF 1.6 at most) (PDF/X: a /GTS_PDFX output intent, by default the CMYK profile in effect, embedded; TrimBox, Trapped, GTS_PDFXVersion, title and dates; fonts embedded or outlined), compatibility?: 1.3 (no transparency: it is flattened with flattenerPreset, without the layers the file leaves out; images keep no see-through pixels)|1.4|1.5|1.6|1.7 (default)|2.0 (choosing a standard sets its version: 1.7 for pdfA2b, 1.6 for pdfX4, 1.3 for pdfX1a and pdfX3, which write 1.4 as 1.3 too; pdfA2b refuses 1.3; in pdfA2b files, and with longPagesInPoints: false, a page with a side longer than 14,400 pt keeps its size with a UserUnit from 1.6 on: 1.5 is then written as 1.6, with 1.5's encryption, and so is 1.4 in pdfA2b files, with a warning; PDF/X files and other 1.3 and 1.4 files write it in points, and 1.3 and 1.4 (pdfX1a and pdfX3 too) refuse a page past 32,767 pt whose size or art needs a real number past 32,767; a page whose short side is 3 pt or longer but would be under 3 units at that UserUnit gets a smaller one that keeps the short side at 3 units; a warning gives each such page's size), longPagesInPoints?: true (such a page is written at its size in points, without a UserUnit, at every version, and 1.5 stays 1.5, in files without a standard (PDF/A files keep the UserUnit); apps that keep to the limit cut it to 200 in; false: the UserUnit as above, with a warning that names this option), preserveEditing? (on in VectorCraft Default: the native document as an embedded file, which document.open restores; choosing a standard turns it off, a standard refuses it), thumbnails? (each page drawn as a /Thumb image, 106 px on its long side), fastWebView? (a linearised file: the first page shows while the rest downloads; it stays linearised when encrypted), viewAfterSaving? (the app opens the written file), createLayers? (each layer and sublayer but template layers as a PDF layer, an optional content group listed under its layer's: hidden layers off, non-printing ones /PrintState /OFF, locked ones locked; needs 1.5 or later; they reopen as layers; choosing pdfX1a or pdfX3 turns it off; they refuse it), includeNonPrinting? (keep layers whose Print option is off; left out by default unless createLayers), flattenerPreset?: \"\" (High Resolution) | high | medium | low | a saved preset (flattener.presets.list): what PDF 1.3 files flatten transparency with, flattener?: {object.flattenTransparency options over it}, compression?: {color?, gray?: {downsample: none|average|subsample|bicubic, ppi: 300, abovePpi: 450, compression: none|zip|jpeg|jpeg2000|auto, quality: minimum|low|medium|high|maximum}, mono?: {downsample, ppi: 1200, abovePpi: 1800, compression: none|ccittG3|ccittG4|zip|runLength} (black-and-white images), compressText?: true} (images above abovePpi are resampled to ppi; auto keeps JPEGs JPEG, the others lossless; JPEG needs opaque images; none, jpeg2000, CCITT and runLength are written as ZIP with a warning), marks?: {trim, registration, colorBars, pageInfo, kind: roman|japanese, weight: 0.25 (trim marks and targets), offset: 6 (pt from the artboard, at least the bleed)} (printer's marks in [Registration], every plate: trim marks, registration targets mid-side, CMYK/spot/black-tint colour bars on top, page information (title, artboard, date UTC) below), bleed?: {useDocument (the document's bleed, document.setup), top, bottom, left, right} (pt; art in the bleed is kept; a PDF/X file with no bleed on a side where the document's bleed has one comes back with a warning). Each page: TrimBox = artboard, BleedBox = artboard + bleed, MediaBox = that + the marks' room (art clipped to the BleedBox), output?: {conversion: none (default)|destination (every colour into the destination profile's model, CMYK or RGB, also colours of that model in another profile)|preserveNumbers (only colours of the other model and Lab; those in the destination's model keep their numbers) (grey stays grey; images are converted too, and with destination and an sRGB destination a gray or RGB image tagged with an ICC profile is converted from it and written untagged; with destination and a CMYK destination, or another RGB one images are converted to (not when colours are ICC-tagged), an RGB image tagged with one is converted from it through sRGB; with preserveNumbers (and pdfX1a) only untagged images keep their numbers: an RGB image tagged with one is converted from it to sRGB or through sRGB to the destination, and a gray one is converted from it in an sRGB destination; any other image whose colors are converted (a CMYK image, an RGB one going to a CMYK destination, or with destination to an RGB one other than sRGB) but whose pixels can't be decoded or written that way is left out with a warning; printer's marks are not), destination: profile name (edit.colorSettings lists them; default: the document's profile for its colour mode), profiles: none (device colours; images are written without the ICC profiles they carry, a JPEG without its ICC_PROFILE segments, but in PDF/A, pdfX3 and pdfX4)|all|destination|taggedSource (documents assigned a profile: edit.assignProfile)|default (not set, the default; \"default\" unsets a preset's value, null keeps it: device colours, and gray and RGB images keep the profiles they carry, but in pdfX1a) (ICC-based colours: CMYK with the destination or document CMYK profile, RGB as sRGB, grey with the sRGB tone curve; PDF/A, pdfX3 and pdfX4 always, whatever profiles says, but in pdfX3 and pdfX4 CMYK colors in the profile of a CMYK output intent are DeviceCMYK, and with none and a CMYK output intent pdfX3 and pdfX4 write every CMYK color as DeviceCMYK, unless colors are converted to a CMYK destination of another profile; a CMYK image that keeps its numbers carries the CMYK profile it embeds with all and taggedSource, and in PDF/A, pdfX3 and pdfX4 unless destination, never in pdfX1a, nor when CMYK colors are DeviceCMYK and either its profile is the output intent's or profiles is none), outputIntent: profile name (embedded as the catalog's /GTS_PDFX output intent; a name that isn't a profile is only named, which pdfX1a and pdfX3 allow only with a registry and pdfX4 refuses; pdfX1a needs a CMYK one), outputCondition, outputConditionId (default: outputIntent), registry, trapped (/Trapped /True; /False when an output intent is written)} (PDF/A files keep their own output intent), advanced?: {fontSubsetPercent: 100 (below 100 is accepted with a warning: fonts are always embedded as subsets), outlineText: false (type as real, selectable and searchable text in embedded subset fonts with a ToUnicode map; fonts whose licence forbids embedding, or allows only whole fonts, stay outlines with a warning; true: every glyph as an outline), overprint: preserve (overprinting fills and strokes set /OP /op true, /OPM 1; white ones knock out with document.setup discardWhiteOverprint)|discard (they knock out)}, security?: {openPassword, permissionsPassword, printing: none|low|high, changes: none|pages|forms|comments|any, copy, screenReader, plaintextMetadata}, acknowledgeLoss?: bool (write over the file the document was read from although reading it left things out), format?: \"pdf\"} → {path, bytes, warnings}; no path → {dataBase64, bytes, warnings}. The options apply over the preset (null keeps its value); options accepted but not applied yet come back as warnings; a standard with a PDF version it doesn't allow and a password with a standard are refused, and so is a PDF/X file that would still break its standard (transparency the flattener left, RGB in pdfX1a, a font not embedded) or a PDF 1.3 file with transparency left. document.export {format: pdf} takes the same options. A key PDF doesn't take, and an unknown key inside one of the option objects, are refused. Under automation read roots, a PDF that carries the native document (preserveEditing on, every artboard, useArtboards not false) is refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked)", has_doc, export_pdf ), diff --git a/crates/engine/src/tests/live.rs b/crates/engine/src/tests/live.rs index 2aa182c8b9..dc37c49761 100644 --- a/crates/engine/src/tests/live.rs +++ b/crates/engine/src/tests/live.rs @@ -1629,9 +1629,9 @@ fn cmyk_mesh(create: Value) -> (Session, NodeId) { (s, a) } -/// The fill colours `document.exportPdf {standard: pdfX4}` writes (`… scn` operands, and the -/// corner colours of its gradient meshes, which are patch shadings, as PDF import reads them -/// back), and its warnings. +/// The fill colours `document.exportPdf {standard: pdfX4}` writes (`… scn` and DeviceCMYK +/// `c m y k k` operands, and the corner colours of its gradient meshes, which are patch shadings, +/// as PDF import reads them back), and its warnings. fn pdf_fill_colours(s: &mut Session) -> (Vec<Vec<f32>>, Vec<String>) { let v = s.execute("document.exportPdf", &json!({"standard": "pdfX4", "compression": {"compressText": false}})).unwrap(); let bytes = vectorcraft_format::base64_decode(v["dataBase64"].as_str().unwrap()).unwrap(); @@ -1646,6 +1646,11 @@ fn pdf_fill_colours(s: &mut Session) -> (Vec<Vec<f32>>, Vec<String>) { if !nums.is_empty() { out.push(nums.into_iter().rev().collect()); } + } else if *w == "k" { + let nums: Vec<f32> = words[..i].iter().rev().take(4).map_while(|x| x.parse().ok()).collect(); + if nums.len() == 4 { + out.push(nums.into_iter().rev().collect()); + } } } } diff --git a/crates/engine/tests/it/dimensions.rs b/crates/engine/tests/it/dimensions.rs index 23bbdb0bee..94c54dea4f 100644 --- a/crates/engine/tests/it/dimensions.rs +++ b/crates/engine/tests/it/dimensions.rs @@ -1971,9 +1971,15 @@ fn dimension_colours_follow_the_document_colour_model() { let black = colours(&s, id); assert!(!black.is_empty() && black.iter().all(|c| *c == vectorcraft_color::Color::cmyk(0.0, 0.0, 0.0, 1.0)), "{black:?}"); let pdf = pdf_content(&run(&mut s, "document.exportPdf", json!({"preset":"PDF/X-4:2010"}))); - // PDF/X-4 paints in the output intent's CMYK space: `/c0 CS 0 0 0 1 SCN` strokes, `scn` fills. - let operands = |op: &str| pdf.match_indices(op).map(|(i, _)| pdf[i.saturating_sub(7)..i].to_string()).collect::<Vec<_>>(); - let (strokes, fills) = (operands(" SCN"), operands(" scn")); + // PDF/X-4 writes CMYK in the output intent's profile as DeviceCMYK: `0 0 0 1 K` strokes, `k` fills. + let words: Vec<&str> = pdf.split_whitespace().collect(); + let operands = |op: &str| { + (4..words.len()) + .filter(|&i| words[i] == op && words[i - 4..i].iter().all(|w| w.parse::<f32>().is_ok())) + .map(|i| words[i - 4..i].join(" ")) + .collect::<Vec<_>>() + }; + let (strokes, fills) = (operands("K"), operands("k")); assert!(!strokes.is_empty() && !fills.is_empty(), "{pdf}"); assert!(strokes.iter().chain(&fills).all(|v| v == "0 0 0 1"), "K-only colours: {strokes:?} {fills:?}"); run(&mut s, "dimension.update", json!({"ids":[id],"options":{"lineColor":[255,0,0]}})); diff --git a/crates/pdf/src/export/writer.rs b/crates/pdf/src/export/writer.rs index e11cda9acd..b7c967989e 100644 --- a/crates/pdf/src/export/writer.rs +++ b/crates/pdf/src/export/writer.rs @@ -69,9 +69,11 @@ impl Writer { pub(crate) fn new(doc: &Document, set: &crate::PdfSettings, title: &str, created: Option<i64>, cmyk: bool) -> Result<Self, PdfError> { let out = ColorOut::new(doc, set)?; let mut warnings = out.profile_notes.clone(); - // Tagged CMYK colours need the profile (PDF/A tags every colour). - let cmyk_profile = if out.tagged { out.cmyk_icc() } else { None }; - if out.tagged && cmyk_profile.is_none() { + // Tagged CMYK colours need the profile (PDF/A tags every colour). When CMYK colors are + // DeviceCMYK (`device_cmyk`), the writer gets no CMYK profile. + let tags_cmyk = out.tagged && !out.device_cmyk(); + let cmyk_profile = if tags_cmyk { out.cmyk_icc() } else { None }; + if tags_cmyk && cmyk_profile.is_none() { warnings.push(format!("the CMYK profile {} can't be embedded: CMYK colours are written untagged", out.cmyk_profile())); } let version = match set.compatibility { @@ -271,8 +273,15 @@ impl Writer { PdfError::from(e) })?; if self.cmyk { - let profile = self.out.tagged.then(|| vectorcraft_color::cms::icc_bytes(self.out.cmyk_profile()).ok()).flatten(); - cmyk_blending(&mut bytes, self.out.tagged, profile.as_deref(), self.out.standard != Standard::PdfA2b); + let device = self.out.device_cmyk(); + let profile = (self.out.tagged && !device).then(|| vectorcraft_color::cms::icc_bytes(self.out.cmyk_profile()).ok()).flatten(); + let without = match (&profile, self.out.standard != Standard::PdfA2b) { + _ if device => Without::AlwaysDeviceCmyk, + (None, _) => Without::FirstCmyk, + (Some(_), true) => Without::DeviceCmyk, + (Some(_), false) => Without::Rgb, + }; + cmyk_blending(&mut bytes, self.out.tagged, profile.as_deref(), without); } let lab = !self.lab_spots.is_empty() && !self.out.standard.cmyk_only(); let bytes = if lab { crate::lab_spot::lab_alternates(bytes, &self.lab_spots) } else { bytes }; @@ -287,19 +296,12 @@ impl Writer { /// are rewritten in place to DeviceCMYK (or the CMYK profile's space), keeping their length so the /// cross-reference offsets stay valid. Luminosity masks' groups keep RGB: mask luminance is that /// of screen colours, as on screen. Tagged groups blend in the space of CMYK profile `profile` -/// (the one that tags CMYK colours) when the file has one. When its only CMYK spaces are of other -/// profiles (images' own), they blend in DeviceCMYK where `device` allows it, else they keep RGB; -/// without `profile`, they blend in the first CMYK space. -fn cmyk_blending(pdf: &mut [u8], tagged: bool, profile: Option<&[u8]>, device: bool) { +/// (the one that tags CMYK colours) when the file has one; otherwise they blend as `without` says. +fn cmyk_blending(pdf: &mut [u8], tagged: bool, profile: Option<&[u8]>, without: Without) { let masks = luminosity_mask_groups(pdf); let mut spaces = vec![("/CS/DeviceRGB".to_string(), "/CS/DeviceCMYK".to_string())]; if tagged { let own = profile.and_then(|icc| crate::output::tagging_stream(pdf, &crate::patch::Xref::read(pdf)?, icc)); - let without = match (profile, device) { - (None, _) => Without::FirstCmyk, - (Some(_), true) => Without::DeviceCmyk, - (Some(_), false) => Without::Rgb, - }; spaces.extend(icc_spaces(pdf, own, without)); } let mut from = 0; @@ -316,11 +318,15 @@ fn cmyk_blending(pdf: &mut [u8], tagged: bool, profile: Option<&[u8]>, device: b /// What tagged groups blend in when the file holds no space of the document's CMYK profile. #[derive(Clone, Copy, Debug, PartialEq)] enum Without { - /// The first ICC-based CMYK space of the file. + /// The first ICC-based CMYK space of the file (the document's profile isn't known). FirstCmyk, + /// DeviceCMYK when the file has an ICC-based CMYK space (images' own profiles), outside PDF/A. DeviceCmyk, - /// The RGB space they have. + /// The RGB space they have (PDF/A, which allows no DeviceCMYK next to images' own profiles). Rgb, + /// DeviceCMYK, also when the file has no ICC-based CMYK space: CMYK colors are DeviceCMYK + /// ([`crate::output::ColorOut::device_cmyk`]). + AlwaysDeviceCmyk, } /// The ICC-based RGB colour spaces of `pdf`, each with the ICC-based CMYK one to blend in instead, @@ -352,6 +358,7 @@ fn icc_spaces(pdf: &[u8], own: Option<u32>, without: Without) -> Vec<(String, St Without::FirstCmyk => cmyk, Without::DeviceCmyk => cmyk.map(|_| "/CS/DeviceCMYK".to_string()), Without::Rgb => None, + Without::AlwaysDeviceCmyk => Some("/CS/DeviceCMYK".to_string()), }); let Some(cmyk) = cmyk else { return vec![] }; rgb.into_iter().map(|r| (r, cmyk.clone())).collect() @@ -435,6 +442,11 @@ mod tests { // profile's space; the first CMYK space when the document's profile isn't known. assert_eq!(icc_spaces(SPACES, None, Without::DeviceCmyk), [(rgb.clone(), "/CS/DeviceCMYK".to_string())]); assert_eq!(icc_spaces(SPACES, None, Without::Rgb), []); - assert_eq!(icc_spaces(SPACES, None, Without::FirstCmyk), [(rgb, "/CS 2 0 R".to_string())]); + assert_eq!(icc_spaces(SPACES, None, Without::FirstCmyk), [(rgb.clone(), "/CS 2 0 R".to_string())]); + // CMYK colors written as DeviceCMYK: groups blend there, with or without a CMYK ICC space. + assert_eq!(icc_spaces(SPACES, None, Without::AlwaysDeviceCmyk), [(rgb.clone(), "/CS/DeviceCMYK".to_string())]); + let rgb_only = b"%PDF-1.7\n1 0 obj\n[/ICCBased 4 0 R]\nendobj\n4 0 obj\n<</N 3/Length 0>>stream\n\nendstream\nendobj\n"; + assert_eq!(icc_spaces(rgb_only, None, Without::DeviceCmyk), []); + assert_eq!(icc_spaces(rgb_only, None, Without::AlwaysDeviceCmyk), [(rgb, "/CS/DeviceCMYK".to_string())]); } } diff --git a/crates/pdf/src/output.rs b/crates/pdf/src/output.rs index f5e4bb6e36..83104215c2 100644 --- a/crates/pdf/src/output.rs +++ b/crates/pdf/src/output.rs @@ -25,12 +25,17 @@ //! document's), RGB with sRGB (colours of another RGB space as their sRGB equivalents) and grey //! with the sRGB tone curve. Otherwise they are device colours. PDF/A, PDF/X-3 and PDF/X-4 //! always tag them, whatever `profiles` says; PDF/X-1a never does, and always converts to a -//! CMYK destination (see [`crate::pdfx`]). A CMYK image that keeps its numbers is tagged with -//! the CMYK profile it carries, if any, with `all` and `taggedSource`, and in PDF/A, PDF/X-3 -//! and PDF/X-4 unless `profiles` is `destination` ([`ColorOut::cmyk_image_icc`]). When +//! CMYK destination (see [`crate::pdfx`]). In PDF/X-3 and PDF/X-4, CMYK colors in the profile +//! of a CMYK output intent are DeviceCMYK, and so are all CMYK colors with `none`, unless +//! colors are converted to a CMYK destination of another profile ([`ColorOut::device_cmyk`]). +//! A CMYK image that keeps +//! its numbers is tagged with the CMYK profile it carries, if any, with `all` and +//! `taggedSource`, and in PDF/A, PDF/X-3 and PDF/X-4 unless `profiles` is `destination` +//! ([`ColorOut::cmyk_image_icc`]); not when that profile is a DeviceCMYK output intent's. When //! `profiles` isn't set, colors are written as with `none` and gray and RGB images keep the //! profiles they carry (but in PDF/X-1a); when it is set to `none`, no image keeps its own -//! profile, a JPEG's `ICC_PROFILE` segments included, except in PDF/A, PDF/X-3 and PDF/X-4 +//! profile, a JPEG's `ICC_PROFILE` segments included, except in PDF/A, PDF/X-3 and PDF/X-4, +//! where CMYK images lose theirs only when CMYK colors are DeviceCMYK //! ([`ColorOut::source_profiles`]). //! - Output intent: the profile `outputIntent` names, embedded as the `/GTS_PDFX` output intent //! of the catalog with the condition, identifier and registry; Trapped goes in the document @@ -82,6 +87,13 @@ pub(crate) struct ColorOut { no_profiles: bool, /// The CMYK profile that tags CMYK colours. cmyk_profile: String, + /// CMYK colors are written as DeviceCMYK although colors are tagged + /// ([`Self::device_cmyk`]): the profile of the CMYK output intent they are in, embedded once + /// as its `DestOutputProfile`. + device_icc: Option<Arc<[u8]>>, + /// With [`Self::device_icc`], CMYK images are untagged too, whatever profile they carry + /// (`profiles` is `none`). + untag_cmyk_images: bool, /// Tagged RGB colours are written as their sRGB equivalents: why (a warning), when their RGB /// space isn't sRGB. pub srgb_note: Option<String>, @@ -132,6 +144,8 @@ impl Default for ColorOut { image_icc: false, no_profiles: false, cmyk_profile, + device_icc: None, + untag_cmyk_images: false, srgb_note: None, pixels: OnceLock::new(), tagged_pixels: OnceLock::new(), @@ -290,9 +304,32 @@ impl ColorOut { } out.catalog = catalog(set, &out.cmyk_profile); out.standard = set.standard; + // In PDF/X-3 and PDF/X-4 the CMYK output intent characterizes DeviceCMYK: CMYK colors in + // its profile are written as DeviceCMYK, and with `none` every CMYK color is, unless + // colors are converted to a CMYK destination of another profile. Files without a standard + // keep the tags that `profiles` asks for. + let intent_cmyk = out.catalog.as_ref().and_then(|c| c.intent.as_ref()?.profile.as_ref()).filter(|(_, n)| *n == 4); + let none = set.output.profiles == Some(ProfileInclusion::None); + let to_cmyk = out.dest.as_ref().is_some_and(|d| d.model == Model::Cmyk); + if out.tagged + && set.standard.is_pdfx() + && let Some(intent) = intent_cmyk.and_then(|(name, _)| cms::icc_bytes(name).ok()) + && ((none && !to_cmyk) || cms::icc_bytes(&out.cmyk_profile).is_ok_and(|own| own == intent)) + { + out.device_icc = Some(intent); + out.untag_cmyk_images = none; + } Ok(out) } + /// CMYK colors are written as DeviceCMYK although colors are tagged, in PDF/X-3 and PDF/X-4 + /// with a CMYK output intent: its profile is the one they are in, or `profiles` is `none` and + /// there is no CMYK destination of another profile. RGB and gray colors stay tagged, and + /// so does a CMYK image that carries another profile, except with `none`. + pub(crate) fn device_cmyk(&self) -> bool { + self.device_icc.is_some() + } + /// Transparency blends in CMYK: converting to CMYK, or (without conversion) in a CMYK /// document (`cmyk`). pub(crate) fn blends_cmyk(&self, cmyk: bool) -> bool { @@ -415,22 +452,29 @@ impl ColorOut { /// The CMYK profile CMYK image `blob` is tagged with ([`crate::images::cmyk_icc`]): the one it /// carries, when its numbers are kept and the Profiles setting or the standard includes source - /// profiles. `None` otherwise, and in PDF/X-1a, whose images are untagged CMYK. + /// profiles. `None` otherwise, and in PDF/X-1a, whose images are untagged CMYK. When CMYK + /// colors are DeviceCMYK ([`Self::device_cmyk`]), an image that carries the output intent's + /// profile is untagged too, and so is every CMYK image with `none`. pub(crate) fn cmyk_image_icc(&self, blob: &vectorcraft_doc::ImageBlob) -> Option<Vec<u8>> { if !self.image_icc || self.cmyk_pixels().is_some() { return None; } - crate::images::cmyk_icc(blob) + let icc = crate::images::cmyk_icc(blob)?; + match &self.device_icc { + Some(intent) if self.untag_cmyk_images || icc == **intent => None, + _ => Some(icc), + } } /// How CMYK image `blob` is tagged ([`crate::images::recode_cmyk`]): with the profile /// [`Self::cmyk_image_icc`] gives (`icc`), else untagged, without a JPEG's own `ICC_PROFILE` - /// segments when Don't Include Profiles was set. + /// segments when Don't Include Profiles was set or CMYK colors are DeviceCMYK + /// ([`Self::device_cmyk`]). pub(crate) fn cmyk_tag<'a>(&self, icc: Option<&'a [u8]>) -> crate::images::CmykTag<'a> { use crate::images::CmykTag; match icc { Some(icc) => CmykTag::Profile(icc), - None if self.no_profiles => CmykTag::Removed, + None if self.no_profiles || self.device_cmyk() => CmykTag::Removed, None => CmykTag::Untagged, } } diff --git a/crates/pdf/src/pdfx.rs b/crates/pdf/src/pdfx.rs index 2313d62129..67c71d5dbc 100644 --- a/crates/pdf/src/pdfx.rs +++ b/crates/pdf/src/pdfx.rs @@ -4,9 +4,11 @@ //! - PDF/X-1a:2001: every colour is CMYK, grey or a spot ink with a CMYK alternate (colours and //! images are converted to a CMYK destination and written untagged, see [`crate::output`]), no //! transparency (the app flattens it before writing), no layers, PDF 1.3. -//! - PDF/X-3:2002: colours are ICC-based (always tagged), no transparency, no layers, PDF 1.3. -//! - PDF/X-4:2010: transparency and layers are kept, colours are tagged, PDF 1.6 at most, and the -//! XMP metadata names the standard too and carries `xmp:MetadataDate`. +//! - PDF/X-3:2002: colors are ICC-based (always tagged), except CMYK colors in the CMYK output +//! intent's profile, which are DeviceCMYK (with `profiles` `none`, all CMYK colors unless they +//! are converted to a CMYK destination of another profile), no transparency, no layers, PDF 1.3. +//! - PDF/X-4:2010: transparency and layers are kept, colors are tagged as in PDF/X-3, PDF 1.6 at +//! most, and the XMP metadata names the standard too and carries `xmp:MetadataDate`. //! - All of them: a `/GTS_PDFX` output intent (blank, the CMYK profile in effect, embedded), a //! TrimBox on every page (the artboard), `/Trapped` True or False, `/GTS_PDFXVersion` in the //! document information, a title and dates, embedded fonts (or text as outlines), no editing diff --git a/crates/pdf/src/tests/cmykimages.rs b/crates/pdf/src/tests/cmykimages.rs index 4d22a10ee6..af3b5f313c 100644 --- a/crates/pdf/src/tests/cmykimages.rs +++ b/crates/pdf/src/tests/cmykimages.rs @@ -164,8 +164,9 @@ fn a_cmyk_jpeg_passes_through_open_and_every_pdf_export() { (json!({}), "DeviceCMYK", None), (json!({"output": {"conversion": "preserveNumbers"}}), "DeviceCMYK", None), (json!({"standard": "pdfX1a"}), "DeviceCMYK", None), - (json!({"standard": "pdfX3"}), "ICCBased", Some(4)), - (json!({"standard": "pdfX4"}), "ICCBased", Some(4)), + // CMYK in the output intent's profile (the CMYK profile in effect) is DeviceCMYK. + (json!({"standard": "pdfX3"}), "DeviceCMYK", None), + (json!({"standard": "pdfX4"}), "DeviceCMYK", None), (json!({"output": {"profiles": "all"}}), "ICCBased", Some(4)), ] { let out = export_with_report(&r.document, &opts(settings.clone())).unwrap(); @@ -645,6 +646,37 @@ fn a_cmyk_image_that_keeps_its_numbers_carries_its_cmyk_profile() { assert!(!String::from_utf8_lossy(&bytes).contains("/S/Luminosity"), "no luminosity soft mask"); } +/// When CMYK colors are DeviceCMYK in the output intent's profile, a CMYK image that carries that +/// profile is DeviceCMYK too, and with `none` so is one that carries another profile; elsewhere +/// it keeps its own (#1954). +#[test] +fn a_cmyk_image_in_the_output_intents_profile_is_device_cmyk() { + let ink = [0u8, 102, 255, 0]; + let working = cms::icc_bytes(&cms::active_settings().cmyk).unwrap(); + let other = cmyk_profile(|_| {}); + let export = |icc: &[u8], s: serde_json::Value| { + let tiff = cmyk_tiff_with(ink, 4, 4, icc); + let inks = tiff.cmyk().unwrap().data; + let d = image_doc(tiff, 4, 4); + let out = export_with_report(&d, &opts(s.clone())).unwrap_or_else(|e| panic!("{s}: {e}")); + let w: Vec<Written> = written(&out.bytes).into_iter().filter(|w| w.space != "DeviceGray").collect(); + assert_eq!(w.len(), 1, "{s}: {w:?}"); + assert_eq!(blobs(&import(&out.bytes).unwrap())[0].cmyk().unwrap().data, inks, "{s}: the inks as they were"); + w.into_iter().next().unwrap() + }; + for s in [json!({"standard": "pdfX4"}), json!({"standard": "pdfX3"}), json!({"standard": "pdfX4", "output": {"profiles": "none"}})] { + let w = export(&working, s.clone()); + assert_eq!((w.space.as_str(), w.icc_n), ("DeviceCMYK", None), "{s}: the output intent's profile"); + } + let w = export(&other, json!({"standard": "pdfX4"})); + assert!((w.space.as_str(), w.icc.as_deref()) == ("ICCBased", Some(other.as_slice())), "another profile is kept: {w:?}"); + let w = export(&other, json!({"standard": "pdfX4", "output": {"profiles": "none"}})); + assert_eq!((w.space.as_str(), w.icc_n), ("DeviceCMYK", None), "with none: {w:?}"); + // Without an output intent, the image keeps the profile it carries. + let w = export(&working, json!({"output": {"profiles": "all"}})); + assert!(w.space == "ICCBased" && w.icc.as_deref() == Some(&*working), "{w:?}"); +} + /// With Don't Include Profiles set, a CMYK JPEG kept as it is is DeviceCMYK without its own /// `ICC_PROFILE` segments, its compressed inks unchanged; one resampled and compressed again is /// written without a profile too. Left unset, the JPEG data stays as it is. @@ -672,6 +704,16 @@ fn a_set_dont_include_profiles_takes_a_cmyk_jpegs_profile_out() { let s = json!({"output": {"profiles": "none"}, "compression": {"color": {"downsample": "bicubic", "ppi": 72.0, "abovePpi": 100.0}}}); let (w, _) = export(s.clone()); assert!(w.icc.is_none() && !segment(&w.data), "{s}: {w:?}"); + // A PDF/X file whose CMYK colors are DeviceCMYK takes the profile out of a JPEG it untags. + let s = json!({"standard": "pdfX4", "output": {"profiles": "none"}}); + let (w, _) = export(s.clone()); + assert!(w.space == "DeviceCMYK" && w.data == vectorcraft_doc::cmyk::jpeg_without_icc(&jpg).unwrap(), "{s}: {w:?}"); + let working = cms::icc_bytes(&cms::active_settings().cmyk).unwrap(); + let own = cmyk_jpeg_with(&flat(ink, 64 * 64), 64, 64, &working); + let d = image_doc(ImageBlob::new("image/jpeg", own.clone()), 64, 64); + let out = export_with_report(&d, &opts(json!({"standard": "pdfX4"}))).unwrap(); + let w: Vec<Written> = written(&out.bytes).into_iter().filter(|w| w.space != "DeviceGray").collect(); + assert!(w.len() == 1 && w[0].space == "DeviceCMYK" && w[0].data == vectorcraft_doc::cmyk::jpeg_without_icc(&own).unwrap(), "{w:?}"); } /// A CMYK JPEG kept as it is whose header declares far more pixels than the app reads is left out diff --git a/crates/pdf/src/tests/output.rs b/crates/pdf/src/tests/output.rs index 71461ae1f8..d9c2fedc1d 100644 --- a/crates/pdf/src/tests/output.rs +++ b/crates/pdf/src/tests/output.rs @@ -591,39 +591,96 @@ fn standard_pdf(d: &Document, settings: Value) -> ExportReport { export_with_report(d, &PdfOptions { settings, created: Some(1_700_000_000), ..Default::default() }).unwrap() } +/// The output intent's profile, decoded, of `bytes`. +fn intent_profile(bytes: &[u8]) -> Vec<u8> { + let mut out = vec![]; + output_intent(bytes, None, |oi| out = oi.get::<Stream<'_>>(b"DestOutputProfile").unwrap().decoded().unwrap().into_owned()); + out +} + +/// CMYK colors in the profile of a CMYK output intent are DeviceCMYK, which the output intent +/// describes: no ICC-based CMYK space carries the same profile, and it is embedded once (#1954). #[test] -fn a_profile_that_tags_colours_and_is_the_output_intent_is_embedded_once() { - let d = doc(ColorMode::Cmyk, &[Color::cmyk(0.1, 0.2, 0.3, 0.4)]); +fn cmyk_colors_in_the_output_intents_profile_are_device_cmyk() { + let ink = [0.1, 0.2, 0.3, 0.4]; + let d = doc(ColorMode::Cmyk, &[Color::cmyk(ink[0], ink[1], ink[2], ink[3])]); let working = cms::active_settings().cmyk; let icc = cms::icc_bytes(&working).unwrap(); for set in [ json!({"standard": "pdfX4"}), json!({"standard": "pdfX4", "output": {"outputIntent": working}}), - // PDF/X-3 and PDF/X-4 always tag their colours: `profiles` doesn't apply. json!({"standard": "pdfX4", "output": {"profiles": "none", "outputIntent": working}}), json!({"standard": "pdfX3"}), - json!({"output": {"profiles": "all", "outputIntent": working}}), ] { let r = standard_pdf(&d, set.clone()); - let streams = icc_streams(&r.bytes); - assert_eq!(streams.len(), 1, "{set}: ICC profile streams"); - assert!(streams[0] == *icc, "{set}: the working CMYK profile"); - assert!(colours(&r.bytes).iter().all(|c| c.0 == "scn"), "{set}: tagged colours"); - output_intent(&r.bytes, None, |oi| assert_eq!(oi.get::<Stream<'_>>(b"DestOutputProfile").unwrap().decoded().unwrap().as_ref(), &*icc)); + assert!(r.warnings.is_empty(), "{set}: {:?}", r.warnings); + assert!(icc_streams(&r.bytes) == [icc.to_vec()], "{set}: the working CMYK profile, once"); + assert!(icc_profiles(&r.bytes).is_empty(), "{set}: no ICC-based color space"); + let c = colours(&r.bytes); + assert!(c.len() == 1 && c[0].0 == "k" && close(&c[0].1, &ink), "{set}: DeviceCMYK, the numbers kept: {c:?}"); + assert!(intent_profile(&r.bytes) == *icc, "{set}"); } - // Another output intent profile is its own stream. + // Another output intent's profile: CMYK colors keep their own, and both are embedded. + let other = cms::icc_bytes(DEVICE_CMYK).unwrap(); let r = standard_pdf(&d, json!({"standard": "pdfX4", "output": {"outputIntent": DEVICE_CMYK}})); assert_eq!(icc_streams(&r.bytes).len(), 2); - output_intent(&r.bytes, None, |oi| { - assert_eq!(oi.get::<Stream<'_>>(b"DestOutputProfile").unwrap().decoded().unwrap().as_ref(), &*cms::icc_bytes(DEVICE_CMYK).unwrap()) - }); + assert!(icc_profiles(&r.bytes) == [(4, icc.to_vec())]); + assert!(colours(&r.bytes).iter().all(|c| c.0 == "scn"), "{:?}", colours(&r.bytes)); + assert!(intent_profile(&r.bytes) == *other); + // With `none`, every CMYK color is DeviceCMYK, in the output intent's profile. + for standard in ["pdfX3", "pdfX4"] { + let set = json!({"standard": standard, "output": {"profiles": "none", "outputIntent": DEVICE_CMYK}}); + let r = standard_pdf(&d, set.clone()); + assert!(icc_streams(&r.bytes) == [other.to_vec()], "{set}"); + let c = colours(&r.bytes); + assert!(c.len() == 1 && c[0].0 == "k" && close(&c[0].1, &ink), "{set}: {c:?}"); + } + // With `none`, colors converted to a CMYK destination of another profile keep its tag: they + // are in the destination's profile, not the output intent's. + let set = json!({"standard": "pdfX4", "output": {"profiles": "none", "conversion": "destination", "destination": DEVICE_CMYK, "outputIntent": working}}); + let r = standard_pdf(&d, set.clone()); + assert!(icc_profiles(&r.bytes) == [(4, other.to_vec())], "{set}"); + assert!(colours(&r.bytes).iter().all(|c| c.0 == "scn"), "{set}: {:?}", colours(&r.bytes)); + assert!(intent_profile(&r.bytes) == *icc, "{set}"); + // Without a standard, `all` tags CMYK colors, with an output intent of their profile or none. + for set in [json!({"output": {"profiles": "all"}}), json!({"output": {"profiles": "all", "outputIntent": working}})] { + let r = standard_pdf(&d, set.clone()); + assert!(icc_profiles(&r.bytes) == [(4, icc.to_vec())], "{set}"); + assert!(colours(&r.bytes).iter().all(|c| c.0 == "scn"), "{set}: {:?}", colours(&r.bytes)); + } +} + +/// Next to DeviceCMYK colors, RGB colors stay ICC-based (a CMYK output intent leaves no room for +/// DeviceRGB), and transparency groups of a CMYK document blend in DeviceCMYK. +#[test] +fn rgb_stays_tagged_and_groups_blend_in_device_cmyk_beside_device_cmyk_colors() { + let d = doc(ColorMode::Rgb, &[Color::rgb(0.2, 0.4, 0.6), Color::cmyk(0.1, 0.2, 0.3, 0.4)]); + for set in [json!({"standard": "pdfX4"}), json!({"standard": "pdfX4", "output": {"profiles": "none"}})] { + let r = standard_pdf(&d, set.clone()); + let ops: Vec<String> = colours(&r.bytes).into_iter().map(|c| c.0).collect(); + assert_eq!(ops, ["scn", "k"], "{set}"); + let n: Vec<i32> = icc_profiles(&r.bytes).iter().map(|p| p.0).collect(); + assert_eq!(n, [3], "{set}: sRGB only"); + } + let mut d = doc(ColorMode::Cmyk, &[Color::cmyk(1.0, 0.0, 0.0, 0.0)]); + let mut n = Node::path( + d.alloc_id(), + shapes::rectangle(Rect::new(20.0, 20.0, 60.0, 60.0)), + Appearance::basic(Paint::solid(Color::cmyk(0.0, 1.0, 0.0, 0.0)), Paint::None, 0.0), + ); + n.opacity = 0.5; + let l = d.layers[0].id; + d.insert(Some(l), 1, n).unwrap(); + let r = standard_pdf(&d, json!({"standard": "pdfX4"})); + let text = String::from_utf8_lossy(&r.bytes); + let groups: Vec<&str> = text.split("/Group<<").skip(1).map(|g| g.split(">>").next().unwrap()).collect(); + assert!(!groups.is_empty() && groups.iter().all(|g| g.contains("/CS/DeviceCMYK")), "{groups:?}"); } /// The profiles assigned to a document (Edit › Assign Profile) are its colour spaces whatever the /// working spaces of the session that exports it: a document opened again in a new session, -/// which starts with the default working spaces, keeps its profiles. Its CMYK colours are tagged -/// with its CMYK profile, which is also the PDF/X output intent, and its RGB colours separate -/// through it. +/// which starts with the default working spaces, keeps its profiles. Its CMYK profile is the PDF/X +/// output intent, whose DeviceCMYK colors are in it, and its RGB colours separate through it. #[test] fn colours_are_in_the_profiles_assigned_to_the_document() { let working = cms::active_settings().cmyk; @@ -635,13 +692,13 @@ fn colours_are_in_the_profiles_assigned_to_the_document() { let r = standard_pdf(&d, json!({"standard": "pdfX4"})); assert!(!r.warnings.iter().any(|w| w.contains("profile")), "{:?}", r.warnings); let own = cms::icc_bytes(DEVICE_CMYK).unwrap(); - assert!(icc_streams(&r.bytes) == [own.to_vec()], "tagged with the document's CMYK profile, not the working one"); + assert!(icc_streams(&r.bytes) == [own.to_vec()], "the document's CMYK profile, not the working one"); output_intent(&r.bytes, None, |oi| assert_eq!(oi.get::<Stream<'_>>(b"DestOutputProfile").unwrap().decoded().unwrap().as_ref(), &*own)); let c = colours(&r.bytes); - assert!(c[0].0 == "scn" && close(&c[0].1, &[0.1, 0.2, 0.3, 0.4]), "CMYK keeps its numbers: {c:?}"); + assert!(c[0].0 == "k" && close(&c[0].1, &[0.1, 0.2, 0.3, 0.4]), "CMYK keeps its numbers: {c:?}"); let separated = to_cmyk(DEVICE_CMYK).to_cmyk(&grey, intent); assert!(!close(&separated, &cms::active().to_cmyk(&grey, intent)), "the two profiles separate grey differently"); - assert!(c[1].0 == "scn" && close(&c[1].1, &separated), "RGB separated through the document's profile: {c:?} vs {separated:?}"); + assert!(c[1].0 == "k" && close(&c[1].1, &separated), "RGB separated through the document's profile: {c:?} vs {separated:?}"); // A profile that isn't available leaves the working space, with a warning. d.color_profiles.cmyk = Some("No Such Press".into()); let r = standard_pdf(&d, json!({"standard": "pdfX4"})); diff --git a/crates/ui-egui/src/dialogs/save_pdf.rs b/crates/ui-egui/src/dialogs/save_pdf.rs index 9a4cbfa364..e07980196d 100644 --- a/crates/ui-egui/src/dialogs/save_pdf.rs +++ b/crates/ui-egui/src/dialogs/save_pdf.rs @@ -711,6 +711,13 @@ fn output(ui: &mut egui::Ui, d: &mut Dialog) { }); if standard.cmyk_only() { note(ui, tl!("PDF/X-1a files are CMYK: every colour is converted to the destination (blank: the output intent's CMYK profile), untagged.")); + } else if standard.is_pdfx() { + note( + ui, + tl!( + "Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK." + ), + ); } else if standard != Standard::None { note(ui, tl!("Files of this standard tag their colours with ICC profiles.")); } diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index bb039bb08e..86ea88e6c4 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -1208,6 +1208,7 @@ font-technology Variable Променливи Files Файлове Files of a PDF standard can't be password-protected. Файлове от PDF стандарт не могат да бъдат защитени с парола. Files of this standard tag their colours with ICC profiles. Файловете от този стандарт етикетират цветовете си с ICC профили. + Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. Файловете от този стандарт етикетират цветовете си с ICC профили, с изключение на CMYK цветовете в профила на предназначението на изхода, които се записват като DeviceCMYK. Fill Запълване Fill & Stroke Запълване и щрих Fill (X), double-click for the Color Picker Запълване (X), щракнете двукратно за избор на цвят diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 99f23d313c..d93d523c4a 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -3087,6 +3087,7 @@ antiAlias Sharp Oštro Every option matches {base}. Sve opcije odgovaraju {base}. Files of a PDF standard can't be password-protected. Datoteke PDF standarda ne mogu se zaštititi lozinkom. Files of this standard tag their colours with ICC profiles. Datoteke ovog standarda označavaju svoje boje ICC profilima. + Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. Datoteke ovog standarda označavaju svoje boje ICC profilima, osim CMYK boja u profilu izlazne namjene, koje se zapisuju kao DeviceCMYK. Flattener preset: Predložak spljoštavanja: General › Thumbnails Općenito › Sličice Grayscale images Slike u nijansama sive diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index c54311799d..41b03b7fe0 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -1706,6 +1706,7 @@ digits Malayalam Malaiàlam Files Fitxers Files of a PDF standard can't be password-protected. Els fitxers d’un estàndard PDF no es poden protegir amb contrasenya. Files of this standard tag their colours with ICC profiles. Els fitxers d’aquest estàndard etiqueten els colors amb perfils ICC. + Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. Els fitxers d’aquest estàndard etiqueten els colors amb perfils ICC, excepte els colors CMYK del perfil d’intenció de sortida, que s’escriuen com a DeviceCMYK. Fill Farciment Fill & Stroke Farciment i traç Fill (X), double-click for the Color Picker Farciment (X), fes doble clic per al selector de color diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index a5d7bb948a..77f7ea934a 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -3171,6 +3171,7 @@ antiAlias Sharp Ostré Every option matches {base}. Všechny možnosti odpovídají: {base}. Files of a PDF standard can't be password-protected. Soubory podle standardu PDF nelze chránit heslem. Files of this standard tag their colours with ICC profiles. Soubory tohoto standardu označují své barvy profily ICC. + Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. Soubory tohoto standardu označují své barvy profily ICC, kromě barev CMYK v profilu výstupního záměru, které se zapisují jako DeviceCMYK. Flattener preset: Přednastavení sloučení: General › Thumbnails Obecné › Miniatury Grayscale images Obrazy ve stupních šedi diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 08100f593f..8f71585fd3 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -5644,6 +5644,7 @@ antiAlias Sharp Skarp Every option matches {base}. Alle indstillinger matcher {base}. Files of a PDF standard can't be password-protected. Filer med en PDF-standard kan ikke beskyttes med adgangskode. Files of this standard tag their colours with ICC profiles. Filer med denne standard mærker deres farver med ICC-profiler. + Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. Filer med denne standard mærker deres farver med ICC-profiler, undtagen CMYK-farver i outputintentens profil, som skrives som DeviceCMYK. Flattener preset: Forudindstilling til fladgøring: General › Thumbnails Generelt › Miniaturer Grayscale images Gråtonebilleder diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 10147b2d45..3c198e8dce 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -1231,6 +1231,7 @@ font-technology Variable Variabel Files Dateien Files of a PDF standard can't be password-protected. Dateien eines PDF-Standards können nicht mit einem Kennwort geschützt werden. Files of this standard tag their colours with ICC profiles. Dateien dieses Standards kennzeichnen ihre Farben mit ICC-Profilen. + Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. Dateien dieses Standards kennzeichnen ihre Farben mit ICC-Profilen, außer CMYK-Farben im Profil der Ausgabemethode, die als DeviceCMYK geschrieben werden. Fill Fläche Fill & Stroke Fläche und Kontur Fill (X), double-click for the Color Picker Fläche (X), Doppelklick öffnet den Farbwähler diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 1ebf6e5684..4741b40dd5 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -1193,6 +1193,7 @@ font-technology Variable Μεταβλητές Files Αρχεία Files of a PDF standard can't be password-protected. Τα αρχεία αυτού του προτύπου PDF δεν μπορούν να προστατεύονται με κωδικό. Files of this standard tag their colours with ICC profiles. Τα αρχεία αυτού του προτύπου χαρακτηρίζουν τα χρώματά τους με προφίλ ICC. + Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. Τα αρχεία αυτού του προτύπου χαρακτηρίζουν τα χρώματά τους με προφίλ ICC, εκτός από τα χρώματα CMYK στο προφίλ προορισμού εξόδου, τα οποία γράφονται ως DeviceCMYK. Fill Γέμισμα Fill & Stroke Γέμισμα και περίγραμμα Fill (X), double-click for the Color Picker Γέμισμα (X), διπλό κλικ για τον επιλογέα χρώματος diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index a456910a16..6530cb8c73 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -1256,6 +1256,7 @@ font-technology Variable Variables Files Archivos Files of a PDF standard can't be password-protected. Los archivos de un estándar PDF no se pueden proteger con contraseña. Files of this standard tag their colours with ICC profiles. Los archivos de este estándar etiquetan sus colores con perfiles ICC. + Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. Los archivos de este estándar etiquetan sus colores con perfiles ICC, excepto los colores CMYK en el perfil de propósito de salida, que se escriben como DeviceCMYK. Fill Relleno Fill & Stroke Relleno y trazo Fill (X), double-click for the Color Picker Relleno (X), doble clic para el selector de color diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index bff46fc0d7..dadad98564 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -3115,6 +3115,7 @@ antiAlias Sharp Terävä Every option matches {base}. Kaikki asetukset vastaavat kohdetta {base}. Files of a PDF standard can't be password-protected. PDF-standardin mukaisia tiedostoja ei voi suojata salasanalla. Files of this standard tag their colours with ICC profiles. Tämän standardin tiedostot merkitsevät värinsä ICC-profiileilla. + Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. Tämän standardin tiedostot merkitsevät värinsä ICC-profiileilla, paitsi tulostustavoitteen profiilin CMYK-värit, jotka kirjoitetaan DeviceCMYK-muodossa. Flattener preset: Litistyksen esiasetus: General › Thumbnails Yleiset › Pikkukuvat Grayscale images Harmaasävykuvat diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 3be3497f97..4559058a49 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -1247,6 +1247,7 @@ font-technology Variable Variables Files Fichiers Files of a PDF standard can't be password-protected. Les fichiers conformes à une norme PDF ne peuvent pas être protégés par mot de passe. Files of this standard tag their colours with ICC profiles. Les fichiers conformes à cette norme balisent leurs couleurs avec des profils ICC. + Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. Les fichiers conformes à cette norme balisent leurs couleurs avec des profils ICC, sauf les couleurs CMJN du profil du mode de sortie, qui sont écrites en DeviceCMYK. Fill Fond Fill & Stroke Fond et contour Fill (X), double-click for the Color Picker Fond (X), double-cliquez pour ouvrir le Sélecteur de couleurs diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index c427fc527c..e0b3e97b9f 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -1378,6 +1378,7 @@ Files ફાઇલો Files of a PDF standard can't be password-protected. PDF સ્ટાન્ડર્ડની ફાઇલો પાસવર્ડ-સુરક્ષિત કરી શકાતી નથી. Files of this standard tag their colours with ICC profiles. આ સ્ટાન્ડર્ડની ફાઇલો તેમના રંગોને ICC પ્રોફાઇલ્સ સાથે ટૅગ કરે છે. + Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. આ સ્ટાન્ડર્ડની ફાઇલો તેમના રંગોને ICC પ્રોફાઇલ્સ સાથે ટૅગ કરે છે, આઉટપુટ ઇન્ટેન્ટ પ્રોફાઇલમાંના CMYK રંગો સિવાય, જે DeviceCMYK તરીકે લખાય છે. Fill ભરો Fill & Stroke ભરો અને સ્ટ્રોક Fill (X), double-click for the Color Picker ભરો (X), કલર પીકર માટે ડબલ-ક્લિક કરો diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index cbfb4f51d1..d8a6d9a124 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -1898,6 +1898,7 @@ antiAlias Sharp शार्प Files फ़ाइलें Files of a PDF standard can't be password-protected. एक PDF मानक की फ़ाइलें पासवर्ड की रक्षा नहीं की जा सकती है। Files of this standard tag their colours with ICC profiles. इस मानक की फ़ाइलें ICC प्रोफ़ाइल के साथ उनके रंगों को टैग करती हैं। + Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. इस मानक की फ़ाइलें ICC प्रोफ़ाइल के साथ उनके रंगों को टैग करती हैं, आउटपुट इंटेंट प्रोफ़ाइल के CMYK रंगों को छोड़कर, जो DeviceCMYK के रूप में लिखे जाते हैं। Fill फ़िल Fill (X), double-click for the Color Picker फ़िल (X), कलर पिकर के लिए डबल-क्लिक करें Fill & Stroke भरें और स्ट्रोक करें diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 0f81a72036..1e9e020a8c 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -1565,6 +1565,7 @@ digits Malayalam Malajálam Files Fájlok Files of a PDF standard can't be password-protected. A PDF-szabványnak megfelelő fájlok nem védhetők jelszóval. Files of this standard tag their colours with ICC profiles. Ennek a szabványnak a fájljai ICC-profillal jelölik a színeiket. + Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. Ennek a szabványnak a fájljai ICC-profillal jelölik a színeiket, kivéve a kimeneti cél profiljában lévő CMYK-színeket, amelyek DeviceCMYK-ként íródnak. Fill Kitöltés Fill & Stroke Kitöltés és körvonal Fill (X), double-click for the Color Picker Kitöltés (X), dupla kattintás: Színválasztó diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 28ea2b5ab3..4bf67e692b 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -2896,6 +2896,7 @@ antiAlias Sharp Tajam Every option matches {base}. Setiap opsi cocok dengan {base}. Files of a PDF standard can't be password-protected. File standar PDF tidak dapat dilindungi kata sandi. Files of this standard tag their colours with ICC profiles. File standar ini menandai warnanya dengan profil ICC. + Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. File standar ini menandai warnanya dengan profil ICC, kecuali warna CMYK dalam profil output intent, yang ditulis sebagai DeviceCMYK. Flattener preset: Preset flattener: General › Thumbnails Umum › Miniatur Grayscale images Gambar skala abu-abu diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 8f2ed3216c..989eaa9b87 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -1265,6 +1265,7 @@ font-technology Variable Variabili Files File Files of a PDF standard can't be password-protected. I file conformi a uno standard PDF non possono essere protetti da password. Files of this standard tag their colours with ICC profiles. I file conformi a questo standard contrassegnano i colori con profili ICC. + Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. I file conformi a questo standard contrassegnano i colori con profili ICC, tranne i colori CMYK nel profilo dell'intento di output, che vengono scritti come DeviceCMYK. Fill Riempimento Fill & Stroke Riempimento e traccia Fill (X), double-click for the Color Picker Riempimento (X), fai doppio clic per il selettore colore diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index c429f204a1..04cfbc90b2 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -1829,6 +1829,7 @@ antiAlias Sharp シャープ Files ファイル Files of a PDF standard can't be password-protected. PDF 規格のファイルにはパスワードを設定できません。 Files of this standard tag their colours with ICC profiles. この規格のファイルでは、カラーに ICC プロファイルが付けられます。 + Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. この規格のファイルでは、カラーに ICC プロファイルが付けられます。ただし、出力インテントのプロファイルの CMYK カラーは DeviceCMYK として書き出されます。 Fill 塗り Fill New Type Objects With Placeholder Text 新規テキストオブジェクトをダミーテキストで埋める Start Lists From Typed Markers 入力した記号からリストを開始 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 414f45171c..b00a69a5df 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -5040,6 +5040,7 @@ antiAlias Sharp მკვეთრი Every option matches {base}. ყველა პარამეტრი ემთხვევა {base}-ს. Files of a PDF standard can't be password-protected. PDF სტანდარტის ფაილების პაროლით დაცვა შეუძლებელია. Files of this standard tag their colours with ICC profiles. ამ სტანდარტის ფაილები ფერებს ICC პროფილებით აღნიშნავს. + Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. ამ სტანდარტის ფაილები ფერებს ICC პროფილებით აღნიშნავს, გარდა გამოტანის მიზნის პროფილის CMYK ფერებისა, რომლებიც DeviceCMYK-ად იწერება. Flattener preset: გაბრტყელების პრესეტი: General › Thumbnails ზოგადი › ესკიზები Grayscale images ნაცრისფერი გამოსახულებები diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index dbda53243f..1db7ed4951 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -1819,6 +1819,7 @@ antiAlias Sharp 날카롭게 Files 파일 Files of a PDF standard can't be password-protected. PDF 표준 파일은 암호로 보호할 수 없습니다. Files of this standard tag their colours with ICC profiles. 이 표준의 파일은 ICC 프로파일로 색상을 태그합니다. + Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. 이 표준의 파일은 ICC 프로파일로 색상을 태그합니다. 단, 출력 의도 프로파일의 CMYK 색상은 DeviceCMYK로 기록됩니다. Fill 칠 Fill New Type Objects With Placeholder Text 새 문자 개체를 대체 텍스트로 채우기 Start Lists From Typed Markers 입력한 기호로 목록 시작 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 69aef91cfc..800e46c54a 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -3518,6 +3518,7 @@ antiAlias Sharp Scherp Every option matches {base}. Elke optie komt overeen met {base}. Files of a PDF standard can't be password-protected. Bestanden volgens een PDF-standaard kunnen niet met een wachtwoord worden beveiligd. Files of this standard tag their colours with ICC profiles. Bestanden volgens deze standaard voorzien hun kleuren van ICC-profielen. + Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. Bestanden volgens deze standaard voorzien hun kleuren van ICC-profielen, behalve CMYK-kleuren in het profiel voor uitvoerintentie, die als DeviceCMYK worden geschreven. Flattener preset: Voorinstelling voor afvlakking: General › Thumbnails Algemeen › Miniaturen Grayscale images Grijswaardenafbeeldingen diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 0147515ffe..8a03719e5c 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -3061,6 +3061,7 @@ antiAlias Sharp Ostre Every option matches {base}. Wszystkie opcje są zgodne z {base}. Files of a PDF standard can't be password-protected. Plików standardu PDF nie można chronić hasłem. Files of this standard tag their colours with ICC profiles. Pliki tego standardu oznaczają kolory profilami ICC. + Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. Pliki tego standardu oznaczają kolory profilami ICC, z wyjątkiem kolorów CMYK w profilu docelowych warunków wyjściowych, które są zapisywane jako DeviceCMYK. Flattener preset: Ustawienie spłaszczania: General › Thumbnails Ogólne › Miniatury Grayscale images Obrazy w skali szarości diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 8201db7ab6..cc88a2bae4 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -1141,6 +1141,7 @@ antiAlias Sharp Nítido Files Arquivos Files of a PDF standard can't be password-protected. Arquivos de um padrão PDF não podem ser protegidos por senha. Files of this standard tag their colours with ICC profiles. Os arquivos deste padrão etiquetam suas cores com perfis ICC. + Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. Os arquivos deste padrão etiquetam suas cores com perfis ICC, exceto as cores CMYK no perfil de intenção de saída, que são gravadas como DeviceCMYK. Fill Preenchimento Fill & Stroke Preenchimento e Traçado Fill Color Cor de Preenchimento diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index d1593508d3..aa78f6335c 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -1254,6 +1254,7 @@ font-technology Variable Вариативные Files Файлы Files of a PDF standard can't be password-protected. Файлы стандарта PDF не могут быть защищены паролем. Files of this standard tag their colours with ICC profiles. Файлы этого стандарта помечают свои цвета профилями ICC. + Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. Файлы этого стандарта помечают свои цвета профилями ICC, кроме цветов CMYK в профиле назначения вывода, которые записываются как DeviceCMYK. Fill Заливка Fill & Stroke Заливка и обводка Fill (X), double-click for the Color Picker Заливка (X), дважды щёлкните для палитры цветов diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 5c0420fcd3..8600a0b479 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -1226,6 +1226,7 @@ font-technology Variable Variabla Files Filer Files of a PDF standard can't be password-protected. Filer enligt en PDF-standard kan inte lösenordsskyddas. Files of this standard tag their colours with ICC profiles. Filer enligt den här standarden märker sina färger med ICC-profiler. + Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. Filer enligt den här standarden märker sina färger med ICC-profiler, utom CMYK-färger i profilen för utgångsavsikt, som skrivs som DeviceCMYK. Fill Fyllning Fill & Stroke Fyllning och kontur Fill (X), double-click for the Color Picker Fyllning (X), dubbelklicka för färgväljaren diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 910a7fc5b1..154683b0d1 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -1217,6 +1217,7 @@ font-technology Variable Değişken Files Dosyalar Files of a PDF standard can't be password-protected. PDF standardının dosyaları parola korumalı olamaz. Files of this standard tag their colours with ICC profiles. Bu standardın dosyaları renklerini ICC profilleriyle etiketler. + Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. Bu standardın dosyaları renklerini ICC profilleriyle etiketler, ancak çıkış amacı profilindeki CMYK renkleri DeviceCMYK olarak yazılır. Fill Dolgu Fill & Stroke Doldur ve Konturla Fill (X), double-click for the Color Picker Doldur (X), Renk Seçici için çift tıklayın diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index dbd6d2609e..6f1fbfb0cf 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -1259,6 +1259,7 @@ font-technology Variable Варіативні Files Файли Files of a PDF standard can't be password-protected. Файли стандарту PDF не можуть бути захищені паролем. Files of this standard tag their colours with ICC profiles. Файли цього стандарту позначають свої кольори профілями ICC. + Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. Файли цього стандарту позначають свої кольори профілями ICC, крім кольорів CMYK у профілі призначення виведення, які записуються як DeviceCMYK. Fill Заливка Fill & Stroke Заливка та обведення Fill (X), double-click for the Color Picker Заливка (X), двічі клацніть на палітрі кольорів diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 519c5d8f0d..e1811b090b 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -1451,6 +1451,7 @@ digits Malayalam Malayalam Files Tệp Files of a PDF standard can't be password-protected. Tệp theo tiêu chuẩn PDF không thể bảo vệ bằng mật khẩu. Files of this standard tag their colours with ICC profiles. Tệp theo tiêu chuẩn này gắn thẻ màu bằng hồ sơ ICC. + Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. Tệp theo tiêu chuẩn này gắn thẻ màu bằng hồ sơ ICC, trừ các màu CMYK trong hồ sơ mục đích đầu ra, được ghi dưới dạng DeviceCMYK. Fill Tô Fill & Stroke Tô & Nét Fill (X), double-click for the Color Picker Tô (X), bấm đúp để mở Bộ chọn màu diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index c6696a9ec6..4c3814bcea 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -1195,6 +1195,7 @@ antiAlias Sharp 锐利 Files 文件 Files of a PDF standard can't be password-protected. PDF 标准的文件无法设置密码保护。 Files of this standard tag their colours with ICC profiles. 此标准的文件会以 ICC 配置文件标记颜色。 + Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. 此标准的文件会以 ICC 配置文件标记颜色,但输出意图配置文件中的 CMYK 颜色会写为 DeviceCMYK。 Fill 填色 Fill & Stroke 填色和描边 Fill (X), double-click for the Color Picker 填色 (X),双击打开拾色器 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 1480422931..1c5db20e0a 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -1229,6 +1229,7 @@ font-technology Variable 可變 Files 檔案 Files of a PDF standard can't be password-protected. PDF 標準的檔案無法設定密碼保護。 Files of this standard tag their colours with ICC profiles. 此標準的檔案會以 ICC 描述檔標記顏色。 + Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. 此標準的檔案會以 ICC 描述檔標記顏色,但輸出目的描述檔中的 CMYK 顏色會寫為 DeviceCMYK。 Fill 填色 Fill & Stroke 填色與筆畫 Fill (X), double-click for the Color Picker 填色 (X),按兩下開啟檢色器 diff --git a/docs/mcp.md b/docs/mcp.md index 092faabc4c..a3fa36ce1f 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1337,7 +1337,7 @@ the image at, and all paint that one image. A 16-bit PNG that is not resampled, recompressed or converted keeps its 16 bits a sample in PDF 1.5 and later files, and is written at 8 bits in PDF 1.3 and 1.4 files. CMYK images stay CMYK (DeviceCMYK, or ICC-based with the CMYK profile when colours are tagged, as in PDF/X-3 and -PDF/X-4): a CMYK JPEG neither resampled nor recompressed is written unchanged, and the others' ink amounts are +PDF/X-4, where an image in the output intent's profile is DeviceCMYK): a CMYK JPEG neither resampled nor recompressed is written unchanged, and the others' ink amounts are resampled and compressed again (CMYK JPEG or ZIP). `output.conversion` converts them like CMYK colours: `destination` to another CMYK profile or to RGB, `preserveNumbers` (and PDF/X-1a) keeps their numbers in a CMYK destination. `document.pdfSettings` lists the options that differ from the preset and the warnings without writing a file. @@ -6259,13 +6259,18 @@ The destination is any profile `edit.colorSettings` lists (default: the document for its colour mode). `profiles` (`all`, `destination`, or `taggedSource` for a document assigned profiles with `edit.assignProfile`) writes colours in ICC-based spaces with their profiles embedded: CMYK with the destination's or the document's CMYK profile, RGB as sRGB, grey with the sRGB tone curve (PDF/A, PDF/X-3 and PDF/X-4 files are -always tagged, whatever `profiles` says). A CMYK image that keeps its numbers carries the CMYK profile it embeds -with `all` and `taggedSource`, and in PDF/A, PDF/X-3 and PDF/X-4 unless `profiles` is `destination`; PDF/X-1a +always tagged, whatever `profiles` says). In PDF/X-3 and PDF/X-4 files, CMYK colors whose profile is the profile of a +CMYK output intent are written as DeviceCMYK, and the profile is embedded once, as the output intent's. With `none` and a CMYK output intent, PDF/X-3 and PDF/X-4 files write every CMYK color as DeviceCMYK +(unless colors are converted to a CMYK `destination` of another profile, which then tags them), and RGB and gray +colors stay tagged. A CMYK image that keeps its numbers carries the CMYK profile it embeds +with `all` and `taggedSource`, and in PDF/A, PDF/X-3 and PDF/X-4 unless `profiles` is `destination`, but not when +CMYK colors are DeviceCMYK and either its profile is the output intent's or `profiles` is `none` (a CMYK JPEG +then loses its `ICC_PROFILE` segments); PDF/X-1a images are always untagged CMYK. Left unset (the default; `"default"` unsets it over a preset, while `null` keeps the preset's value), `profiles` writes device colours and gray and RGB images keep the profiles they carry (not in PDF/X-1a). Set to `none`, it also writes every image without the profile it carries, and a JPEG kept as it is without its `ICC_PROFILE` segments, its other segments and compressed samples unchanged; PDF/A, PDF/X-3 and PDF/X-4 files keep -the profiles they tag images with. The Save PDF dialog lists the unset value as Default. `outputIntent` embeds a profile as the file's +the profiles they tag images with, except CMYK images when CMYK colors are DeviceCMYK. The Save PDF dialog lists the unset value as Default. `outputIntent` embeds a profile as the file's `/GTS_PDFX` output intent with `outputCondition`, `outputConditionId` and `registry`, and `trapped` sets `/Trapped` (PDF/A files keep their own output intent). Type is written as selectable, searchable text in embedded subset fonts with a ToUnicode map (fonts whose licence forbids embedding stay outlines, with a warning); `advanced: {outlineText: @@ -9399,9 +9404,10 @@ layers are refused. - **pdfX1a** (PDF/X-1a:2001, written as PDF 1.3): CMYK, grey and spot colours only. Every colour and image is converted to `output.destination` (blank: the output intent's CMYK profile, else the working CMYK profile), untagged; an RGB destination or output intent is refused. Transparency is flattened before writing. -- **pdfX3** (PDF/X-3:2002, written as PDF 1.3): colours are tagged with ICC profiles; transparency is flattened. -- **pdfX4** (PDF/X-4:2010, PDF 1.6 at most): transparency and layers are kept, colours are tagged, and the XMP metadata - names the standard and has an `xmp:MetadataDate` equal to its `xmp:ModifyDate`. +- **pdfX3** (PDF/X-3:2002, written as PDF 1.3): colours are tagged with ICC profiles, except CMYK colors in the CMYK + output intent's profile, which are DeviceCMYK (see `output.profiles`); transparency is flattened. +- **pdfX4** (PDF/X-4:2010, PDF 1.6 at most): transparency and layers are kept, colours are tagged as in pdfX3, and the + XMP metadata names the standard and has an `xmp:MetadataDate` equal to its `xmp:ModifyDate`. Flattening uses `flattenerPreset` (default High Resolution, see PDF 1.3 above) on a copy (the document is untouched; a warning says so), and images with see-through pixels count as transparency. The written file is checked against diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index eb8aae5389..29bb9b70dd 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1914,8 +1914,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Save as Template writes a PDF-compatible `.ait` as well as a `.vctemplate`, which stays the default: the save panel and the web build's Save as Template dialog list both, and New from Template opens the `.ait` as an untitled document with its layers and art (`file.saveAsTemplate {format: "ait"}`, or a path ending in `.ait`). Save as Template always writes a file named with its template type's extension: `file.saveAsTemplate` saves a path ending in another format's extension (`card.png`) as `card.vctemplate` (or `card.ait`), the desktop save panel does the same with a Save As format's extension typed in it (`card.pdf` is saved as `card.vctemplate`), and `file.saveAs` and `document.save` refuse `ait` with an error that names `file.saveAsTemplate`. A `.ait` is PDF-compatible only: `aiVersion: "7"` is an error for it, and the web build's dialog shows no Version row for it. Exports refuse a `.ait` with an error that names `file.saveAsTemplate`, and `vectorcraft-cli convert in.pdf out.ait` and `run --export out.ait` write the template as `file.saveAsTemplate` does. - - SVG/SVGZ in and out with SVG Options, Preserve Editing, symbols, filters, rich text and physical units (SVG type under a transform or `viewBox` scale opens at the size it draws at, the scale moved into its size, leading, baseline shift and strokes, a stretch, skew or rotation kept as its transform: #396; a top-level group with a clip path, such as a clipped Inkscape layer, opens as a layer with a clipping mask, its name kept: #420; hidden objects written hidden on Save and `convert`, and `data-*` attributes kept as the objects' own data: #522; top-level groups open as layers named from `data-name`, else the id, also when one more group (a transform on all the art, a `<switch>`) wraps them, hidden ones hidden, and a file whose art sits loose under a root `<svg>` with an id (or `data-name`), as one-layer exports write it, opens with its one layer named from it; nested groups stay groups, except the sublayers VectorCraft writes, marked `data-vc-layer`, and Inkscape sublayers, which open as sublayers in their layer's colour: #372); PDF and PDF-compatible `.ai` in and out (layers, with hidden ones kept hidden with their art and nested ones as sublayers, on pages of up to 64 million operators, art whose layer can't be told going to a hidden, non-printing layer rather than showing or printing: #419; strokes kept live, a fill and a stroke of one outline as one object; a type object's stroke written as each glyph's outline stroked back on the type, so it stays one editable object; lines wrapped in a frame (each wrapped line ending in a space, one left edge, leading and font) back as one area type object, left aligned or justified with its paragraph spacing, where laying it out breaks the lines where the file does; glyphs set apart by gaps wider than a space (a barcode's digit groups) keeping their places; layers stacked as the pages mark them even when one first paints on a later page, art ending a layer's marked content or a clip closing in a later layer kept in its own layer, and layers with no art kept empty: #508; art reaching past a plain PDF's page clipped to its crop box, as PDF viewers show it, each such object in a clip group of its own (a PDF-compatible `.ai` opens whole: #675); a `.ai` on its trim boxes with the bleed boxes round them as the document's bleed, as Crop To › Trim opens a PDF (#1266); masks, editable text with type set along a curve coming back as type on a path, each artboard's art on its own page only, an `.ai`'s white page under its layers left out rather than coming in as art, spot colours, presets, security, marks and bleed, ICC output intents, raster effects, subset fonts, PDF/X, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3). CMYK images keep their ink amounts from PDF import (and from placed CMYK TIFFs) to PDF export: a CMYK JPEG passes through unchanged, others stay CMYK (DeviceCMYK, or ICC-based CMYK in PDF/X-3/X-4) unless the Output settings convert them; the canvas shows them through the working CMYK profile (#320). Overprint is kept from PDF import (opened, the PDF part of an `.ai`, placed) to PDF export: the graphics state's `/OP` and `/op` become the overprint of fills, strokes and type, so a spot colour over a process colour still overprints; a page whose overprint can't be read for certain knocks out with a note, as does `/OPM 0` being read as nonzero overprint (#1388; hand-written fixtures, `pdf/src/tests/import_overprint.rs`). A masked CMYK image (`/SMask`, `/Mask` or a colour key) keeps its inks too, its alpha coming in as a greyscale opacity mask. - - SVG/SVGZ in and out with SVG Options, Preserve Editing, symbols, filters, rich text and physical units (SVG type under a transform or `viewBox` scale opens at the size it draws at, the scale moved into its size, leading, baseline shift and strokes, a stretch, skew or rotation kept as its transform: #396; a top-level group with a clip path, such as a clipped Inkscape layer, opens as a layer with a clipping mask, its name kept: #420; hidden objects written hidden on Save and `convert`, and `data-*` attributes kept as the objects' own data: #522; top-level groups open as layers named from `data-name`, else the id, also when one more group (a transform on all the art, a `<switch>`) wraps them, hidden ones hidden, and a file whose art sits loose under a root `<svg>` with an id (or `data-name`), as one-layer exports write it, opens with its one layer named from it; nested groups stay groups, except the sublayers VectorCraft writes, marked `data-vc-layer`, and Inkscape sublayers, which open as sublayers in their layer's colour: #372); PDF and PDF-compatible `.ai` in and out (layers, with hidden ones kept hidden with their art and nested ones as sublayers, on pages of up to 64 million operators, art whose layer can't be told going to a hidden, non-printing layer rather than showing or printing: #419; strokes kept live, a fill and a stroke of one outline as one object; a type object's stroke written as each glyph's outline stroked back on the type, so it stays one editable object; lines wrapped in a frame (each wrapped line ending in a space, one left edge, leading and font) back as one area type object, left aligned or justified with its paragraph spacing, where laying it out breaks the lines where the file does; glyphs set apart by gaps wider than a space (a barcode's digit groups) keeping their places; layers stacked as the pages mark them even when one first paints on a later page, art ending a layer's marked content or a clip closing in a later layer kept in its own layer, and layers with no art kept empty: #508; art reaching past a plain PDF's page clipped to its crop box, as PDF viewers show it, each such object in a clip group of its own (a PDF-compatible `.ai` opens whole: #675); a `.ai` on its trim boxes with the bleed boxes round them as the document's bleed, as Crop To › Trim opens a PDF (#1266); masks, editable text with type set along a curve coming back as type on a path, each artboard's art on its own page only, an `.ai`'s white page under its layers left out rather than coming in as art, spot colours, presets, security, marks and bleed, ICC output intents, raster effects, subset fonts, PDF/X, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3). CMYK images keep their ink amounts from PDF import (and from placed CMYK TIFFs and the images in an `.ai` or EPS file's editing data, an alpha channel coming in as a grayscale opacity mask) to PDF export: a CMYK JPEG passes through unchanged, others stay CMYK (DeviceCMYK, or ICC-based CMYK in PDF/X-3/X-4) unless the Output settings convert them; the canvas shows them through the working CMYK profile (#320). Overprint is kept from PDF import (opened, the PDF part of an `.ai`, placed) to PDF export: the graphics state's `/OP` and `/op` become the overprint of fills, strokes and type, so a spot colour over a process colour still overprints; a page whose overprint can't be read for certain knocks out with a note, as does `/OPM 0` being read as nonzero overprint (#1388; hand-written fixtures, `pdf/src/tests/import_overprint.rs`). A masked CMYK image (`/SMask`, `/Mask` or a colour key) keeps its inks too, its alpha coming in as a greyscale opacity mask. + - SVG/SVGZ in and out with SVG Options, Preserve Editing, symbols, filters, rich text and physical units (SVG type under a transform or `viewBox` scale opens at the size it draws at, the scale moved into its size, leading, baseline shift and strokes, a stretch, skew or rotation kept as its transform: #396; a top-level group with a clip path, such as a clipped Inkscape layer, opens as a layer with a clipping mask, its name kept: #420; hidden objects written hidden on Save and `convert`, and `data-*` attributes kept as the objects' own data: #522; top-level groups open as layers named from `data-name`, else the id, also when one more group (a transform on all the art, a `<switch>`) wraps them, hidden ones hidden, and a file whose art sits loose under a root `<svg>` with an id (or `data-name`), as one-layer exports write it, opens with its one layer named from it; nested groups stay groups, except the sublayers VectorCraft writes, marked `data-vc-layer`, and Inkscape sublayers, which open as sublayers in their layer's colour: #372); PDF and PDF-compatible `.ai` in and out (layers, with hidden ones kept hidden with their art and nested ones as sublayers, on pages of up to 64 million operators, art whose layer can't be told going to a hidden, non-printing layer rather than showing or printing: #419; strokes kept live, a fill and a stroke of one outline as one object; a type object's stroke written as each glyph's outline stroked back on the type, so it stays one editable object; lines wrapped in a frame (each wrapped line ending in a space, one left edge, leading and font) back as one area type object, left aligned or justified with its paragraph spacing, where laying it out breaks the lines where the file does; glyphs set apart by gaps wider than a space (a barcode's digit groups) keeping their places; layers stacked as the pages mark them even when one first paints on a later page, art ending a layer's marked content or a clip closing in a later layer kept in its own layer, and layers with no art kept empty: #508; art reaching past a plain PDF's page clipped to its crop box, as PDF viewers show it, each such object in a clip group of its own (a PDF-compatible `.ai` opens whole: #675); a `.ai` on its trim boxes with the bleed boxes round them as the document's bleed, as Crop To › Trim opens a PDF (#1266); masks, editable text with type set along a curve coming back as type on a path, each artboard's art on its own page only, an `.ai`'s white page under its layers left out rather than coming in as art, spot colours, presets, security, marks and bleed, ICC output intents, raster effects, subset fonts, PDF/X, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3). CMYK images keep their ink amounts from PDF import (and from placed CMYK TIFFs) to PDF export: a CMYK JPEG passes through unchanged, others stay CMYK (DeviceCMYK, or ICC-based CMYK in PDF/X-3/X-4 when not in the output intent's profile) unless the Output settings convert them; the canvas shows them through the working CMYK profile (#320). Overprint is kept from PDF import (opened, the PDF part of an `.ai`, placed) to PDF export: the graphics state's `/OP` and `/op` become the overprint of fills, strokes and type, so a spot colour over a process colour still overprints; a page whose overprint can't be read for certain knocks out with a note, as does `/OPM 0` being read as nonzero overprint (#1388; hand-written fixtures, `pdf/src/tests/import_overprint.rs`). A masked CMYK image (`/SMask`, `/Mask` or a colour key) keeps its inks too, its alpha coming in as a greyscale opacity mask. + - SVG/SVGZ in and out with SVG Options, Preserve Editing, symbols, filters, rich text and physical units (SVG type under a transform or `viewBox` scale opens at the size it draws at, the scale moved into its size, leading, baseline shift and strokes, a stretch, skew or rotation kept as its transform: #396; a top-level group with a clip path, such as a clipped Inkscape layer, opens as a layer with a clipping mask, its name kept: #420; hidden objects written hidden on Save and `convert`, and `data-*` attributes kept as the objects' own data: #522; top-level groups open as layers named from `data-name`, else the id, also when one more group (a transform on all the art, a `<switch>`) wraps them, hidden ones hidden, and a file whose art sits loose under a root `<svg>` with an id (or `data-name`), as one-layer exports write it, opens with its one layer named from it; nested groups stay groups, except the sublayers VectorCraft writes, marked `data-vc-layer`, and Inkscape sublayers, which open as sublayers in their layer's colour: #372); PDF and PDF-compatible `.ai` in and out (layers, with hidden ones kept hidden with their art and nested ones as sublayers, on pages of up to 64 million operators, art whose layer can't be told going to a hidden, non-printing layer rather than showing or printing: #419; strokes kept live, a fill and a stroke of one outline as one object; a type object's stroke written as each glyph's outline stroked back on the type, so it stays one editable object; lines wrapped in a frame (each wrapped line ending in a space, one left edge, leading and font) back as one area type object, left aligned or justified with its paragraph spacing, where laying it out breaks the lines where the file does; glyphs set apart by gaps wider than a space (a barcode's digit groups) keeping their places; layers stacked as the pages mark them even when one first paints on a later page, art ending a layer's marked content or a clip closing in a later layer kept in its own layer, and layers with no art kept empty: #508; art reaching past a plain PDF's page clipped to its crop box, as PDF viewers show it, each such object in a clip group of its own (a PDF-compatible `.ai` opens whole: #675); a `.ai` on its trim boxes with the bleed boxes round them as the document's bleed, as Crop To › Trim opens a PDF (#1266); masks, editable text with type set along a curve coming back as type on a path, each artboard's art on its own page only, an `.ai`'s white page under its layers left out rather than coming in as art, spot colours, presets, security, marks and bleed, ICC output intents, raster effects, subset fonts, PDF/X, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3). CMYK images keep their ink amounts from PDF import (and from placed CMYK TIFFs and the images in an `.ai` or EPS file's editing data, an alpha channel coming in as a grayscale opacity mask) to PDF export: a CMYK JPEG passes through unchanged, others stay CMYK (DeviceCMYK, or ICC-based CMYK in PDF/X-3/X-4 when not in the output intent's profile) unless the Output settings convert them; the canvas shows them through the working CMYK profile (#320). Overprint is kept from PDF import (opened, the PDF part of an `.ai`, placed) to PDF export: the graphics state's `/OP` and `/op` become the overprint of fills, strokes and type, so a spot colour over a process colour still overprints; a page whose overprint can't be read for certain knocks out with a note, as does `/OPM 0` being read as nonzero overprint (#1388; hand-written fixtures, `pdf/src/tests/import_overprint.rs`). A masked CMYK image (`/SMask`, `/Mask` or a colour key) keeps its inks too, its alpha coming in as a greyscale opacity mask. In imported PDF type, a space glyph the file draws between two words also keeps the next word where the file has it when the gap beside the space is wide, as VectorCraft's own export draws a tracked space: the space gets tracking of its own, and the wrapped lines of a justified paragraph still come back as one area type object when the word gaps on each line are alike (part of #2384). Letter-spaced PDF type, whether set with character spacing (`Tc`) or glyph by glyph, keeps its word spaces and gains none between its letters: the spacing a line's letters share is taken off each gap before a gap reads as a space. That holds on a line that also shows where its words break, with spaces the file draws or gaps wider than the rest; evenly spaced glyphs alone, which could be words of one letter, keep every gap as a space, as do glyphs set more than half an em apart, such as figures in columns. A function-based PDF shading (type 1) whose colour changes along one axis only, as a browser writes a repeating linear gradient, comes in as a linear gradient over its domain, each hard colour change two stops at one offset; one whose colour changes in two directions comes in as its average colour, with a warning. Either paints only over the shading's domain. Both came in as a flat grey that wasn't in the file (#3621). Each such shading is read once per import, and all of them within one budget of 200,000 function evaluations, so a file filling thousands of paths with long functions still opens in about a second (it took minutes); past the budget they come in as their average colour, then grey, with a warning. @@ -2089,7 +2089,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - File › Revert also drops what was started for the content it discards: a file being read for Place, for the place cursor or dropped on the canvas, a bitmap being read for Paste, and a paste waiting at its Swatch Conflict dialog are not placed or pasted in the reverted document, and the status bar says the document was reverted. Edits made while a file is read, a Revert that fails or that a batch rolls back, and a Revert of another document leave the read to finish as before (`crates/ui-egui/src/placing/tests.rs`). - The pixels of a PNG, JPEG, GIF or WebP file that Place decodes to check them are kept in the image store the renderers share, so the canvas's first frame with the placed image draws them without decoding the file again on the UI thread: File › Place, a file dropped on the canvas, a click or drag of the place cursor, `file.place`, and Paste of such an image. A CMYK JPEG is still decoded when it is first drawn (`crates/ui-egui/src/placing.rs`, `crates/render/src/tests.rs`). - A photo whose EXIF orientation turns or flips it (a camera held upright or upside down) is placed and opened upright, as it was taken; the image is stored as it is seen (#4284). A quarter turn swaps the resolution's axes, so the image keeps its physical size. TIFFs read without the image decoder (grayscale with extra channels, CCITT Group 3, CMYK with one plane per ink) follow their Orientation tag too, and a turned CMYK JPEG or TIFF keeps its inks, at the 8 or 16 bits the file has, as a CMYK TIFF. - - PDF export writes a CMYK image that keeps its numbers in an `ICCBased` color space holding, byte for byte, the CMYK profile the image carries (a CMYK TIFF's tag 34675, or a CMYK JPEG's `ICC_PROFILE` APP2 segments) when `output.profiles` is `all` or `taggedSource`, and in PDF/A-2b, PDF/X-3 and PDF/X-4 unless it is `destination` ([the help page](https://helpx.adobe.com/illustrator/desktop/save-and-export/export-files-to-different-formats/pdf-marks-bleeds-and-color-output-options.html)). This covers a CMYK JPEG embedded as it is, one the Compression settings resample or compress again, a TIFF written again, and an image written with its mask as its soft mask. With `none`, and in PDF/X-1a, the image is DeviceCMYK and a JPEG's own profile is left out, so PDF/X-1a export writes a CMYK JPEG that carries a profile. Pixels the Output settings convert are never tagged with the profile of their old numbers. A profile tags an image only when its size, signature, class, CMYK color space and tag table are well formed and it is at most 16 MiB (VectorCraft's own limit). Transparency in a tagged CMYK document blends in the document's CMYK profile; when the file holds no space of that profile it blends in DeviceCMYK, or keeps its RGB space in PDF/A, and never in an image's own profile (`crates/pdf/src/tests/cmykimages.rs`, `export::writer::tests`). + - PDF export writes a CMYK image that keeps its numbers in an `ICCBased` color space holding, byte for byte, the CMYK profile the image carries (a CMYK TIFF's tag 34675, or a CMYK JPEG's `ICC_PROFILE` APP2 segments) when `output.profiles` is `all` or `taggedSource`, and in PDF/A-2b, PDF/X-3 and PDF/X-4 unless it is `destination`, except in PDF/X-3 and PDF/X-4 when that profile is the CMYK output intent's, or when `none` makes every CMYK color DeviceCMYK (#1954) ([the help page](https://helpx.adobe.com/illustrator/desktop/save-and-export/export-files-to-different-formats/pdf-marks-bleeds-and-color-output-options.html)). This covers a CMYK JPEG embedded as it is, one the Compression settings resample or compress again, a TIFF written again, and an image written with its mask as its soft mask. With `none`, and in PDF/X-1a, the image is DeviceCMYK and a JPEG's own profile is left out, so PDF/X-1a export writes a CMYK JPEG that carries a profile. Pixels the Output settings convert are never tagged with the profile of their old numbers. A profile tags an image only when its size, signature, class, CMYK color space and tag table are well formed and it is at most 16 MiB (VectorCraft's own limit). Transparency in a tagged CMYK document blends in the document's CMYK profile; when the file holds no space of that profile it blends in DeviceCMYK, or keeps its RGB space in PDF/A, and never in an image's own profile (`crates/pdf/src/tests/cmykimages.rs`, `export::writer::tests`). - When the Output settings convert an image's colors ([the help page](https://helpx.adobe.com/illustrator/desktop/save-and-export/export-files-to-different-formats/pdf-marks-bleeds-and-color-output-options.html)), PDF export leaves out an image whose pixels can't be decoded or written in the destination's colors, with the warning "an image couldn't be converted to the Output destination and is missing from the picture", in every standard, instead of writing it in its own colors. This covers a CMYK image with more than 2^26 pixels, the most VectorCraft reads CMYK inks for, and a color image that could be embedded as it is but is more than VectorCraft decodes. A color image whose pixel data can't be read is left out with the warning "an image couldn't be decoded and is missing from the picture", as without a conversion. Gray images, whose pixels are not converted, images in a file that converts no colors, and a gray or RGB image that an sRGB destination would convert from its ICC profile (it keeps the profile, with a warning) are written as before, and an image that can't be written at all still gets the warning that it couldn't be decoded (`crates/pdf/src/tests/cmykimages.rs`, `crates/pdf/src/tests/compression.rs`). - PDF export with `output.profiles` set to `none` (Don't Include Profiles) writes no image with the ICC profile it carries, as [the help page](https://helpx.adobe.com/illustrator/desktop/save-and-export/export-files-to-different-formats/pdf-marks-bleeds-and-color-output-options.html) describes for that setting: gray and RGB PNG, JPEG and TIFF images embedded as they are, resampled or compressed again, and CMYK JPEG images. A JPEG kept as it is loses its `ICC_PROFILE` APP2 segments, its other segments and compressed samples unchanged. PDF/A-2b, PDF/X-3 and PDF/X-4 files keep the profiles they tag images with. Left unset (the default, `"default"`, listed as Default in Save PDF), the setting writes device colors while gray and RGB images keep their profiles, as before; that default is VectorCraft's own rule (`a_set_dont_include_profiles_removes_image_profiles`, `a_set_dont_include_profiles_takes_a_cmyk_jpegs_profile_out`). - PDF import keeps the CMYK profile of an image in a four-component `ICCBased` color space, whose stream holds the profile ([ISO 32000-1, §8.6.5.5](https://opensource.adobe.com/dc-acrobat-sdk-docs/pdfstandards/PDF32000_2008.pdf#page=157)), byte for byte with the image's ink amounts, so PDF export can write the image in it again. A CMYK TIFF carries it as tag 34675, whatever the image's Decode array and bit depth ([ICC.1:2010, Annex B](https://www.color.org/specification/ICC1v43_2010-12.pdf)). A CMYK JPEG kept as it is carries it in `ICC_PROFILE` APP2 segments in place of a profile of its own, with its compressed samples unchanged, and one whose segments can't hold it is stored as a CMYK TIFF carrying it. A profile that isn't well formed, isn't of CMYK colors or is over 16 MiB (VectorCraft's own limit) leaves the image's inks as they are, untagged. DeviceCMYK and DeviceN images carry no profile, and a CMYK TIFF's tag 34675 is read up to 16 MiB. EPS and PostScript import does not keep one: PostScript defines no `ICCBased` profile stream (`crates/pdf/src/tests/cmykimages.rs`, `cmyk::tests`). From 3c7f03f62df17be4e8b133bddc18e82becd0ae37 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 17 Nov 2026 00:00:19 -0800 Subject: [PATCH 086/176] Stroke: the Profile list is dimmed while the stroke's brush keeps its own size Brush art does not follow a stroke's width profile, so picking a profile for a brushed stroke changed nothing on the canvas. - While every stroke the Profile list edits draws with a brush, the list in the Stroke panel, the Properties panel and the Control bar is dimmed and says why when hovered. It opens no list while those strokes are uniform, and offers only Uniform, which removes the profiles, while one has a profile. The Flip Along and Flip Across buttons beside it are off. The strokes are the ones stroke.set edits: the active Appearance stroke row, a selected group's or compound shape's own stroke, or the objects' top strokes. Images and symbol instances do not count. A selection where one stroke has no brush keeps the full list. - The Width tool adds, edits and deletes no width points on a brushed stroke; a press or double-click on one, or Delete with its width points selected, shows the same reason in the status bar. Without Shift, the press deselects the width points of other strokes. A plain stroke under a selected brushed one stays reachable, and width points selected before their stroke took a brush show no handles. - The reason has a row in every complete catalog. --- crates/brush/src/lib.rs | 8 + crates/engine/src/cmd/stroke.rs | 45 +++ crates/engine/src/tests/appearance.rs | 106 +++++++ crates/engine/src/tooling.rs | 1 + crates/tools/src/distort/width.rs | 260 +++++++++++++++++- crates/tools/src/input.rs | 4 + crates/ui-egui/src/chrome/control_bar.rs | 2 +- crates/ui-egui/src/i18n/bg.tsv | 2 + crates/ui-egui/src/i18n/bs.tsv | 2 + crates/ui-egui/src/i18n/ca.tsv | 2 + crates/ui-egui/src/i18n/cs.tsv | 2 + crates/ui-egui/src/i18n/da.tsv | 2 + crates/ui-egui/src/i18n/de.tsv | 2 + crates/ui-egui/src/i18n/el.tsv | 2 + crates/ui-egui/src/i18n/es.tsv | 2 + crates/ui-egui/src/i18n/fi.tsv | 2 + crates/ui-egui/src/i18n/fr.tsv | 2 + crates/ui-egui/src/i18n/gu.tsv | 2 + crates/ui-egui/src/i18n/hi.tsv | 2 + crates/ui-egui/src/i18n/hu.tsv | 2 + crates/ui-egui/src/i18n/id.tsv | 2 + crates/ui-egui/src/i18n/it.tsv | 2 + crates/ui-egui/src/i18n/ja.tsv | 2 + crates/ui-egui/src/i18n/ka.tsv | 2 + crates/ui-egui/src/i18n/ko.tsv | 2 + crates/ui-egui/src/i18n/nl.tsv | 2 + crates/ui-egui/src/i18n/pl.tsv | 2 + crates/ui-egui/src/i18n/pt-br.tsv | 2 + crates/ui-egui/src/i18n/ru.tsv | 2 + crates/ui-egui/src/i18n/sv.tsv | 2 + crates/ui-egui/src/i18n/tr.tsv | 2 + crates/ui-egui/src/i18n/uk.tsv | 2 + crates/ui-egui/src/i18n/vi.tsv | 2 + crates/ui-egui/src/i18n/zh-hans.tsv | 2 + crates/ui-egui/src/i18n/zh-hant.tsv | 2 + crates/ui-egui/src/panels/properties.rs | 2 +- crates/ui-egui/src/panels/properties/tests.rs | 20 ++ crates/ui-egui/src/panels/stroke.rs | 66 ++++- .../ui-egui/src/panels/tests_strokedepth.rs | 195 ++++++++++++- docs/target-app-parity.md | 1 + 40 files changed, 739 insertions(+), 27 deletions(-) diff --git a/crates/brush/src/lib.rs b/crates/brush/src/lib.rs index 0b48f586cd..04ebd41b10 100644 --- a/crates/brush/src/lib.rs +++ b/crates/brush/src/lib.rs @@ -1008,6 +1008,14 @@ pub fn has_brush(n: &Node) -> bool { n.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Stroke(s) if s.brush.is_some() && s.visible)) } +/// Does `stroke` draw with a brush of `lib` (the document's [`library`])? [`stroke_pieces`] sizes +/// brush art from the brush and the stroke weight and does not read the stroke's width profile, so +/// the profile does not change what such a stroke draws. A stroke without a brush, or one that +/// names a brush `lib` lacks, draws a plain stroke, which follows the profile. +pub fn keeps_brush_size(lib: &[Brush], stroke: &StrokeLayer) -> bool { + stroke.brush.as_deref().is_some_and(|name| lib.iter().any(|b| b.name == name)) +} + /// How far brush art can paint past the visual box of `n`: `16 × w + 8`, where `w` is the widest /// stroke of `n` (at least 1), when `n` has a visible brushed stroke with a paint; 0 when it has /// none, as a brushed stroke without a paint draws no brush art. This is the room the renderer and diff --git a/crates/engine/src/cmd/stroke.rs b/crates/engine/src/cmd/stroke.rs index e8fb1349c3..038483182f 100644 --- a/crates/engine/src/cmd/stroke.rs +++ b/crates/engine/src/cmd/stroke.rs @@ -429,6 +429,51 @@ impl Session { painted(first, true, &mut nodes); node_stroke(nodes.first()?) } + + /// Do all the strokes that `stroke.set` edits without `ids` or `item` draw with a brush + /// ([`vectorcraft_brush::keeps_brush_size`])? If they do, a width profile changes none of + /// them, and the result is `Some`, holding whether any of them has a width profile. The result + /// is `None` when a profile changes at least one of them. + /// + /// The strokes are the ones `stroke.set` edits: + /// - the Appearance panel's active stroke row in each target that has an equal row + /// ([`ItemTarget::per_target`]), and the top stroke in the others; + /// - else a selected group's own stroke; + /// - else the top strokes of the objects it paints ([`own_stroke_or_leaves`]). + /// + /// The art of graph designs is left out, and so are images and symbol instances without an + /// active row. The result is also `None` with nothing selected, with an object inside a symbol + /// instance selected, with type among the targets, and with a target that has no stroke row, + /// since `stroke.set` gives such a target a plain stroke. + pub fn brushed_strokes_profiled(&self) -> Option<bool> { + const C: &str = "stroke.set"; + let st = self.active()?; + if st.selected_symbol_part().is_some() { + return None; + } + let p = json!({}); + let item = item_target(self, &p, C).ok()?.of_kind(self, false); + let ids = if item == ItemTarget::Top { own_stroke_or_leaves(self, &p).ok()? } else { item.targets(self, &p).ok()? }; + let mut ids = super::appearance::drop_design_art_rows(self, ids, item, false, C).ok()?; + if item == ItemTarget::Top { + ids.retain(|id| !matches!(st.doc.node(*id).map(|n| &n.kind), Some(NodeKind::Image(_) | NodeKind::SymbolInstance { .. }))); + } + let mut strokes = vec![]; + for (id, each) in ids.iter().zip(item.per_target(self, &ids)) { + let n = st.doc.node(*id)?; + let row = each?.resolve(&n.appearance, false, C).ok()?; + if row.is_none() && matches!(n.kind, NodeKind::Text(_)) { + return None; + } + strokes.push(n.appearance.stroke_at(row).filter(|s| s.brush.is_some())?); + } + if strokes.is_empty() { + return None; + } + // The library is read only when every stroke names a brush. + let lib = vectorcraft_brush::library(&st.doc); + strokes.iter().all(|s| vectorcraft_brush::keeps_brush_size(&lib, s)).then(|| strokes.iter().any(|s| s.profile.is_some())) + } } impl DocState { diff --git a/crates/engine/src/tests/appearance.rs b/crates/engine/src/tests/appearance.rs index 53cbb42ca9..a04bb89b4a 100644 --- a/crates/engine/src/tests/appearance.rs +++ b/crates/engine/src/tests/appearance.rs @@ -227,6 +227,112 @@ fn stroke_options_on_a_group_with_its_own_stroke_edit_that_stroke() { assert_eq!((st.paint, st.width), (Paint::solid(Color::BLACK), 3.0)); } +/// `brushed_strokes_profiled` reads the strokes `stroke.set` edits: a group's own stroke when it +/// has one, else its members'. It answers only while each of them draws with a brush, and not +/// while an object has no stroke row, which `stroke.set` would give a plain stroke. +#[test] +fn brushed_strokes_profiled_reads_the_strokes_stroke_set_edits() { + let mut s = session(); + let (a, b) = (rect(&mut s, 100.0), rect(&mut s, 250.0)); + run(&mut s, "brush.apply", json!({"ids": [a.0, b.0], "name": "3 pt. Round"})); + run(&mut s, "select.set", json!({"ids": [a.0, b.0]})); + assert_eq!(s.brushed_strokes_profiled(), Some(false), "both draw with a brush, neither has a profile"); + run(&mut s, "stroke.set", json!({"ids": [b.0], "profile": "lens"})); + run(&mut s, "select.set", json!({"ids": [a.0, b.0]})); + assert_eq!(s.brushed_strokes_profiled(), Some(true), "one has a profile"); + let g = NodeId(run(&mut s, "object.group", json!({"ids": [a.0, b.0]}))["id"].as_u64().unwrap()); + run(&mut s, "select.set", json!({"ids": [g.0]})); + assert_eq!(s.brushed_strokes_profiled(), Some(true), "a group without its own stroke: its members'"); + run(&mut s, "appearance.addStroke", json!({"ids": [g.0]})); + run(&mut s, "select.set", json!({"ids": [g.0]})); + assert_eq!(s.brushed_strokes_profiled(), None, "the group's own plain stroke takes the profile"); + let c = rect(&mut s, 400.0); + run(&mut s, "appearance.removeItem", json!({"ids": [c.0], "index": 1})); + assert!(node(&s, c).appearance.stroke().is_none()); + run(&mut s, "select.set", json!({"ids": [a.0, c.0]})); + assert_eq!(s.brushed_strokes_profiled(), None, "an object without a stroke row takes a plain stroke"); +} + +/// A compound shape's own stroke is the one `stroke.set` edits: brushed members do not count. +#[test] +fn brushed_strokes_profiled_reads_a_compound_shapes_own_stroke() { + let mut s = session(); + let (a, b) = (rect(&mut s, 100.0), rect(&mut s, 120.0)); + run(&mut s, "select.set", json!({"ids": [a.0, b.0]})); + let c = NodeId(run(&mut s, "object.compoundShape.make", json!({"mode": "add"}))["id"].as_u64().unwrap()); + assert!(node(&s, c).appearance.stroke().is_some_and(|st| st.brush.is_none()), "the compound shape's own plain stroke"); + s.edit("Brush", |d, _| { + for id in [a, b] { + if let Some(st) = d.node_mut(id).and_then(|n| n.appearance.stroke_mut()) { + st.brush = Some("3 pt. Round".into()); + } + } + Ok(()) + }) + .unwrap(); + run(&mut s, "select.set", json!({"ids": [c.0]})); + assert_eq!(s.brushed_strokes_profiled(), None); + s.edit("Brush", |d, _| { + d.node_mut(c).unwrap().appearance.stroke_mut().unwrap().brush = Some("3 pt. Round".into()); + Ok(()) + }) + .unwrap(); + run(&mut s, "select.set", json!({"ids": [c.0]})); + assert_eq!(s.brushed_strokes_profiled(), Some(false)); +} + +/// A targeted layer with its own plain Stroke row active: `stroke.set` edits that row, so the +/// brushed path inside the layer does not count. +#[test] +fn brushed_strokes_profiled_reads_a_targeted_layers_active_stroke_row() { + let mut s = session(); + let a = rect(&mut s, 100.0); + run(&mut s, "brush.apply", json!({"ids": [a.0], "name": "3 pt. Round"})); + let layer = s.doc().unwrap().doc.layers[0].id; + run(&mut s, "layer.target", json!({"id": layer.0})); + run(&mut s, "appearance.addStroke", json!({})); + let rows = &node(&s, layer).appearance.items; + let index = rows.iter().position(|it| matches!(it, AppearanceItem::Stroke(st) if st.brush.is_none())).expect("the layer's own stroke row"); + run(&mut s, "appearance.setActiveItem", json!({"index": index})); + assert_eq!(s.brushed_strokes_profiled(), None, "the layer's plain stroke takes the profile"); + run(&mut s, "stroke.set", json!({"profile": "lens"})); + assert!(node(&s, layer).appearance.items.get(index).is_some_and(|it| matches!(it, AppearanceItem::Stroke(st) if st.profile.is_some()))); + assert!(node(&s, a).appearance.stroke().is_some_and(|st| st.profile.is_none()), "the brushed path is left as it was"); +} + +/// A symbol instance selected with a brushed path takes no stroke from `stroke.set`, so it does +/// not count; the brushed path alone decides. +#[test] +fn brushed_strokes_profiled_leaves_out_symbol_instances() { + let mut s = session(); + let a = rect(&mut s, 100.0); + run(&mut s, "brush.apply", json!({"ids": [a.0], "name": "3 pt. Round"})); + let r = rect(&mut s, 300.0); + run(&mut s, "select.set", json!({"ids": [r.0]})); + let inst = NodeId(run(&mut s, "symbol.new", json!({"name": "Dot"}))["id"].as_u64().unwrap()); + assert!(matches!(node(&s, inst).kind, NodeKind::SymbolInstance { .. })); + run(&mut s, "select.set", json!({"ids": [a.0, inst.0]})); + assert_eq!(s.brushed_strokes_profiled(), Some(false)); +} + +/// With the active row a stroke of the first object that another selected object has no equal +/// row for, `stroke.set` edits that object's top stroke, so its top stroke decides. +#[test] +fn brushed_strokes_profiled_falls_back_to_the_top_stroke_where_the_active_row_has_no_match() { + let mut s = session(); + let (a, b) = (rect(&mut s, 100.0), rect(&mut s, 250.0)); + run(&mut s, "select.set", json!({"ids": [a.0]})); + run(&mut s, "appearance.addStroke", json!({})); + run(&mut s, "brush.apply", json!({"ids": [a.0, b.0], "name": "3 pt. Round"})); + run(&mut s, "stroke.set", json!({"ids": [b.0], "weight": 5})); + let rows = &node(&s, a).appearance.items; + let index = rows.iter().position(|it| matches!(it, AppearanceItem::Stroke(st) if st.brush.is_some())).expect("a's brushed stroke"); + assert!(index >= node(&s, b).appearance.items.len() || node(&s, b).appearance.items[index].is_fill(), "{rows:?}"); + run(&mut s, "select.set", json!({"ids": [a.0, b.0]})); + run(&mut s, "appearance.setActiveItem", json!({"index": index})); + assert_eq!(s.brushed_strokes_profiled(), Some(false), "b's top stroke has the brush too"); +} + #[test] fn text_items_take_item_paint() { let mut s = session(); diff --git a/crates/engine/src/tooling.rs b/crates/engine/src/tooling.rs index 9250cf8030..542ee871d3 100644 --- a/crates/engine/src/tooling.rs +++ b/crates/engine/src/tooling.rs @@ -1530,6 +1530,7 @@ impl Session { } Action::Dialog(k, p) => ui.push(UiRequest::Dialog(k, p)), Action::SwitchTool(t) => ui.push(UiRequest::SwitchTool(t)), + Action::Status(msg) => ui.push(UiRequest::Status(msg)), Action::Notify(what) => { let view = self.last_view; self.with_tool_cx(view, |t, cx| t.notify(cx, &what)); diff --git a/crates/tools/src/distort/width.rs b/crates/tools/src/distort/width.rs index 4ebbac4981..7eda93305e 100644 --- a/crates/tools/src/distort/width.rs +++ b/crates/tools/src/distort/width.rs @@ -19,8 +19,18 @@ //! A compound path's stroke is the compound's: its members are edited through it, and the width //! points show on every subpath of the stroke (one profile runs along each). The cursor says what a //! drag does: add a width point on a stroke, or move or widen the one under it. +//! +//! A stroke drawn with a brush is left alone, as a width profile does not change it: a press or a +//! double-click on it, and Delete/Backspace with its width points selected, send no command and +//! show why in the status bar ([`KEEPS_SIZE`]). A press or double-click on it deselects the +//! width points, the cursor over it offers no edit, and its width points selected before it took +//! the brush show no handles. + +use std::cell::Cell; +use std::sync::Arc; use serde_json::json; +use vectorcraft_brush::Brush; use vectorcraft_doc::{Document, NodeId, NodeKind, StrokeLayer}; use vectorcraft_geom::{Point, Vec2}; @@ -107,8 +117,14 @@ pub struct WidthTool { selected: Option<(NodeId, Vec<f64>)>, /// The selected width points when the button went down: a dropped press puts them back. before_press: Option<(NodeId, Vec<f64>)>, + /// The document's brush library as it was at a revision, so pointer moves and overlays do not + /// parse it again ([`Self::keeps_size`]). + brushes: Cell<Option<BrushesAt>>, } +/// A document revision and its brush library ([`WidthTool::keeps_size`]). +type BrushesAt = ((u64, u64), Arc<Vec<Brush>>); + /// The object whose stroke path `id` draws with: its compound path, if it is a member of one. pub fn stroke_owner(doc: &Document, id: NodeId) -> NodeId { doc.parent_of(id).filter(|p| doc.node(*p).is_some_and(|n| matches!(n.kind, NodeKind::Compound { .. }))).unwrap_or(id) @@ -132,6 +148,9 @@ fn paths_of(doc: &Document, owner: NodeId) -> Vec<NodeId> { out } +/// The status message for a press on a stroke the tool leaves alone ([`WidthTool::keeps_size`]). +pub const KEEPS_SIZE: &str = "The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile."; + /// Side widths (points) of a stroke at fraction `t`. pub fn sides_at(st: &StrokeLayer, t: f64) -> (f64, f64) { let (l, r) = st.profile.as_ref().map(|p| p.at(t)).unwrap_or((1.0, 1.0)); @@ -139,8 +158,46 @@ pub fn sides_at(st: &StrokeLayer, t: f64) -> (f64, f64) { } impl WidthTool { - /// The stroked path nearest to `p` within reach (stroke half-width + a few pixels). - fn spot_at(cx: &ToolContext, p: Point) -> Option<Spot> { + /// Does `owner`'s stroke draw with a brush ([`vectorcraft_brush::keeps_brush_size`])? A width + /// profile does not change it, so the tool adds and edits no width points on it. The library is + /// parsed once per document revision. + fn keeps_size(&self, cx: &ToolContext, owner: NodeId) -> bool { + let Some(st) = stroke_of(cx.doc, owner).filter(|s| s.brush.is_some()) else { return false }; + let lib = self + .brushes + .take() + .filter(|(rev, _)| *rev == cx.revision) + .map(|(_, lib)| lib) + .unwrap_or_else(|| Arc::new(vectorcraft_brush::library(cx.doc))); + let keeps = vectorcraft_brush::keeps_brush_size(&lib, st); + self.brushes.set(Some((cx.revision, lib))); + keeps + } + + /// Where a press at `p` lands: the nearest stroke the tool edits ([`Self::spot_at`] without + /// brushed strokes), so a plain stroke under a selected brushed one stays reachable. `Err(true)` + /// when only brushed strokes are within reach, `Err(false)` when no stroke is. + fn edit_spot_at(&self, cx: &ToolContext, p: Point) -> Result<Spot, bool> { + // `spot_at` asks `skip` only about strokes within reach, so one search tells both apart. + let passed_over = Cell::new(false); + let skip = |owner| { + let keeps = self.keeps_size(cx, owner); + passed_over.set(passed_over.get() || keeps); + keeps + }; + Self::spot_at(cx, p, &skip).ok_or_else(|| passed_over.get()) + } + + /// The hovered stroke while the tool still edits it: a brush applied since the last pointer + /// move takes away its handles and its edit cursor. + fn live_hover(&self, cx: &ToolContext) -> Option<Spot> { + self.hover.filter(|s| !self.keeps_size(cx, s.owner)) + } + + /// The stroked path nearest to `p` within reach (stroke half-width + a few pixels), passing over + /// the strokes whose owner `skip` returns true for. `skip` is asked only about strokes within + /// reach. + fn spot_at(cx: &ToolContext, p: Point, skip: &dyn Fn(NodeId) -> bool) -> Option<Spot> { let editable = cx.doc.editable(); let consider = |id: NodeId| -> Option<(f64, Spot)> { if !editable(id) { @@ -156,7 +213,7 @@ impl WidthTool { return None; } let (sub, t, q, tan, d) = nearest_fraction(path, p)?; - if d > reach { + if d > reach || skip(owner) { return None; } let (left, right) = sides_at(st, t); @@ -297,12 +354,22 @@ impl Tool for WidthTool { let p = ev.pos; match ev.kind { PointerKind::Move => { - self.hover = Self::spot_at(cx, p); + // A brushed stroke takes no width points, so the cursor offers no edit over it. + self.hover = self.edit_spot_at(cx, p).ok(); vec![] } PointerKind::TripleClick => vec![], PointerKind::DoubleClick => { - let Some(spot) = Self::spot_at(cx, p) else { return vec![] }; + let spot = match self.edit_spot_at(cx, p) { + Ok(spot) => spot, + Err(false) => return vec![], + Err(true) => { + if !ev.mods.shift { + self.selected = None; + } + return vec![Action::Status(KEEPS_SIZE.into())]; + } + }; let Some((w, _)) = Self::hit(cx, &spot, p) else { self.selected = Some((spot.owner, vec![spot.t])); return vec![Action::Dialog("widthPoint".into(), json!({"id": spot.owner.0, "t": spot.t}))]; @@ -312,11 +379,14 @@ impl Tool for WidthTool { } PointerKind::Down => { self.before_press = self.selected.clone(); - let Some(spot) = Self::spot_at(cx, p) else { - if !ev.mods.shift { - self.selected = None; + let spot = match self.edit_spot_at(cx, p) { + Ok(spot) => spot, + Err(brushed) => { + if !ev.mods.shift { + self.selected = None; + } + return if brushed { vec![Action::Status(KEEPS_SIZE.into())] } else { vec![] }; } - return vec![]; }; let drag = match Self::hit(cx, &spot, p) { Some((w, part)) => { @@ -426,12 +496,16 @@ impl Tool for WidthTool { return vec![]; } self.selected = None; + if self.keeps_size(cx, id) { + return vec![Action::Status(KEEPS_SIZE.into())]; + } vec![Action::Exec("stroke.widthPoint.remove".into(), json!({"id": id.0, "indices": indices}))] } fn overlays(&self, cx: &ToolContext) -> Vec<Overlay> { let mut out = vec![]; let r = cx.tol(4.0); - let focus = self.drag.as_ref().map(|d| d.spot).or(self.hover); + let hover = self.live_hover(cx); + let focus = self.drag.as_ref().map(|d| d.spot).or(hover); // Every subpath's width points of the stroke under the pointer, and of the selected ones'. let show = |owner: NodeId, out: &mut Vec<Overlay>| { for w in Self::all_points(cx, owner) { @@ -445,8 +519,11 @@ impl Tool for WidthTool { if let Some(s) = focus { show(s.owner, &mut out); } + // Width points selected before their stroke took a brush show no handles: the tool no + // longer edits them. if let Some((owner, _)) = &self.selected && focus.is_none_or(|s| s.owner != *owner) + && !self.keeps_size(cx, *owner) { show(*owner, &mut out); } @@ -457,7 +534,7 @@ impl Tool for WidthTool { if cx.measurement_labels { out.push(Overlay::Measure { p: q + d.spot.n * (d.left + r * 3.0), text: format!("W: {}", cx.stroke_unit.readout(d.left + d.right)) }); } - } else if let Some(h) = &self.hover { + } else if let Some(h) = &hover { out.push(Overlay::Line { a: h.p + h.n * h.left, b: h.p - h.n * h.right, color: BLUE, dashed: true }); out.push(Overlay::Path { path: diamond(h.p, r), color: BLUE, width: 1.0, dashed: false }); } @@ -468,7 +545,7 @@ impl Tool for WidthTool { return Cursor::WidthPoint; } // The stroke under the pointer, as the last move found it (no search every frame). - match self.hover { + match self.live_hover(cx) { Some(spot) if Self::hit(cx, &spot, p).is_some() => Cursor::WidthPoint, Some(_) => Cursor::WidthAdd, None => Cursor::Width, @@ -538,6 +615,165 @@ mod tests { assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Up, 150.0, 220.0)), vec![Action::Commit]); } + /// A stroke drawn with a brush of the library (the 3 pt. Round calligraphic brush) is left + /// alone: a press or a double-click sends no command and says why. A brush name the library + /// lacks draws a plain stroke, which the tool edits as usual. + #[test] + fn brushed_stroke_is_left_alone_with_a_reason() { + let (mut d, id) = doc_line(); + d.node_mut(id).unwrap().appearance.stroke_mut().unwrap().brush = Some("3 pt. Round".into()); + let (s, p) = (Selection::default(), paint()); + let mut t = WidthTool::default(); + let c = cx(&d, &s, &p); + let refused = vec![Action::Status(KEEPS_SIZE.into())]; + assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Down, 150.0, 201.0)), refused); + assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 150.0, 220.0)), vec![], "no drag began"); + assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Up, 150.0, 220.0)), vec![]); + assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::DoubleClick, 150.0, 201.0)), refused); + + d.node_mut(id).unwrap().appearance.stroke_mut().unwrap().brush = Some("No Such Brush".into()); + let c = cx(&d, &s, &p); + assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Down, 150.0, 201.0)), vec![Action::Begin("Width Point".into())]); + } + + /// A selected brushed stroke lying on a plain one does not hide the plain one: a press there + /// edits the plain stroke. + #[test] + fn a_plain_stroke_under_a_selected_brushed_one_stays_reachable() { + let (mut d, _) = doc_line(); + let l = d.layers[0].id; + let brushed = d.alloc_id(); + let mut ap = Appearance::default_art(); + let st = ap.stroke_mut().unwrap(); + st.width = 10.0; + st.brush = Some("3 pt. Round".into()); + let path = PathData::single(SubPath::polyline(&[Point::new(100.0, 200.0), Point::new(300.0, 200.0)], false)); + d.insert(Some(l), 0, Node::path(brushed, path, ap)).unwrap(); + let (s, p) = (Selection { objects: vec![brushed], ..Default::default() }, paint()); + let mut t = WidthTool::default(); + let c = cx(&d, &s, &p); + t.pointer(&c, &PointerEvent::new(PointerKind::Move, 150.0, 201.0)); + assert_eq!(t.cursor(&c, Point::new(150.0, 201.0), Mods::default()), Cursor::WidthAdd); + assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Down, 150.0, 201.0)), vec![Action::Begin("Width Point".into())]); + } + + /// A brush applied to the hovered stroke, with the pointer still, takes away its handles and its + /// edit cursor before the next pointer move. + #[test] + fn a_brush_applied_under_a_still_pointer_takes_away_the_hover() { + let (mut d, id) = doc_line(); + let (s, p) = (Selection::default(), paint()); + let mut t = WidthTool::default(); + let c = cx(&d, &s, &p); + t.pointer(&c, &PointerEvent::new(PointerKind::Move, 150.0, 201.0)); + assert_eq!(t.cursor(&c, Point::new(150.0, 201.0), Mods::default()), Cursor::WidthAdd); + assert!(!t.overlays(&c).is_empty()); + d.node_mut(id).unwrap().appearance.stroke_mut().unwrap().brush = Some("3 pt. Round".into()); + let c = ToolContext { revision: (0, 1), ..cx(&d, &s, &p) }; + assert_eq!(t.cursor(&c, Point::new(150.0, 201.0), Mods::default()), Cursor::Width); + assert!(t.overlays(&c).is_empty()); + } + + /// The brush library is read once per document revision: a brush added to the library under a + /// new revision is seen, so a stroke naming it is then left alone. + #[test] + fn a_brush_added_to_the_library_is_seen_at_the_next_revision() { + let (mut d, id) = doc_line(); + d.node_mut(id).unwrap().appearance.stroke_mut().unwrap().brush = Some("Added Later".into()); + let (s, p) = (Selection::default(), paint()); + let mut t = WidthTool::default(); + let c = cx(&d, &s, &p); + assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Down, 150.0, 201.0)), vec![Action::Begin("Width Point".into())]); + t.pointer(&c, &PointerEvent::new(PointerKind::Up, 150.0, 201.0)); + let mut lib = vectorcraft_brush::library(&d); + let mut added = lib[0].clone(); + added.name = "Added Later".into(); + lib.push(added); + vectorcraft_brush::store(&mut d, &lib); + let c = ToolContext { revision: (0, 1), ..cx(&d, &s, &p) }; + assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Down, 150.0, 201.0)), vec![Action::Status(KEEPS_SIZE.into())]); + } + + /// Width points selected before the stroke took a brush: Delete removes none and says why. + #[test] + fn delete_leaves_the_width_points_of_a_brushed_stroke() { + let (mut d, id) = doc_line(); + d.node_mut(id).unwrap().appearance.stroke_mut().unwrap().profile = + Some(WidthProfile { points: vec![(0.0, 1.0, 1.0), (0.5, 2.0, 2.0), (1.0, 1.0, 1.0)] }); + let (s, p) = (Selection::default(), paint()); + let mut t = WidthTool::default(); + let c = cx(&d, &s, &p); + t.pointer(&c, &PointerEvent::new(PointerKind::Down, 200.0, 200.0)); + t.pointer(&c, &PointerEvent::new(PointerKind::Up, 200.0, 200.0)); + assert!(t.claims_key(&c, ToolKey::Delete), "a width point is selected"); + assert!(!t.overlays(&c).is_empty(), "the selected point shows its handles"); + d.node_mut(id).unwrap().appearance.stroke_mut().unwrap().brush = Some("3 pt. Round".into()); + let c = ToolContext { revision: (0, 1), ..cx(&d, &s, &p) }; + assert!(t.overlays(&c).is_empty(), "no handles show on a stroke the tool no longer edits"); + assert_eq!(t.key(&c, ToolKey::Delete, Mods::default()), vec![Action::Status(KEEPS_SIZE.into())]); + assert!(t.selected.is_none()); + } + + /// With Shift held, a press or a double-click on a brushed stroke keeps the width points of + /// another stroke selected, as a Shift-press that misses every stroke does. + #[test] + fn shift_on_a_brushed_stroke_keeps_the_selected_width_points() { + let (mut d, _) = doc_three_points(); + let l = d.layers[0].id; + let other = d.alloc_id(); + let mut ap = Appearance::default_art(); + let st = ap.stroke_mut().unwrap(); + st.width = 10.0; + st.brush = Some("3 pt. Round".into()); + let path = PathData::single(SubPath::polyline(&[Point::new(100.0, 400.0), Point::new(300.0, 400.0)], false)); + d.insert(Some(l), 0, Node::path(other, path, ap)).unwrap(); + let (s, p) = (Selection::default(), paint()); + let shift = Mods { shift: true, ..Default::default() }; + let mut t = WidthTool::default(); + let c = cx(&d, &s, &p); + t.pointer(&c, &PointerEvent::new(PointerKind::Down, 200.0, 200.0)); + t.pointer(&c, &PointerEvent::new(PointerKind::Up, 200.0, 200.0)); + let kept = t.selected.clone(); + assert!(kept.is_some(), "the plain stroke's width point is selected"); + for kind in [PointerKind::Down, PointerKind::DoubleClick] { + assert_eq!(t.pointer(&c, &ev(kind, 200.0, 401.0, shift)), vec![Action::Status(KEEPS_SIZE.into())]); + assert_eq!(t.selected, kept, "{kind:?} with Shift keeps the selection"); + } + assert_eq!(t.pointer(&c, &ev(PointerKind::DoubleClick, 200.0, 401.0, Mods::default())), vec![Action::Status(KEEPS_SIZE.into())]); + assert!(t.selected.is_none(), "a double-click without Shift deselects"); + } + + /// A press on a brushed stroke deselects the width points of another stroke, as a press that + /// misses every stroke does, so a later Delete does not edit that other stroke. The cursor over + /// a brushed stroke offers no edit. + #[test] + fn a_press_on_a_brushed_stroke_deselects_and_its_cursor_offers_no_edit() { + let (mut d, _) = doc_three_points(); + let l = d.layers[0].id; + let other = d.alloc_id(); + let mut ap = Appearance::default_art(); + let st = ap.stroke_mut().unwrap(); + st.width = 10.0; + st.brush = Some("3 pt. Round".into()); + let path = PathData::single(SubPath::polyline(&[Point::new(100.0, 400.0), Point::new(300.0, 400.0)], false)); + d.insert(Some(l), 0, Node::path(other, path, ap)).unwrap(); + let (s, p) = (Selection::default(), paint()); + let mut t = WidthTool::default(); + let c = cx(&d, &s, &p); + t.pointer(&c, &PointerEvent::new(PointerKind::Down, 200.0, 200.0)); + t.pointer(&c, &PointerEvent::new(PointerKind::Up, 200.0, 200.0)); + assert!(t.claims_key(&c, ToolKey::Delete), "the plain stroke's width point is selected"); + assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Down, 200.0, 401.0)), vec![Action::Status(KEEPS_SIZE.into())]); + t.pointer(&c, &PointerEvent::new(PointerKind::Up, 200.0, 401.0)); + assert!(!t.claims_key(&c, ToolKey::Delete), "nothing is left to delete"); + assert_eq!(t.key(&c, ToolKey::Delete, Mods::default()), vec![]); + + t.pointer(&c, &PointerEvent::new(PointerKind::Move, 200.0, 401.0)); + assert_eq!(t.cursor(&c, Point::new(200.0, 401.0), Mods::default()), Cursor::Width); + t.pointer(&c, &PointerEvent::new(PointerKind::Move, 220.0, 201.0)); + assert_eq!(t.cursor(&c, Point::new(220.0, 201.0), Mods::default()), Cursor::WidthAdd, "the plain stroke still offers one"); + } + #[test] fn alt_drag_changes_one_side_and_move_slides() { let (mut d, id) = doc_line(); diff --git a/crates/tools/src/input.rs b/crates/tools/src/input.rs index 5362147b97..629970b066 100644 --- a/crates/tools/src/input.rs +++ b/crates/tools/src/input.rs @@ -218,4 +218,8 @@ pub enum Action { SwitchTool(String), /// Call the tool's `notify` after the preceding actions ran (e.g. to pick up a created object). Notify(String), + /// Show this English message in the status bar (e.g. why a Shape Builder gesture built + /// nothing); an empty message clears the status bar. It changes nothing in the document and + /// records no undo step. + Status(String), } diff --git a/crates/ui-egui/src/chrome/control_bar.rs b/crates/ui-egui/src/chrome/control_bar.rs index 71b737dbfc..f73a39a269 100644 --- a/crates/ui-egui/src/chrome/control_bar.rs +++ b/crates/ui-egui/src/chrome/control_bar.rs @@ -710,7 +710,7 @@ fn fill_and_stroke(app: &mut VectorcraftApp, ui: &mut Ui, reserve: f32) { stroke_panel::weight_field(app, ui, "cb-stroke", weight, WEIGHT_FIELD_WIDTH); if ui.available_width() < row_width(ui, &[stroke_panel::PROFILE_DROPDOWN_WIDTH]) + reserve { left_out(ui); - } else if let Some(id) = stroke_panel::profile_dropdown(app, ui, shown_stroke.as_ref().and_then(|s| s.profile.as_ref())) { + } else if let Some(id) = stroke_panel::profile_dropdown(app, ui, shown_stroke.as_ref()) { app.run("stroke.set", json!({"profile": id})).ok(); } } else { diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index bb039bb08e..3321a9b9d7 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -4045,6 +4045,8 @@ digits Malayalam Малаялам V Spacing: В. разстояние: V: В: Variable Width Profile Профил с променлива ширина + The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. Четката на щриха запазва собствения си размер, затова профилът на ширината не го променя. Премахнете четката, за да използвате профил. +@msg The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. Четката на щриха запазва собствения си размер, затова профилът на ширината не го променя. Премахнете четката, за да използвате профил. Variables Променливи New Variable Нова променлива Delete Variable Изтриване на променлива diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 99f23d313c..bda7d72d7d 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -2237,6 +2237,8 @@ digits Malayalam Malajalam Tip extends past the end point Vrh prelazi preko krajnje tačke Tip on the end point Vrh na krajnjoj tački Variable Width Profile Profil promjenjive širine + The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. Četkica poteza zadržava vlastitu veličinu, pa je profil širine ne mijenja. Uklonite četkicu da biste koristili profil. +@msg The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. Četkica poteza zadržava vlastitu veličinu, pa je profil širine ne mijenja. Uklonite četkicu da biste koristili profil. Weight: Debljina: Art using a deleted global swatch keeps its colour. Crtež koji koristi izbrisani globalni uzorak boje zadržava svoju boju. Color Group: {name} Grupa boja: {name} diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index c54311799d..3870e51a82 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -5303,6 +5303,8 @@ digits Malayalam Malaiàlam Variable Options Opcions de variable Variable Options… Opcions de variable… Variable Width Profile Perfil d’amplada variable + The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. El pinzell del traç manté la seva pròpia mida, de manera que un perfil d’amplada no el canvia. Traieu el pinzell per fer servir un perfil. +@msg The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. El pinzell del traç manté la seva pròpia mida, de manera que un perfil d’amplada no el canvia. Traieu el pinzell per fer servir un perfil. Variables Variables Variation Variació Variation: Variació: diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index a5d7bb948a..b1956d0b6c 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -2310,6 +2310,8 @@ digits Malayalam Malajálamské Tip extends past the end point Hrot přesahuje koncový bod Tip on the end point Hrot na koncovém bodu Variable Width Profile Profil proměnné šířky + The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. Štětec tahu si zachovává vlastní velikost, takže ho profil šířky nemění. Chcete-li použít profil, odeberte štětec. +@msg The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. Štětec tahu si zachovává vlastní velikost, takže ho profil šířky nemění. Chcete-li použít profil, odeberte štětec. Weight: Tloušťka: Art using a deleted global swatch keeps its colour. Kresba, která používá odstraněnou globální položku vzorníku, si barvu ponechá. Color Group: {name} Skupina barev: {name} diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 08100f593f..d1bac3c370 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -4801,6 +4801,8 @@ digits Malayalam Malayalam Tip extends past the end point Spidsen rager ud over endepunktet Tip on the end point Spidsen på endepunktet Variable Width Profile Variabel breddeprofil + The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. Stregens pensel beholder sin egen størrelse, så et breddeprofil ændrer den ikke. Fjern penslen for at bruge et profil. +@msg The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. Stregens pensel beholder sin egen størrelse, så et breddeprofil ændrer den ikke. Fjern penslen for at bruge et profil. Weight: Vægt: Art using a deleted global swatch keeps its colour. Grafik, der bruger en slettet global farveprøve, bevarer sin farve. Color Group: {name} Farvegruppe: {name} diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 10147b2d45..36a0423689 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -4139,6 +4139,8 @@ effect Points Punkte V Spacing: V-Abstand: V: V: Variable Width Profile Variables Breitenprofil + The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. Der Pinsel der Kontur behält seine eigene Größe, daher ändert ein Breitenprofil die Kontur nicht. Entfernen Sie den Pinsel, um ein Profil zu verwenden. +@msg The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. Der Pinsel der Kontur behält seine eigene Größe, daher ändert ein Breitenprofil die Kontur nicht. Entfernen Sie den Pinsel, um ein Profil zu verwenden. Variables Variablen Variation: Variation: Vector Effects Vektoreffekte diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 1ebf6e5684..9f4974d355 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -4672,6 +4672,8 @@ digits Malayalam Μαλαγιάλαμ V Spacing: Κατακόρυφη απόσταση: V: Κατακόρυφα: Variable Width Profile Προφίλ μεταβλητού πλάτους + The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. Το πινέλο του περιγράμματος διατηρεί το δικό του μέγεθος, οπότε ένα προφίλ πλάτους δεν το αλλάζει. Αφαιρέστε το πινέλο για να χρησιμοποιήσετε προφίλ. +@msg The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. Το πινέλο του περιγράμματος διατηρεί το δικό του μέγεθος, οπότε ένα προφίλ πλάτους δεν το αλλάζει. Αφαιρέστε το πινέλο για να χρησιμοποιήσετε προφίλ. New Variable Νέα μεταβλητή Delete Variable Διαγραφή μεταβλητής Lock Variables Κλείδωμα μεταβλητών diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index a456910a16..f00b32d379 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -4190,6 +4190,8 @@ digits Malayalam Malayálam V Spacing: Espaciado V: V: V: Variable Width Profile Perfil de anchura variable + The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. El pincel del trazo mantiene su propio tamaño, así que un perfil de anchura no lo cambia. Quite el pincel para usar un perfil. +@msg The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. El pincel del trazo mantiene su propio tamaño, así que un perfil de anchura no lo cambia. Quite el pincel para usar un perfil. Variables Variables New Variable Nueva variable Delete Variable Eliminar variable diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index bff46fc0d7..acbe85c0e5 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -2271,6 +2271,8 @@ digits Malayalam Malajalam Tip extends past the end point Kärki ulottuu päätepisteen yli Tip on the end point Kärki päätepisteessä Variable Width Profile Muuttuvan leveyden profiili + The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. Viivan sivellin säilyttää oman kokonsa, joten leveysprofiili ei muuta sitä. Poista sivellin, jos haluat käyttää profiilia. +@msg The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. Viivan sivellin säilyttää oman kokonsa, joten leveysprofiili ei muuta sitä. Poista sivellin, jos haluat käyttää profiilia. Weight: Paksuus: Art using a deleted global swatch keeps its colour. Poistettua globaalia värimallia käyttävä kuvitus säilyttää värinsä. Color Group: {name} Väriryhmä: {name} diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 3be3497f97..229fbd9901 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -4177,6 +4177,8 @@ digits Malayalam Malayalam V Spacing: Espacement V : V: V : Variable Width Profile Profil de largeur variable + The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. La forme du contour garde sa propre taille, donc un profil de largeur ne la modifie pas. Supprimez la forme pour utiliser un profil. +@msg The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. La forme du contour garde sa propre taille, donc un profil de largeur ne la modifie pas. Supprimez la forme pour utiliser un profil. Variables Variables New Variable Nouvelle variable Delete Variable Supprimer la variable diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index c427fc527c..1464a51892 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -4320,6 +4320,8 @@ Variable Font વેરિએબલ ફૉન્ટ Variable Options… વેરિએબલ વિકલ્પો… Variable Width Profile વેરિએબલ પહોળાઈ પ્રોફાઇલ + The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. સ્ટ્રોકનું બ્રશ પોતાનું કદ જાળવે છે, તેથી પહોળાઈ પ્રોફાઇલ તેને બદલતી નથી. પ્રોફાઇલ વાપરવા માટે બ્રશ દૂર કરો. +@msg The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. સ્ટ્રોકનું બ્રશ પોતાનું કદ જાળવે છે, તેથી પહોળાઈ પ્રોફાઇલ તેને બદલતી નથી. પ્રોફાઇલ વાપરવા માટે બ્રશ દૂર કરો. Variables વેરિએબલ્સ Variation: વેરિએશન: Vector Effects વેક્ટર અસરો diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index cbfb4f51d1..09119c407f 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -5722,6 +5722,8 @@ antiAlias Sharp शार्प Variable Options वेरिएबल ऑप्शन्स Variable Options… वेरिएबल ऑप्शन्स… Variable Width Profile वेरिएबल चौड़ाई प्रोफ़ाइल + The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. स्ट्रोक का ब्रश अपना आकार बनाए रखता है, इसलिए चौड़ाई प्रोफ़ाइल उसे नहीं बदलती। प्रोफ़ाइल का उपयोग करने के लिए ब्रश निकालें। +@msg The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. स्ट्रोक का ब्रश अपना आकार बनाए रखता है, इसलिए चौड़ाई प्रोफ़ाइल उसे नहीं बदलती। प्रोफ़ाइल का उपयोग करने के लिए ब्रश निकालें। Variables वेरिएबल्स Variation वैरिएशन Variation: भिन्नता: diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 0f81a72036..1024d5a1a9 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -4940,6 +4940,8 @@ mark-style Japanese Japán Variable Options Változó beállításai Variable Options… Változó beállításai… Variable Width Profile Változó szélességprofil + The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. A körvonal ecsetje megtartja a saját méretét, ezért a szélességprofil nem változtatja meg. Profil használatához távolítsa el az ecsetet. +@msg The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. A körvonal ecsetje megtartja a saját méretét, ezért a szélességprofil nem változtatja meg. Profil használatához távolítsa el az ecsetet. Variables Változók Variation Ingadozás Variation: Ingadozás: diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 28ea2b5ab3..b9b39831e0 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -2060,6 +2060,8 @@ digits Malayalam Malayalam Tip extends past the end point Ujung melewati titik akhir Tip on the end point Ujung pada titik akhir Variable Width Profile Profil lebar variabel + The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. Kuas pada guratan mempertahankan ukurannya sendiri, sehingga profil lebar tidak mengubahnya. Hapus kuas untuk menggunakan profil. +@msg The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. Kuas pada guratan mempertahankan ukurannya sendiri, sehingga profil lebar tidak mengubahnya. Hapus kuas untuk menggunakan profil. Weight: Ketebalan: Art using a deleted global swatch keeps its colour. Karya seni yang memakai swatch global terhapus tetap mempertahankan warnanya. Color Group: {name} Grup warna: {name} diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 8f2ed3216c..deebb1e5ed 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -4239,6 +4239,8 @@ digits Malayalam Malayalam V Spacing: Spaziatura verticale: V: V: Variable Width Profile Profilo larghezza variabile + The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. Il pennello della traccia mantiene la propria dimensione, quindi un profilo di larghezza non la modifica. Rimuovi il pennello per usare un profilo. +@msg The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. Il pennello della traccia mantiene la propria dimensione, quindi un profilo di larghezza non la modifica. Rimuovi il pennello per usare un profilo. Variables Variabili New Variable Nuova variabile Delete Variable Elimina variabile diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index c429f204a1..f04be71521 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -3783,6 +3783,8 @@ mark-style Japanese 日本式 User Swatch Library 9 ユーザースウォッチライブラリ 9 V Spacing: 垂直方向の間隔: Variable Width Profile 可変幅プロファイル + The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. 線のブラシは独自のサイズを保つため、幅プロファイルでは変わりません。プロファイルを使うにはブラシを削除してください。 +@msg The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. 線のブラシは独自のサイズを保つため、幅プロファイルでは変わりません。プロファイルを使うにはブラシを削除してください。 Variation: バリエーション: Vector Halftone ベクトルハーフトーン Vector illustration — fast, open, scriptable. ベクターイラスト — 高速・オープン・スクリプト対応 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 414f45171c..1f5bcbaf4f 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -4229,6 +4229,8 @@ digits Malayalam მალაიალამური Tip extends past the end point წვერი ბოლო წერტილს სცდება Tip on the end point წვერი ბოლო წერტილზე Variable Width Profile ცვლადი სიგანის პროფილი + The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. კონტურის ფუნჯი საკუთარ ზომას ინარჩუნებს, ამიტომ სიგანის პროფილი მას არ ცვლის. პროფილის გამოსაყენებლად მოხსენით ფუნჯი. +@msg The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. კონტურის ფუნჯი საკუთარ ზომას ინარჩუნებს, ამიტომ სიგანის პროფილი მას არ ცვლის. პროფილის გამოსაყენებლად მოხსენით ფუნჯი. Weight: სისქე: Art using a deleted global swatch keeps its colour. წაშლილი გლობალური ფერის ნიმუშის მქონე ნახატი თავის ფერს ინარჩუნებს. Color Group: {name} ფერთა ჯგუფი: {name} diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index dbda53243f..8635287711 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -3772,6 +3772,8 @@ mark-style Japanese 일본식 User Swatch Library 9 사용자 견본 라이브러리 9 V Spacing: 세로 간격: Variable Width Profile 가변 너비 프로파일 + The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. 선의 브러시는 고유한 크기를 유지하므로 너비 프로파일로 바뀌지 않습니다. 프로파일을 사용하려면 브러시를 제거하세요. +@msg The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. 선의 브러시는 고유한 크기를 유지하므로 너비 프로파일로 바뀌지 않습니다. 프로파일을 사용하려면 브러시를 제거하세요. Variation: 변형: Vector Halftone 벡터 하프톤 Vector illustration — fast, open, scriptable. 벡터 일러스트레이션 — 빠르고 개방적이며 스크립트 지원. diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 69aef91cfc..880c7fd1fe 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -2675,6 +2675,8 @@ digits Malayalam Malayalam Tip extends past the end point Punt steekt uit voorbij het eindpunt Tip on the end point Punt op het eindpunt Variable Width Profile Variabel breedteprofiel + The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. Het penseel van de contour behoudt zijn eigen grootte, dus een breedteprofiel verandert de contour niet. Verwijder het penseel om een profiel te gebruiken. +@msg The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. Het penseel van de contour behoudt zijn eigen grootte, dus een breedteprofiel verandert de contour niet. Verwijder het penseel om een profiel te gebruiken. Weight: Dikte: Art using a deleted global swatch keeps its colour. Artwork met een verwijderd globaal staal behoudt zijn kleur. Color Group: {name} Kleurgroep: {name} diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 0147515ffe..92348fce2a 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -2228,6 +2228,8 @@ digits Malayalam Malajalam Tip extends past the end point Czubek wystaje poza punkt końcowy Tip on the end point Czubek na punkcie końcowym Variable Width Profile Profil zmiennej szerokości + The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. Pędzel obrysu zachowuje własny rozmiar, więc profil szerokości go nie zmienia. Usuń pędzel, aby użyć profilu. +@msg The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. Pędzel obrysu zachowuje własny rozmiar, więc profil szerokości go nie zmienia. Usuń pędzel, aby użyć profilu. Weight: Grubość: Art using a deleted global swatch keeps its colour. Kompozycja używająca usuniętej próbki globalnej zachowa swój kolor. Color Group: {name} Grupa kolorów: {name} diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 8201db7ab6..66461106ce 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -3426,6 +3426,8 @@ digits Malayalam Malaiala V Spacing: Espaçamento V: V: V: Variable Width Profile Perfil de Largura Variável + The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. O pincel do traçado mantém o próprio tamanho, então um perfil de largura não o altera. Remova o pincel para usar um perfil. +@msg The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. O pincel do traçado mantém o próprio tamanho, então um perfil de largura não o altera. Remova o pincel para usar um perfil. Variables Variáveis New Variable… Nova variável… Unbind Variable Desassociar variável diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index d1593508d3..014f2e9b9e 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -4222,6 +4222,8 @@ digits Malayalam Малаялам V Spacing: Интервал по вертикали: V: В: Variable Width Profile Профиль переменной ширины + The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. Кисть обводки сохраняет собственный размер, поэтому профиль ширины её не меняет. Чтобы использовать профиль, уберите кисть. +@msg The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. Кисть обводки сохраняет собственный размер, поэтому профиль ширины её не меняет. Чтобы использовать профиль, уберите кисть. Variables Переменные New Variable Новая переменная Delete Variable Удалить переменную diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 5c0420fcd3..949fd0f502 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -4107,6 +4107,8 @@ digits Malayalam Malayalam V Spacing: V-avstånd: V: V: Variable Width Profile Profil för variabel bredd + The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. Konturens pensel behåller sin egen storlek, så en breddprofil ändrar inte konturen. Ta bort penseln för att använda en profil. +@msg The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. Konturens pensel behåller sin egen storlek, så en breddprofil ändrar inte konturen. Ta bort penseln för att använda en profil. Variables Variabler New Variable Ny variabel Delete Variable Radera variabel diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 910a7fc5b1..1d20b5d72a 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -3961,6 +3961,8 @@ digits Malayalam Malayalam V Spacing: V Aralığı: V: V: Variable Width Profile Değişken Genişlik Profili + The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. Konturun fırçası kendi boyutunu korur, bu yüzden genişlik profili konturu değiştirmez. Profil kullanmak için fırçayı kaldırın. +@msg The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. Konturun fırçası kendi boyutunu korur, bu yüzden genişlik profili konturu değiştirmez. Profil kullanmak için fırçayı kaldırın. Variables Değişkenler New Variable Yeni Değişken Delete Variable Değişkeni Sil diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index dbd6d2609e..b5ce19eab1 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -4232,6 +4232,8 @@ effect Points Точки V Spacing: Інтервал по вертикалі: V: В: Variable Width Profile Профіль змінної ширини + The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. Пензель обведення зберігає власний розмір, тому профіль ширини його не змінює. Щоб використати профіль, заберіть пензель. +@msg The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. Пензель обведення зберігає власний розмір, тому профіль ширини його не змінює. Щоб використати профіль, заберіть пензель. Variables Змінні New Variable Нова змінна Delete Variable Видалити змінну diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 519c5d8f0d..989fa6c393 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -4641,6 +4641,8 @@ mark-style Japanese Kiểu Nhật Variable Options Tùy chọn biến Variable Options… Tùy chọn biến số… Variable Width Profile Hồ sơ chiều rộng biến đổi + The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. Cọ của nét giữ kích thước riêng, nên hồ sơ chiều rộng không thay đổi nét. Gỡ cọ để dùng hồ sơ. +@msg The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. Cọ của nét giữ kích thước riêng, nên hồ sơ chiều rộng không thay đổi nét. Gỡ cọ để dùng hồ sơ. Variables Biến số Variation: Biến thể: Vector Effects Hiệu ứng vector diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index c6696a9ec6..34636b6f63 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -4061,6 +4061,8 @@ digits Malayalam 马拉雅拉姆数字 V Spacing: 垂直间距: V: V: Variable Width Profile 变量宽度配置文件 + The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. 描边的画笔保持其自身大小,因此宽度配置文件不会改变它。移除画笔即可使用配置文件。 +@msg The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. 描边的画笔保持其自身大小,因此宽度配置文件不会改变它。移除画笔即可使用配置文件。 Variables 变量 New Variable 新建变量 Delete Variable 删除变量 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 1480422931..f1fa194422 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -5385,6 +5385,8 @@ digits Malayalam 馬來亞拉姆數字 V Spacing: 垂直間距: V: V: Variable Width Profile 可變寬度描述檔 + The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. 筆畫的筆刷會保持自身大小,因此寬度描述檔不會改變它。移除筆刷即可使用描述檔。 +@msg The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile. 筆畫的筆刷會保持自身大小,因此寬度描述檔不會改變它。移除筆刷即可使用描述檔。 Variables 變數 New Variable 新增變數 Delete Variable 刪除變數 diff --git a/crates/ui-egui/src/panels/properties.rs b/crates/ui-egui/src/panels/properties.rs index 5dede1697b..05db9d9cfd 100644 --- a/crates/ui-egui/src/panels/properties.rs +++ b/crates/ui-egui/src/panels/properties.rs @@ -985,7 +985,7 @@ fn width_profile_row(app: &mut VectorcraftApp, ui: &mut Ui) { } ui.horizontal(|ui| { dim_label(ui, tl!("Profile:")); - if let Some(id) = super::stroke::profile_dropdown(app, ui, profile) { + if let Some(id) = super::stroke::profile_dropdown(app, ui, stroke.as_ref()) { app.run("stroke.set", json!({"profile": id})).ok(); } }); diff --git a/crates/ui-egui/src/panels/properties/tests.rs b/crates/ui-egui/src/panels/properties/tests.rs index c91d01a2bf..613eb73793 100644 --- a/crates/ui-egui/src/panels/properties/tests.rs +++ b/crates/ui-egui/src/panels/properties/tests.rs @@ -1515,6 +1515,26 @@ fn the_width_profile_shows_for_a_variable_width_or_the_width_tool() { assert_eq!(WidthProfile::id_of(profile.as_ref()), "taperStart"); } +/// A brushed stroke with a variable width: the Width Profile list lists only Uniform, which removes +/// the profile. +#[test] +fn the_width_profile_of_a_brushed_stroke_offers_only_uniform() { + let mut app = new_app(); + let line = app.run("shape.line", json!({"x1": 20, "y1": 100, "x2": 300, "y2": 100})).unwrap()["id"].clone(); + app.run("select.set", json!({"ids": [line]})).unwrap(); + app.run("stroke.set", json!({"profile": "lens"})).unwrap(); + app.run("brush.apply", json!({"ids": [line], "name": "3 pt. Round"})).unwrap(); + let ctx = egui::Context::default(); + let texts = tall(&mut app, &ctx, vec![]); + let spacing = ctx.global_style().spacing.item_spacing.x; + let texts = press(&mut app, &ctx, text_at(&texts, "Profile:").right_center() + vec2(spacing + 50.0, 0.0)); + assert!(!shows(&texts, "Taper Start"), "{texts:?}"); + press(&mut app, &ctx, text_at(&texts, "Uniform").center()); + let profile = + app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(line.as_u64().unwrap())).unwrap().appearance.stroke().unwrap().profile.clone(); + assert_eq!(profile, None); +} + /// With Direct Selection, a path whose corner is selected shows that corner's kind and radius; /// each edit sets that corner alone in one undo step. Not with the Selection tool, nor with the /// whole path selected; a live rectangle keeps its own Corner Radius row instead. diff --git a/crates/ui-egui/src/panels/stroke.rs b/crates/ui-egui/src/panels/stroke.rs index c667f01200..25c32db77e 100644 --- a/crates/ui-egui/src/panels/stroke.rs +++ b/crates/ui-egui/src/panels/stroke.rs @@ -355,10 +355,10 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { // Profile. ui.horizontal(|ui| { row_label(ui, tl!("Profile:")); - if let Some(id) = profile_dropdown(app, ui, st.as_ref().and_then(|s| s.profile.as_ref())) { + if let Some(id) = profile_dropdown(app, ui, st.as_ref()) { set(app, json!({"profile": id})); } - let can_flip = st.as_ref().is_some_and(|s| s.profile.is_some()); + let can_flip = st.as_ref().is_some_and(|s| s.profile.is_some()) && brush_keeps_size(app, ui.ctx(), st.as_ref()).is_none(); // Lucide names these icons for their mirror line: the vertical-line icon flips the // profile along the path, while the horizontal-line icon flips it across the path. if widgets::icon_button_enabled(ui, "flip-vertical-2", tl!("Flip Along"), false, can_flip, 22.0).clicked() { @@ -498,24 +498,66 @@ pub fn paint_profile(ui: &Ui, r: Rect, points: Option<&[(f64, f64, f64)]>, color /// The width of the [`profile_dropdown`] button. pub(crate) const PROFILE_DROPDOWN_WIDTH: f32 = 100.0; -/// The Profile dropdown (Stroke panel, Control bar): the stroke's own silhouette on the button -/// (a custom profile too), the built-in profiles and then the saved ones in the list. Returns the -/// id or name picked. -pub(crate) fn profile_dropdown(app: &VectorcraftApp, ui: &mut Ui, cur: Option<&WidthProfile>) -> Option<String> { +/// While a width profile changes none of the strokes the Profile list edits, because each draws +/// with a brush: whether any of them has a profile. None while a profile changes one of them. +/// With nothing selected the list sets up the next object drawn, whose stroke is `shown` (the +/// stroke the panels show). Otherwise it edits the strokes `stroke.set` targets +/// ([`vectorcraft_engine::Session::brushed_strokes_profiled`], cached per document revision and +/// active Appearance row), such as a selected group's own stroke while `shown` is its first +/// member's. +pub(crate) fn brush_keeps_size(app: &VectorcraftApp, ctx: &egui::Context, shown: Option<&StrokeLayer>) -> Option<bool> { + let st = app.session.active()?; + if st.selection.objects.is_empty() && st.selection.subjects().is_empty() { + let s = shown?; + let name = s.brush.as_deref()?; + return super::brushes::document_brushes(st).iter().any(|b| b.name == name).then_some(s.profile.is_some()); + } + let key = (st.uid, st.revision, app.session.appearance_item()); + match pstate::<Option<((u64, u64, Option<usize>), Option<bool>)>>(ctx, "stroke-brushed") { + Some((k, v)) if k == key => v, + _ => { + let v = app.session.brushed_strokes_profiled(); + set_pstate(ctx, "stroke-brushed", Some((key, v))); + v + } + } +} + +/// The Profile dropdown (Stroke panel, Properties panel, Control bar): the stroke's own silhouette +/// on the button (a custom profile too), the built-in profiles and then the saved ones in the list. +/// Returns the id or name picked. While the strokes draw with a brush ([`brush_keeps_size`]), the +/// button is dimmed and says why when hovered; it opens no list while every one is uniform, and +/// only the Uniform row, which removes the profiles, while one has a profile. +pub(crate) fn profile_dropdown(app: &VectorcraftApp, ui: &mut Ui, shown: Option<&StrokeLayer>) -> Option<String> { let t = Tokens::get(ui.ctx()); - let (r, resp) = ui.allocate_exact_size(vec2(PROFILE_DROPDOWN_WIDTH, 24.0), Sense::click()); + let cur = shown.and_then(|s| s.profile.as_ref()); + let brushed = brush_keeps_size(app, ui.ctx(), shown); + let keeps_size = brushed.is_some(); + let uniform = brushed == Some(false); + let sense = if uniform { Sense::hover() } else { Sense::click() }; + let (r, resp) = ui.allocate_exact_size(vec2(PROFILE_DROPDOWN_WIDTH, 24.0), sense); ui.painter().rect_filled(r, 2, t.input); - ui.painter().rect_stroke(r, 2, Stroke::new(1.0, if resp.hovered() { t.text } else { t.input_border }), StrokeKind::Inside); + let border = if resp.hovered() && !keeps_size { t.text } else { t.input_border }; + ui.painter().rect_stroke(r, 2, Stroke::new(1.0, border), StrokeKind::Inside); let body = Rect::from_min_max(r.min + vec2(6.0, 5.0), pos2(r.right() - 20.0, r.bottom() - 5.0)); - paint_profile(ui, body, cur.and_then(|p| silhouette(&p.points)), t.text_strong); - icons::paint(ui, "chevron-down", Rect::from_center_size(pos2(r.right() - 9.0, r.center().y), vec2(10.0, 10.0)), t.icon); - let resp = resp.on_hover_text(tl!("Variable Width Profile")); + let (shape, icon) = if keeps_size { (t.text_disabled, t.text_disabled) } else { (t.text_strong, t.icon) }; + paint_profile(ui, body, cur.and_then(|p| silhouette(&p.points)), shape); + icons::paint(ui, "chevron-down", Rect::from_center_size(pos2(r.right() - 9.0, r.center().y), vec2(10.0, 10.0)), icon); + let tip = if keeps_size { + tl!("The stroke's brush keeps its own size, so a width profile does not change it. Remove the brush to use a profile.") + } else { + tl!("Variable Width Profile") + }; + let resp = resp.on_hover_text(tip); + if uniform { + return None; + } let mut out = None; egui::Popup::menu(&resp).show(|ui| { egui::ScrollArea::vertical().max_height(360.0).show(ui, |ui| { // A divider between the built-in profiles and the saved ones. let mut divide = true; - for e in app.session.profile_entries() { + for e in app.session.profile_entries().filter(|e| !keeps_size || e.matches(None)) { if !e.built_in && std::mem::take(&mut divide) { ui.separator(); } diff --git a/crates/ui-egui/src/panels/tests_strokedepth.rs b/crates/ui-egui/src/panels/tests_strokedepth.rs index 1d80cc1c66..aa4dfb9fa1 100644 --- a/crates/ui-egui/src/panels/tests_strokedepth.rs +++ b/crates/ui-egui/src/panels/tests_strokedepth.rs @@ -1,5 +1,6 @@ //! Headless frames of the Stroke panel's width profile library: the ≡ menu's Add to Profiles…, -//! Delete Profile and Reset Profiles, and the Profile dropdown listing saved profiles. +//! Delete Profile and Reset Profiles, and the Profile dropdown listing saved profiles and dimmed +//! while the strokes draw with a brush. use serde_json::json; use vectorcraft_doc::WidthProfile; @@ -88,6 +89,198 @@ fn dropdown_lists_saved_profiles_and_applies_them() { assert_eq!(profile_points(&app), Some(custom().points)); } +/// The Stroke panel's Profile dropdown button, right of the "Profile:" label. +fn profile_button(ctx: &egui::Context, app: &mut VectorcraftApp) -> egui::Pos2 { + let t = frame_events(ctx, app, vec![], stroke::show); + let label = text_rect(&t, "Profile:"); + egui::pos2(label.right() + ctx.global_style().spacing.item_spacing.x + 50.0, label.center().y) +} + +/// Is the Profile dropdown dimmed for the stroke the panels show? +fn dimmed(ctx: &egui::Context, app: &VectorcraftApp) -> bool { + stroke::brush_keeps_size(app, ctx, current_stroke(app).as_ref()).is_some() +} + +/// The rows the Profile dropdown lists after a click on it. +fn listed(ctx: &egui::Context, app: &mut VectorcraftApp) -> Vec<&'static str> { + let button = profile_button(ctx, app); + click(ctx, app, button, stroke::show); + let t = frame_events(ctx, app, vec![], stroke::show); + let out = WidthProfile::PRESETS.iter().map(|p| p.label).filter(|l| t.iter().any(|(s, _)| s == l)).collect(); + // Close the list. + let escape = egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }; + frame_events(ctx, app, vec![escape], stroke::show); + out +} + +/// A stroke drawn with a brush (here the 3 pt. Round calligraphic brush) keeps the brush's size, +/// so a width profile does not change it: the Profile dropdown is dimmed, opens no list on a +/// uniform stroke, and lists only Uniform on a stroke that has a profile (which resets it). +/// Without the brush, the full list comes back. +#[test] +fn dropdown_is_dimmed_while_the_brush_keeps_its_size() { + let ctx = egui::Context::default(); + let mut app = app_with_line(); + let id = app.session.active().unwrap().selection.objects[0].0; + run(&mut app, "brush.apply", json!({"ids": [id], "name": "3 pt. Round"})); + assert!(dimmed(&ctx, &app)); + assert_eq!(listed(&ctx, &mut app), Vec::<&str>::new(), "no list on a uniform stroke"); + + set_profile(&mut app, custom()); + assert_eq!(listed(&ctx, &mut app), ["Uniform"]); + let button = profile_button(&ctx, &mut app); + click(&ctx, &mut app, button, stroke::show); + let t = frame_events(&ctx, &mut app, vec![], stroke::show); + click(&ctx, &mut app, text_rect(&t, "Uniform").center(), stroke::show); + assert_eq!(profile_points(&app), None, "Uniform resets the profile"); + + run(&mut app, "brush.remove", json!({"ids": [id]})); + assert!(!dimmed(&ctx, &app)); + assert_eq!(listed(&ctx, &mut app).len(), WidthProfile::PRESETS.len()); +} + +/// With an Appearance panel stroke row active, the dropdown follows that row: a brushed row below +/// a plain top stroke dims it, and the plain row does not. +#[test] +fn the_active_stroke_row_decides_whether_the_dropdown_is_dimmed() { + let ctx = egui::Context::default(); + let mut app = app_with_line(); + let id = app.session.active().unwrap().selection.objects[0].0; + run(&mut app, "brush.apply", json!({"ids": [id], "name": "3 pt. Round"})); + run(&mut app, "appearance.addStroke", json!({})); + let items = app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().appearance.items.clone(); + let rows: Vec<(usize, bool)> = items + .iter() + .enumerate() + .filter_map(|(i, it)| if let vectorcraft_doc::AppearanceItem::Stroke(s) = it { Some((i, s.brush.is_some())) } else { None }) + .collect(); + let [(lower, true), (top, false)] = rows[..] else { panic!("{rows:?}") }; + assert!(!dimmed(&ctx, &app), "the top stroke has no brush"); + run(&mut app, "appearance.setActiveItem", json!({"index": lower})); + assert!(dimmed(&ctx, &app)); + assert_eq!(listed(&ctx, &mut app), Vec::<&str>::new()); + run(&mut app, "appearance.setActiveItem", json!({"index": top})); + assert!(!dimmed(&ctx, &app)); +} + +/// A selected group with a brushed stroke of its own dims the dropdown, though the panel shows its +/// first member's plain stroke: the list edits the group's stroke. +#[test] +fn a_groups_own_brushed_stroke_dims_the_dropdown() { + let ctx = egui::Context::default(); + let mut app = app_with_line(); + let a = app.session.active().unwrap().selection.objects[0].0; + run(&mut app, "shape.line", json!({"x1": 10, "y1": 150, "x2": 150, "y2": 150})); + let b = app.session.active().unwrap().selection.objects[0].0; + let g = run(&mut app, "object.group", json!({"ids": [a, b]}))["id"].as_u64().unwrap(); + run(&mut app, "appearance.addStroke", json!({"ids": [g]})); + app.session + .edit("Brush", |d, _| { + d.node_mut(vectorcraft_doc::NodeId(g)).unwrap().appearance.stroke_mut().unwrap().brush = Some("3 pt. Round".into()); + Ok(()) + }) + .unwrap(); + run(&mut app, "select.set", json!({"ids": [g]})); + assert!(current_stroke(&app).is_some_and(|s| s.brush.is_none()), "the panel shows a member's plain stroke"); + assert!(dimmed(&ctx, &app)); + assert_eq!(listed(&ctx, &mut app), Vec::<&str>::new()); +} + +/// A selection change with no edit between decides whether the dropdown is dimmed: from a brushed +/// line to a plain one and back. +#[test] +fn selecting_another_object_without_an_edit_updates_the_dimming() { + let ctx = egui::Context::default(); + let mut app = app_with_line(); + let a = app.session.active().unwrap().selection.objects[0].0; + run(&mut app, "shape.line", json!({"x1": 10, "y1": 150, "x2": 150, "y2": 150})); + let b = app.session.active().unwrap().selection.objects[0].0; + run(&mut app, "brush.apply", json!({"ids": [a], "name": "3 pt. Round"})); + run(&mut app, "select.set", json!({"ids": [a]})); + assert!(dimmed(&ctx, &app)); + run(&mut app, "select.set", json!({"ids": [b]})); + assert!(!dimmed(&ctx, &app), "the plain line follows a profile"); + run(&mut app, "select.set", json!({"ids": [a]})); + assert!(dimmed(&ctx, &app)); +} + +/// The Flip Along and Flip Across buttons beside a dimmed dropdown do not flip a brushed stroke's +/// profile, which does not change what the stroke draws. +#[test] +fn flip_buttons_leave_a_brushed_strokes_profile_alone() { + let ctx = egui::Context::default(); + let mut app = app_with_line(); + set_profile(&mut app, custom()); + let spacing = ctx.global_style().spacing.item_spacing.x; + // The dropdown is 100 pt wide and the Flip Along button, 22 pt wide, follows it. + let flip = |ctx: &egui::Context, app: &mut VectorcraftApp| { + let button = profile_button(ctx, app); + let at = egui::pos2(button.x + stroke::PROFILE_DROPDOWN_WIDTH / 2.0 + spacing + 11.0, button.y); + click(ctx, app, at, stroke::show); + }; + flip(&ctx, &mut app); + let flipped = profile_points(&app); + assert_ne!(flipped, Some(custom().points), "Flip Along flips a plain stroke's profile"); + let id = app.session.active().unwrap().selection.objects[0].0; + run(&mut app, "brush.apply", json!({"ids": [id], "name": "3 pt. Round"})); + assert!(dimmed(&ctx, &app)); + let before = profile_points(&app); + assert!(before.is_some()); + flip(&ctx, &mut app); + assert_eq!(profile_points(&app), before, "the buttons are off on a brushed stroke"); +} + +/// With several objects selected, the dropdown is dimmed only while every one of their strokes +/// draws with a brush: a profile still changes the strokes without one. A brush name the +/// document's brushes lack draws a plain stroke, which follows the profile. +#[test] +fn mixed_selection_dims_the_dropdown_only_when_every_stroke_has_a_brush() { + let ctx = egui::Context::default(); + let mut app = app_with_line(); + let a = app.session.active().unwrap().selection.objects[0].0; + run(&mut app, "shape.line", json!({"x1": 10, "y1": 150, "x2": 150, "y2": 150})); + let b = app.session.active().unwrap().selection.objects[0].0; + run(&mut app, "brush.apply", json!({"ids": [a], "name": "3 pt. Round"})); + // The first selected object is the brushed one, whose stroke the panel shows. + run(&mut app, "select.set", json!({"ids": [a, b]})); + assert!(current_stroke(&app).and_then(|s| s.brush).is_some()); + assert!(!dimmed(&ctx, &app)); + assert_eq!(listed(&ctx, &mut app).len(), WidthProfile::PRESETS.len()); + + run(&mut app, "brush.apply", json!({"ids": [b], "name": "3 pt. Round"})); + run(&mut app, "select.set", json!({"ids": [a, b]})); + assert!(dimmed(&ctx, &app)); + assert_eq!(listed(&ctx, &mut app), Vec::<&str>::new()); + + // The shown stroke is uniform and the other has a profile: Uniform still removes it. + let edit = |app: &mut VectorcraftApp, f: &dyn Fn(&mut vectorcraft_doc::Appearance)| { + app.session + .edit("Edit", |d, _| { + f(&mut d.node_mut(vectorcraft_doc::NodeId(b)).unwrap().appearance); + Ok(()) + }) + .unwrap(); + }; + edit(&mut app, &|ap| ap.stroke_mut().unwrap().profile = Some(custom())); + assert_eq!(current_stroke(&app).and_then(|s| s.profile), None); + assert_eq!(listed(&ctx, &mut app), ["Uniform"]); + let button = profile_button(&ctx, &mut app); + click(&ctx, &mut app, button, stroke::show); + let t = frame_events(&ctx, &mut app, vec![], stroke::show); + click(&ctx, &mut app, text_rect(&t, "Uniform").center(), stroke::show); + let node = |app: &VectorcraftApp| app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(b)).unwrap().clone(); + assert_eq!(node(&app).appearance.stroke().unwrap().profile, None, "Uniform reset the other stroke"); + + edit(&mut app, &|ap| ap.stroke_mut().unwrap().brush = Some("No Such Brush".into())); + assert!(!dimmed(&ctx, &app)); + + // An object without a stroke item takes a plain stroke from a profile. + edit(&mut app, &|ap| ap.items.retain(|i| !matches!(i, vectorcraft_doc::AppearanceItem::Stroke(_)))); + assert!(node(&app).appearance.stroke().is_none()); + assert!(!dimmed(&ctx, &app)); + assert_eq!(listed(&ctx, &mut app).len(), WidthProfile::PRESETS.len()); +} + #[test] fn every_arrowhead_preview_draws_its_head() { use vectorcraft_doc::Arrowhead; diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index eb8aae5389..046a1b2ffd 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -775,6 +775,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Width-point finite-arithmetic follow-up (G1/M3):** Adjoining adjustments avoid intermediate overflow; non-finite normalized or resulting factors are rejected before committing. Engine regressions in `tests/widthpoints.rs` cover finite extremes, small nonzero results, atomic rejection, Undo/Redo and native save/reopen. Historical focused validation on the `a3357121` integration observed 2 expected RED failures with 11 passing controls, then all 13 tests passing with the repair; none were ignored. All three added regressions passed in current full CI. A full CI retry on the five-unit combined source at `a0671777` passed all seven stages with 6,613 test outcomes on 2026-10-14. An earlier full-CI run on the identical source panicked in the randomized `ai_mutated_save_never_panics` test; the cause remains unresolved. This five-fix batch does not claim to repair that failure. Scores and hours unchanged. - **Width-point creation (G1):** double-click a stroked segment with the Width tool to open Width Point Edit using sampled side widths. OK creates the point and optionally adjusts adjoining widths in one undo step. Cancel or Delete discards a prospective point without changing the document or redo history. Command and pointer tests cover profiles, compound paths, adjoining adjustment, existing-point editing and Undo/Redo. Message-catalog checks and full CI passed; the original capture verifies opening and Cancel, and the dialog layout was reviewed (2026-10-13: 28 focused Width tests, all seven cargo xtask ci stages, and a headless opening/Cancel capture with original PNG review). [Variable-width strokes](https://helpx.adobe.com/illustrator/using/stroke-object.html). - **Escape deselects width points:** with the Width tool, Escape deselects the selected width points, on the key the reference app's [Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) page lists for deselecting a width point. The path, its widths and the undo history do not change. With no width point selected, Escape does what it does with the other tools, such as leaving isolation mode. +- **Width profiles on brushed strokes:** brush art does not follow a stroke's width profile, so while every stroke the list edits draws with a brush, the Profile list in the Stroke panel, the Properties panel and the Control bar is dimmed and says why when hovered (VectorCraft's own rule). It opens no list while every one of those strokes is uniform, and only Uniform, which removes the profiles, while one has a profile. The Flip Along and Flip Across buttons beside it are off. The strokes are the ones `stroke.set` edits: the active Appearance stroke row in each selected object that has an equal row and the top stroke in the others, else a selected group's or compound shape's own stroke, else the objects' strokes. Images and symbol instances, which take no stroke from the list, do not count. A selection where some of them have no brush, or an object has no stroke, keeps the full list. The Width tool adds, edits and deletes no width points on a brushed stroke, and a press on one, or Delete with its width points selected, says why in the status bar; without Shift the press deselects the width points of other strokes, and the cursor over a brushed stroke offers no edit. A plain stroke under a selected brushed one stays reachable, and width points selected before their stroke took a brush show no handles. Tests: `panels::tests_strokedepth::{dropdown_is_dimmed_while_the_brush_keeps_its_size, the_active_stroke_row_decides_whether_the_dropdown_is_dimmed, a_groups_own_brushed_stroke_dims_the_dropdown, selecting_another_object_without_an_edit_updates_the_dimming, flip_buttons_leave_a_brushed_strokes_profile_alone, mixed_selection_dims_the_dropdown_only_when_every_stroke_has_a_brush}`, `panels::properties::tests::the_width_profile_of_a_brushed_stroke_offers_only_uniform`, `tests::appearance::{brushed_strokes_profiled_reads_the_strokes_stroke_set_edits, brushed_strokes_profiled_reads_a_compound_shapes_own_stroke, brushed_strokes_profiled_reads_a_targeted_layers_active_stroke_row, brushed_strokes_profiled_leaves_out_symbol_instances, brushed_strokes_profiled_falls_back_to_the_top_stroke_where_the_active_row_has_no_match}`, `distort::width::tests::{brushed_stroke_is_left_alone_with_a_reason, delete_leaves_the_width_points_of_a_brushed_stroke, a_press_on_a_brushed_stroke_deselects_and_its_cursor_offers_no_edit, shift_on_a_brushed_stroke_keeps_the_selected_width_points, a_plain_stroke_under_a_selected_brushed_one_stays_reachable, a_brush_applied_under_a_still_pointer_takes_away_the_hover, a_brush_added_to_the_library_is_seen_at_the_next_revision}`. - **Smooth widths between width points (#5714):** a variable-width stroke changes width along a smooth curve from one width point to the next, where it used to run in a straight line and turn a corner at each point. The public description is that the path "gradually gets wider or narrower from one point to the next" in "a flowing, continuous curve", and that stacked points make a sharp break ([Peachpit, Expressive Strokes](https://www.peachpit.com/articles/article.aspx?p=2979069)); the exact curve is not documented, so each side follows a monotone cubic (Fritsch–Carlson): no kink at a point, flat where a point is wider or narrower than both neighbours, never past the points either side, points on one line kept on it. The outline samples straight runs between width points closely enough to follow the curve to the drawing tolerance (at most 64 samples per span and 4,096 per piece). Presets with a middle point (Lens, Pinch, Teardrop, Wave) look softer; two-point tapers are unchanged. Tests: `appearance::profile::tests::{widths_run_smoothly_through_width_points, widths_never_pass_the_points_either_side, a_step_ends_the_curve_on_each_side, widest_covers_every_width_along_the_profile}`, `stroke::width::tests::{a_straight_run_follows_the_curve_between_width_points, samples_between_width_points_are_capped}`. - **Stroke gradients where a variable-width stroke meets itself (#5960):** with a gradient along or across a stroke that has a width profile, where the stroke crosses itself the later part paints over the earlier one only where the two overlap, and a narrow part running close beside a wide one leaves its edge alone. Each slice of the gradient reaches as far as the stroke is wide where it sits (for a dashed stroke, as wide as it gets within the reach of a cap or dot, found in one pass along the path, so a densely flattened path costs no more per point), where it used to reach as far as the stroke is wide anywhere and paint a square of its colour over the wider part. Strokes without a profile are unchanged. Tests: `stroke::tests_gradient::a_narrow_pass_over_a_wide_one_paints_only_where_they_overlap`, `a_narrow_pass_beside_a_wide_one_leaves_its_edge_alone`, `a_densely_flattened_dashed_pass_beside_a_wide_one_leaves_its_edge_alone` and `widest_ahead_is_the_widest_within_the_window`, with the existing coverage tests (joins, caps, arrowheads, profiles, dashes, aligned strokes). - **Width strokes zoomed out (#995):** a stroke with a width profile keeps its shape while the view zooms out. The canvas keeps a hairline visible (at least half a device pixel); for a profiled stroke it is the profile's widest point that gets that minimum, not the weight, so a 1 pt stroke with a 6x width point is no longer drawn twice as thick at 25% zoom than at 100%. Plain strokes are unchanged. Test: `render::tests::widthzoom`. From 8f166584984e63def66ab3a7308c43b477f57865 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 17 Nov 2026 07:07:44 -0800 Subject: [PATCH 087/176] Fix #7906: a dialog that opens closes the Command Palette, flyouts and menus A dialog opened without a press in the window, such as a pick in the macOS menu bar, an automation command or a run that ends in a dialog, left the Command Palette open over it, and the palette's search field kept the keyboard focus. A tool group's flyout, the All Tools drawer and an open menu or popup also stayed open above the dialog's backdrop. The palette could also be opened over an open dialog from the macOS menu bar or by an automation command, and its field then took the keyboard focus from the dialog. In the pass a dialog, the About window, a file dialog, the update prompt or a progress window opens, the app now closes the palette, the flyout, the drawer and any open popup. A flyout, drawer or menu opened while a progress window is waiting to appear also closes when it appears. While such a window is open, the palette stays closed, and the widget that had the focus before the palette opened does not take it back under the window. A palette opened after the window closes stays open until the next window opens. --- crates/ui-egui/src/app.rs | 2 + crates/ui-egui/src/dialogs/modal.rs | 13 ++ crates/ui-egui/src/palette.rs | 194 +++++++++++++++++++++++++++- crates/ui-egui/src/panel_docking.rs | 34 +++++ docs/target-app-parity.md | 1 + 5 files changed, 239 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index e3d2a13d64..b2757ca2fc 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -628,6 +628,8 @@ impl VectorcraftApp { plugin_runs::show(self, &ctx); trace_runs::show(self, &ctx); opening::show(self, &ctx); + // After every window this pass may open, and before the palette's field takes the keyboard. + panel_docking::close_overlays_for_modal(self, &ctx); palette::show(self, &ctx); // After every panel had its chance to draw in this pass. crate::panels::three_d::end_stale_drag(self, &ctx); diff --git a/crates/ui-egui/src/dialogs/modal.rs b/crates/ui-egui/src/dialogs/modal.rs index f72383068e..c7bedbe2b1 100644 --- a/crates/ui-egui/src/dialogs/modal.rs +++ b/crates/ui-egui/src/dialogs/modal.rs @@ -25,6 +25,8 @@ pub(crate) fn show_at<R>(ctx: &egui::Context, title: &str, id: Id, initial: Vec2 // Not focusable (`Sense::click()` is): Tab goes through the dialog's controls, not the backdrop. ui.allocate_rect(ctx.content_rect(), egui::Sense::CLICK); }); + let pass = ctx.cumulative_pass_nr(); + ctx.data_mut(|d| d.insert_temp(drawn_pass_id(), pass)); let shown = egui::Window::new(title) .id(id) .order(egui::Order::Foreground) @@ -44,6 +46,17 @@ pub(crate) fn backdrop() -> egui::LayerId { egui::LayerId::new(egui::Order::Middle, Id::unique("modal-dim")) } +/// The key of the pass in which [`show_at`] last drew a modal window. +fn drawn_pass_id() -> Id { + Id::unique("modal-drawn-pass") +} + +/// Whether [`show_at`] drew a modal window in this pass. Unlike the backdrop's visibility, which +/// also counts the last pass, it is false in the pass after the window closes. +pub(crate) fn drawn_this_pass(ctx: &egui::Context) -> bool { + ctx.data(|d| d.get_temp::<u64>(drawn_pass_id())) == Some(ctx.cumulative_pass_nr()) +} + /// The dialog's heading, which also moves the window ([`drag_band`]). pub(crate) fn heading(ui: &mut egui::Ui, text: &str) { let t = Tokens::get(ui.ctx()); diff --git a/crates/ui-egui/src/palette.rs b/crates/ui-egui/src/palette.rs index 5c531019ce..74acb1bfb0 100644 --- a/crates/ui-egui/src/palette.rs +++ b/crates/ui-egui/src/palette.rs @@ -563,8 +563,9 @@ pub(crate) fn recent_list_open(ctx: &egui::Context) -> bool { pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { // The widget that had the keyboard focus when the palette opened takes it back when the palette - // closes, unless a pick opened a dialog, which focuses its own first field, or the press that - // closed it focused another widget, such as a field in a window above the backdrop. + // closes, unless a modal window is up (a pick opened a dialog, which focuses its own first + // field, or a window that opened closed the palette), or the press that closed it focused + // another widget, such as a field in a window above the backdrop. let focus_id = egui::Id::unique("palette-focus-before"); let field_id = egui::Id::unique("palette-field"); if !app.ui.palette_open { @@ -575,7 +576,7 @@ pub fn show(app: &mut VectorcraftApp, ctx: &egui::Context) { }); let now = ctx.memory(|m| m.focused()); if let Some(Some(before)) = ctx.data_mut(|d| d.remove_temp::<Option<egui::Id>>(focus_id)) - && app.ui.dialog.is_none() + && !crate::panel_docking::modal_window_up(app, ctx) && (now.is_none() || now == field) { ctx.memory_mut(|m| m.request_focus(before)); @@ -2292,6 +2293,38 @@ mod tests { assert!(labels(&nodes).contains(&footer(n, n)), "{:?}", labels(&nodes)); } + /// When a modal window that is not a dialog, such as the About window, closes the palette, the + /// widget under the window's backdrop does not get the keyboard focus back. + #[test] + fn a_modal_window_that_closes_the_palette_keeps_the_focus_from_the_widget_under_it() { + let ctx = egui::Context::default(); + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); + let mut text = String::new(); + let field = egui::Id::unique("other field"); + let mut frame = |app: &mut VectorcraftApp, focus: bool| { + ctx.run_ui(egui::RawInput::default(), |ui| { + let r = ui.add(egui::TextEdit::singleline(&mut text).id(field)); + if focus { + r.request_focus(); + } + show(app, ui.ctx()); + }) + .textures_delta + .clear(); + }; + frame(&mut app, true); + frame(&mut app, false); + app.ui.palette_open = true; + frame(&mut app, false); + frame(&mut app, false); + // As `panel_docking::close_overlays_for_modal` does when the About window opens. + app.ui.about = true; + app.ui.palette_open = false; + frame(&mut app, false); + frame(&mut app, false); + assert_ne!(ctx.memory(|m| m.focused()), Some(field), "the field under the About window does not take the focus"); + } + /// The widget that had the keyboard focus when the palette opened has it again once the /// palette closes. #[test] @@ -2387,6 +2420,9 @@ mod tests { /// app, as a progress window is drawn, and count its clicks. above: Option<egui::Pos2>, above_clicks: usize, + /// Draw a modal window over the backdrop before the app's windows, as a progress window + /// of a plug-in, trace or open run is drawn. + progress: bool, } impl Window { @@ -2398,7 +2434,7 @@ mod tests { assert!(!app.session.doc().unwrap().selection.is_empty()); let ctx = egui::Context::default(); ctx.enable_accesskit(); - let mut window = Window { app, ctx, time: 0.0, above: None, above_clicks: 0 }; + let mut window = Window { app, ctx, time: 0.0, above: None, above_clicks: 0, progress: false }; window.frame(vec![]); window.frame(vec![]); window @@ -2410,9 +2446,13 @@ mod tests { let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, WINDOW); let input = egui::RawInput { time: Some(self.time), screen_rect: Some(screen), events, ..Default::default() }; let app = &mut self.app; - let (above, clicks) = (self.above, &mut self.above_clicks); + let (above, clicks, progress) = (self.above, &mut self.above_clicks, self.progress); let mut out = self.ctx.run_ui(input, |ui| { app.logic(ui.ctx()); + if progress { + let id = egui::Id::unique("test-progress"); + crate::dialogs::modal::show_at(ui.ctx(), "Progress", id, egui::Vec2::ZERO, 12, |ui| ui.label("Working")); + } app.ui(ui); if let Some(at) = above { let area = egui::Area::new(egui::Id::unique("test-above")).order(egui::Order::Foreground).fixed_pos(at); @@ -2484,6 +2524,150 @@ mod tests { assert_eq!(window.selection(), before, "the click does not reach the canvas"); } + /// #7906: a pick in the macOS menu bar that opens a dialog closes the palette, and the search + /// field does not keep the keyboard from the dialog. + #[test] + fn a_dialog_opened_from_the_system_menu_closes_the_palette() { + let mut window = Window::new(); + window.app.ui.palette_open = true; + window.frame(vec![]); + window.frame(vec![]); + let field = window.ctx.data(|d| d.get_temp::<egui::Id>(egui::Id::unique("palette-field"))).expect("the search field is drawn"); + assert_eq!(window.ctx.memory(|m| m.focused()), Some(field), "the search field has the keyboard"); + menus::invoke_from_system_menu(&mut window.app, &window.ctx, "object.move", json!({})); + assert!(window.app.ui.dialog.is_some(), "Move… opens its dialog: {}", window.app.ui.status); + window.frame(vec![]); + assert!(!window.app.ui.palette_open, "the dialog closes the palette"); + window.frame(vec![]); + assert!(window.app.ui.dialog.is_some(), "the dialog stays open"); + assert_ne!(window.ctx.memory(|m| m.focused()), Some(field), "the search field does not keep the keyboard"); + } + + /// #7906: with the palette open, the About window that opens without a press closes the palette. + #[test] + fn the_about_window_closes_the_palette() { + let mut window = Window::new(); + window.app.ui.palette_open = true; + window.frame(vec![]); + menus::invoke_from_system_menu(&mut window.app, &window.ctx, "help.about", json!({})); + assert!(window.app.ui.about, "About opens"); + window.frame(vec![]); + assert!(!window.app.ui.palette_open, "the About window closes the palette"); + } + + /// #7906: a window drawn over the modal backdrop, as a plug-in, trace or open run's progress + /// window is, closes the palette in the pass it first draws. + #[test] + fn a_progress_window_closes_the_palette() { + let mut window = Window::new(); + window.app.ui.palette_open = true; + window.frame(vec![]); + assert!(window.app.ui.palette_open, "the palette is open"); + window.progress = true; + window.frame(vec![]); + assert!(!window.app.ui.palette_open, "the progress window closes the palette"); + } + + /// #7906: the palette opened from the macOS menu bar while a dialog is open closes again, and its + /// search field does not take the keyboard from the dialog. + #[test] + fn the_palette_opened_over_a_dialog_closes() { + let mut window = Window::new(); + menus::invoke(&mut window.app, "object.move", json!({})); + assert!(window.app.ui.dialog.is_some(), "Move… opens its dialog: {}", window.app.ui.status); + window.frame(vec![]); + window.frame(vec![]); + let before = window.ctx.memory(|m| m.focused()); + menus::invoke_from_system_menu(&mut window.app, &window.ctx, "help.commandPalette", json!({})); + assert!(window.app.ui.palette_open, "the command opens the palette"); + window.frame(vec![]); + window.frame(vec![]); + assert!(!window.app.ui.palette_open, "the dialog keeps the palette closed"); + assert!(window.app.ui.dialog.is_some(), "the dialog stays open"); + let field = window.ctx.data(|d| d.get_temp::<egui::Id>(egui::Id::unique("palette-field"))); + let now = window.ctx.memory(|m| m.focused()); + assert!(field.is_none() || now != field, "the search field does not take the keyboard"); + assert_eq!(now, before, "the dialog keeps its focus"); + } + + /// #7906 as reported: with the palette open, a click on the Effect menu in the window's menu bar + /// closes the palette, and a dialog opened afterwards is not under it. + #[test] + fn a_click_on_the_menu_bar_closes_the_palette_before_a_dialog_opens() { + let mut window = Window::new(); + window.app.ui.palette_open = true; + let nodes = window.frame(vec![]); + window.click(button_at(&nodes, "Effect")); + assert!(!window.app.ui.palette_open, "the click on the menu bar closes the palette"); + menus::invoke(&mut window.app, "object.move", json!({})); + assert!(window.app.ui.dialog.is_some(), "Move… opens its dialog: {}", window.app.ui.status); + window.frame(vec![]); + window.frame(vec![]); + assert!(!window.app.ui.palette_open, "the palette stays closed over the dialog"); + } + + /// Opens `overlay` ("flyout", "drawer" or "menu") in a new window, then opens Move… without a + /// press, as the macOS menu bar or an automation command does: whether the overlay is still open. + fn overlay_open_after_a_dialog_opens(overlay: &str) -> bool { + let mut window = Window::new(); + match overlay { + "flyout" => { + window.app.ui.flyout = Some(0); + let tools = vec!["rectangle".to_string(), "ellipse".to_string()]; + window.ctx.data_mut(|d| d.insert_temp(egui::Id::unique("flyout-tools"), tools)); + } + "drawer" => window.app.ui.tools_drawer = true, + _ => { + let nodes = window.frame(vec![]); + window.click(button_at(&nodes, "Object")); + } + } + window.frame(vec![]); + let open = |w: &Window| w.app.ui.flyout.is_some() || w.app.ui.tools_drawer || egui::Popup::is_any_open(&w.ctx); + assert!(open(&window), "the {overlay} is open"); + menus::invoke(&mut window.app, "object.move", json!({})); + assert!(window.app.ui.dialog.is_some(), "Move… opens its dialog: {}", window.app.ui.status); + window.frame(vec![]); + open(&window) + } + + /// #7906: a dialog that opens without a press closes a tool group's flyout. + #[test] + fn a_dialog_opened_without_a_press_closes_a_flyout() { + assert!(!overlay_open_after_a_dialog_opens("flyout"), "the dialog closes the flyout"); + } + + /// #7906: a dialog that opens without a press closes the All Tools drawer. + #[test] + fn a_dialog_opened_without_a_press_closes_the_tools_drawer() { + assert!(!overlay_open_after_a_dialog_opens("drawer"), "the dialog closes the drawer"); + } + + /// #7906: a dialog that opens without a press closes an open menu. + #[test] + fn a_dialog_opened_without_a_press_closes_a_menu() { + assert!(!overlay_open_after_a_dialog_opens("menu"), "the dialog closes the menu"); + } + + /// The palette opened in the pass after a dialog closes stays open, and the next dialog to open, + /// one pass later, closes it. + #[test] + fn the_palette_opened_as_a_dialog_closes_stays_open_until_the_next_dialog() { + let mut window = Window::new(); + menus::invoke(&mut window.app, "object.move", json!({})); + assert!(window.app.ui.dialog.is_some(), "Move… opens its dialog: {}", window.app.ui.status); + window.frame(vec![]); + window.frame(vec![]); + crate::dialogs::cancel(&mut window.app); + window.app.ui.palette_open = true; + window.frame(vec![]); + assert!(window.app.ui.palette_open, "the palette stays open"); + menus::invoke(&mut window.app, "object.move", json!({})); + assert!(window.app.ui.dialog.is_some(), "Move… opens its dialog again: {}", window.app.ui.status); + window.frame(vec![]); + assert!(!window.app.ui.palette_open, "the next dialog closes the palette"); + } + /// A click on another control outside the popup closes the popup and does not press the /// control. #[test] diff --git a/crates/ui-egui/src/panel_docking.rs b/crates/ui-egui/src/panel_docking.rs index 0a4f01879d..b25c334370 100644 --- a/crates/ui-egui/src/panel_docking.rs +++ b/crates/ui-egui/src/panel_docking.rs @@ -1305,6 +1305,40 @@ pub(crate) fn modal_open(app: &VectorcraftApp, ctx: &egui::Context) -> bool { || ctx.memory(|m| m.areas().is_visible(&crate::dialogs::modal::backdrop())) } +/// Is a modal window open in this pass: a dialog, the About window, a file dialog, the update +/// prompt, or a window such as a progress window drawn over the modal backdrop in this pass? +pub(crate) fn modal_window_up(app: &VectorcraftApp, ctx: &egui::Context) -> bool { + app.ui.dialog.is_some() + || app.ui.about + || app.file_dialog_open() + || crate::updates_ui::blocks_input(app) + || crate::dialogs::modal::drawn_this_pass(ctx) +} + +/// The key of whether a modal window was up in the last pass ([`close_overlays_for_modal`]). +fn modal_window_up_id() -> egui::Id { + egui::Id::unique("modal-window-up") +} + +/// While a modal window is up ([`modal_window_up`]), keeps the command palette closed, so a palette +/// opened over it from the macOS menu bar or by an automation command does not take the keyboard +/// from the window. In the pass the window opens, also closes a tool group's flyout, the All Tools +/// drawer and any open popup, whatever opened the window: a press in the window, a pick in the +/// macOS menu bar, an automation command or a run that ends in a dialog. Popups the window itself +/// opens later stay open. Called after every window of the pass has drawn. +pub(crate) fn close_overlays_for_modal(app: &mut VectorcraftApp, ctx: &egui::Context) { + let up = modal_window_up(app, ctx); + let was = ctx.data_mut(|d| std::mem::replace(d.get_temp_mut_or_default::<bool>(modal_window_up_id()), up)); + if up { + app.ui.palette_open = false; + } + if up && !was { + app.ui.flyout = None; + app.ui.tools_drawer = false; + egui::Popup::close_all(ctx); + } +} + /// Keys, text and clipboard events that a floating panel's own OS window left over run the main /// window's shortcuts, tool keys and clipboard on its next frame ([`VectorcraftApp::raw_input_hook`]). /// craft-ui forwards nothing while a field in that window has the keyboard. A field of the main diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index db61a96f73..5562356691 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1373,6 +1373,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur The Command Palette leaves out the engine commands that Edit › Keyboard Shortcuts marks as needing a value: a query with no default key and no menu bar item (Document JSON, Select All Unused in the Brushes panel), and a command that needs a value no menu item gives (Window › Transparency's `transparency.set`, Document Setup's units). Of those, it still lists the ones whose pick does something without params: Stop Script, Clear Script Console, Clear Plug-in Cache, Reset Preferences, Forget Import Matches, Begin Undo Group and End Undo Group, the six Save … Preset commands, Delete Gradient Preset, Pixel Snapping Options…, the Asset Export commands, New Symbol, Gradient Vector, Define Perspective Grid and Select Slice. Each panel is a result under Window › Show Panel, whose pick shows the panel and leaves one already showing as it is, and each Effect menu item is a result, named as the menu names it, whose pick runs what its menu item runs; while the item is dimmed, no dialog opens and the status line says why. A query of "layers" shows the Layers panel first. The search field's hint and the app bar's search tooltip say "Search commands, tools, panels and effects" (`palette` tests `the_palette_leaves_out_the_commands_a_pick_cannot_run`, `a_pick_of_a_session_command_runs_it`, `a_panel_is_a_result_whose_pick_shows_it`, `an_effect_is_a_result_whose_pick_runs_its_menu_item`; `shortcut_editor` test `a_command_given_a_key_that_needs_a_value_is_no_pick`). The Command Palette shows each result as a 20-point row, with no gap between rows, and shows 12 rows at a time in a list that scrolls; a short window shows fewer. A name too long for its row ends with "…". The list holds up to 50 results, and the line under it says how many matched ("14 results", "50 of 120 results. Keep typing to narrow them." or "No commands match"). Up and Down move the highlight and wrap at the ends, Page Up and Page Down move it by the rows shown and stop at the ends, and the highlighted row scrolls into view; after a scroll with the wheel, the highlight moves to the nearest row in view. A click anywhere on a row runs it. Screen readers stay on the search field, whose description names the highlighted result and its place among every match ("2 of 14: …", or "2 of 120: …" when the list holds 50); the rows are list items, the highlighted one selected, and the keyboard focus goes back to where it was when the palette closes, unless a pick opened a dialog (`palette` tests `results_are_compact_rows_that_touch`, `the_footer_counts_the_results`, `with_no_match_enter_runs_nothing`, `the_sixteenth_result_is_reached_by_keyboard_and_runs`, `page_keys_move_by_a_page_without_wrapping`, `a_wheel_scroll_keeps_the_highlight_in_view`, `the_row_under_the_pointer_is_the_one_highlighted`, `a_long_name_ends_with_an_ellipsis`, `the_popup_stays_inside_a_short_window`, `a_click_anywhere_on_a_row_runs_it`, `screen_readers_hear_the_highlighted_result_and_the_count`, `closing_gives_the_focus_back`). A press of any pointer button outside the Command Palette closes it: a click, a right-click or the start of a drag. While the palette is open, the canvas, the toolbars, the docked panels and the app bar under it do not respond to the pointer, so the press that closes the palette does not press a tool button or another control there. A window drawn above them, such as a progress window, still gets its click, and that click also closes the palette (`palette` tests `a_click_on_the_canvas_closes_the_palette`, `a_click_on_another_control_closes_the_palette_without_pressing_it`, `a_right_click_or_a_drag_outside_closes_the_palette`, `a_click_on_a_window_above_closes_the_palette_and_reaches_it`, `the_click_that_opens_the_palette_does_not_close_it`). + A modal window that opens without a press in the window (a dialog opened from the macOS menu bar or by an automation command, the About window, a file dialog, the update prompt, or the progress window of a plug-in, trace or open run) closes the Command Palette, a tool group's flyout, the All Tools drawer and any open menu or popup in the pass it opens. While such a window is open, the palette stays closed, so opening it from the macOS menu bar or by an automation command does not take the keyboard from the window; it opens again once the window closes (`palette` tests `a_dialog_opened_from_the_system_menu_closes_the_palette`, `the_about_window_closes_the_palette`, `a_progress_window_closes_the_palette`, `the_palette_opened_over_a_dialog_closes`, `a_click_on_the_menu_bar_closes_the_palette_before_a_dialog_opens`, `a_dialog_opened_without_a_press_closes_a_flyout`, `a_dialog_opened_without_a_press_closes_the_tools_drawer`, `a_dialog_opened_without_a_press_closes_a_menu`, `the_palette_opened_as_a_dialog_closes_stays_open_until_the_next_dialog`). The Command Palette ranks its results by how well they match. A query that is a result's id lists that result first (`view.goto1` lists Saved View 1 above Saved View 10); then come results whose name is the query, results whose name without its menu path starts with it, and results whose initials it is ("ea" finds Export As…). Within each of those, a result where every word of the query is a whole word of its name ranks above one where a word only starts a word of the name, then one where it is a word of the menu that holds it, then of its id, then text inside a word, so a query that is a menu's title ("object") lists results named with that word above the items of that menu. A tool ranks above a menu command, panel, effect or filter plug-in that matches as well, so "rect" lists the Rectangle Tool above Effect › Convert to Shape › Rectangle…, and of two results of the same kind the shorter name comes first. Words of the menu bar item that runs a result also find it, the item's own label included ("exit" finds Quit VectorCraft, which File › Exit runs); with the native macOS menu bar, the items that bar moves into its application menu are found under it (Preferences… under Settings). Every result the earlier search found is still found, and the highlight stays on its result when a plug-in is installed, a shortcut changes or the language changes while the palette is open (`palette::search` tests `a_better_word_grade_ranks_first`, `a_better_whole_query_tier_ranks_first`, `kind_and_length_never_lift_a_worse_grade`, `a_menu_title_does_not_lift_its_items`, `common_queries_list_the_command_near_the_top`, `every_result_is_found_first_by_its_name_and_its_id`, `every_result_found_before_is_still_found_and_shown`, `results_know_their_place_in_the_menu_bar`, `native_homes_follow_the_native_application_menu`; `palette` test `the_highlight_stays_on_its_result_when_the_results_change`). `object.setProps` with `visible: false` or `locked: true` deselects every selected object that is then hidden or locked, the key object included, as the eye and lock columns do. Ctrl/Cmd+Alt-clicking an eye switches the other layers to Outline and the row's layer to Preview, or switches all layers back to Preview when the others are in Outline (`layer.outlineOthers`, `layer.previewAll`). From 9c586a2b4f34ae60f01fe6f481b97372d5b4591e Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 17 Nov 2026 08:17:11 -0800 Subject: [PATCH 088/176] Sync PNG export options in the MCP command catalog --- crates/mcp/src/ui_catalog.rs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/crates/mcp/src/ui_catalog.rs b/crates/mcp/src/ui_catalog.rs index b6da21331e..3b5985956f 100644 --- a/crates/mcp/src/ui_catalog.rs +++ b/crates/mcp/src/ui_catalog.rs @@ -143,7 +143,12 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[ "", "{} opens SVG Options; with params = document.export {path?, svg?: {…SVG options}, range?…} (a .svgz path writes it gzipped)", ), - ("file.export.png", "Export As PNG…", "", "{path?, …document.export options}; no path: pick the file, then PNG Options"), + ( + "file.export.png", + "Export As PNG…", + "", + "{path?, …document.export options}; no path: pick the file, then PNG Options with supplied options retained and defaults for omitted options", + ), ( "file.exportForScreens", "Export for Screens…", From 102cfd0cdece8a4e405a3d13db19148d255cdb79 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 17 Nov 2026 08:30:52 -0800 Subject: [PATCH 089/176] Color: built-in CMYK profiles carry their paper and an exact colorimetric table The ICC profile written for a built-in CMYK working space (embedded in PDF, TIFF, JPEG and PSD exports) changes in two ways: - The media white point (wtpt) is the model's paper instead of D50, so the ICC-absolute colorimetric intent reproduces the paper. - The colorimetric Lab -> CMYK table (B2A1), which the gamut tag is also sampled from, is the inverse of the CMYK -> Lab table without black-point compensation. Before, all three Lab -> CMYK tables had compensation built in, so a dark build such as C40 M30 Y30 K60 that went through the profile and back missed by Delta E 2000 2.7 on Generic CMYK. The perceptual and saturation tables keep compensation. --- crates/color/src/cms.rs | 17 +++++++++-- crates/color/src/cms/generic.rs | 5 ++++ crates/color/src/cms/icc.rs | 38 +++++++++++++++++-------- crates/color/src/cms/tests_icc.rs | 47 ++++++++++++++++++++++++++----- docs/target-app-parity.md | 2 +- 5 files changed, 86 insertions(+), 23 deletions(-) diff --git a/crates/color/src/cms.rs b/crates/color/src/cms.rs index 3ad4820ce1..96640b5508 100644 --- a/crates/color/src/cms.rs +++ b/crates/color/src/cms.rs @@ -347,7 +347,9 @@ pub fn profiles_generation() -> u64 { /// Profile `name` as an ICC file to embed in an export: any RGB or CMYK profile of [`profiles`] /// (by its current or legacy name), or [`GRAY`]. Built-in profiles are written in code from the /// CMS: the RGB spaces from their primaries, the CMYK spaces as lookup tables sampled from their -/// model (both directions, perceptual and relative colorimetric, Lab PCS); a profile the user +/// model (both directions, perceptual and relative colorimetric, Lab PCS, with the model's paper +/// as the media white point; the colorimetric Lab → CMYK table without black-point +/// compensation, the perceptual and saturation ones with it); a profile the user /// loaded is the file it came from. Cached. pub fn icc_bytes(name: &str) -> Result<Arc<[u8]>, CmsError> { static CACHE: Mutex<Vec<(String, Arc<[u8]>)>> = Mutex::new(Vec::new()); @@ -361,8 +363,17 @@ pub fn icc_bytes(name: &str) -> Result<Arc<[u8]>, CmsError> { let bytes: Arc<[u8]> = if name == GRAY { icc::encode(&icc::gray_profile(name))? } else if BUILTIN_CMYK.contains(&name) { - let cms = Cms::new(&ColorSettings { cmyk: name.into(), ..ColorSettings::default() })?; - icc::encode(&icc::cmyk_profile(name, |c| cms.cmyk_to_lab(c), |l| cms.lab_to_cmyk(l, Intent::RelativeColorimetric)))? + // The perceptual and saturation tables map the shadows with black-point compensation; the + // colorimetric table is the inverse of the CMYK → Lab table, without it. + let mapped = Cms::new(&ColorSettings { cmyk: name.into(), bpc: true, ..ColorSettings::default() })?; + let cms = Cms::new(&ColorSettings { cmyk: name.into(), bpc: false, ..ColorSettings::default() })?; + let paper = match &cms.cmyk { + CmykSpace::Generic(g) => g.paper_xyz(), + CmykSpace::Device | CmykSpace::Icc(_) => lab::D50, + }; + let to_lab = |c| cms.cmyk_to_lab(c); + let shadows = |l| mapped.lab_to_cmyk(l, Intent::RelativeColorimetric); + icc::encode(&icc::cmyk_profile(name, paper, to_lab, shadows, |l| cms.lab_to_cmyk(l, Intent::RelativeColorimetric)))? } else { icc::builtin_rgb_bytes(name)? } diff --git a/crates/color/src/cms/generic.rs b/crates/color/src/cms/generic.rs index 3d532ac02a..16f251054b 100644 --- a/crates/color/src/cms/generic.rs +++ b/crates/color/src/cms/generic.rs @@ -133,6 +133,11 @@ pub struct GenericCmyk { } impl GenericCmyk { + /// Absolute XYZ (D50) of the paper. + pub fn paper_xyz(&self) -> [f32; 3] { + self.paper_xyz + } + pub fn new(params: GenericCmykParams) -> Self { let paper_xyz = lab_to_xyz(params.paper); let mut prim = [D50; 16]; diff --git a/crates/color/src/cms/icc.rs b/crates/color/src/cms/icc.rs index ffddd6c955..8fc287ae23 100644 --- a/crates/color/src/cms/icc.rs +++ b/crates/color/src/cms/icc.rs @@ -446,11 +446,20 @@ const B2A_GRID: usize = 17; const GAMUT_GRID: usize = 9; /// A CMYK output profile sampled from a conversion: `to_lab` (CMYK → media-relative Lab) in a -/// 9⁴ table, `from_lab` (Lab → CMYK, gamut-mapped) in a 17³ table, Lab PCS (ICC v4 encoding). +/// 9⁴ table, and Lab → CMYK in 17³ tables, Lab PCS (ICC v4 encoding): `mapped` (gamut-mapped, +/// with black-point compensation) for the perceptual and saturation intents, `colorimetric` (the +/// colorimetric inverse of `to_lab`) for the colorimetric intents and the gamut tag. /// It carries every tag ICC.1 requires of an output profile: the tables for all three intents /// and the gamut tag (Windows rejects a CMYK profile without them, so Photos couldn't show a CMYK -/// TIFF that embedded one, #2707). -pub(super) fn cmyk_profile(name: &str, to_lab: impl Fn([f32; 4]) -> lab::Lab, from_lab: impl Fn(lab::Lab) -> [f32; 4]) -> ColorProfile { +/// TIFF that embedded one, #2707). The media white point is `paper` (absolute XYZ, D50), which +/// the ICC-absolute colorimetric intent reproduces. +pub(super) fn cmyk_profile( + name: &str, + paper: [f32; 3], + to_lab: impl Fn([f32; 4]) -> lab::Lab, + mapped: impl Fn(lab::Lab) -> [f32; 4], + colorimetric: impl Fn(lab::Lab) -> [f32; 4], +) -> ColorProfile { let unit = |i: usize, n: usize| i as f32 / (n - 1) as f32; let q = |v: f32| (v.clamp(0.0, 1.0) * 65535.0).round() as u16; let mut a2b = Vec::with_capacity(A2B_GRID.pow(4) * 3); @@ -459,17 +468,21 @@ pub(super) fn cmyk_profile(name: &str, to_lab: impl Fn([f32; 4]) -> lab::Lab, fr let l = to_lab(cmyk); a2b.extend([l.l / 100.0, (l.a + 128.0) / 255.0, (l.b + 128.0) / 255.0].map(q)); } - let mut b2a = Vec::with_capacity(B2A_GRID.pow(3) * 4); - for i in 0..B2A_GRID.pow(3) { - let [l, a, b] = [2, 1, 0].map(|d| unit(i / B2A_GRID.pow(d) % B2A_GRID, B2A_GRID)); - b2a.extend(from_lab(lab::Lab::new(l * 100.0, a * 255.0 - 128.0, b * 255.0 - 128.0)).map(q)); - } + let b2a_of = |from_lab: &dyn Fn(lab::Lab) -> [f32; 4]| { + let mut b2a = Vec::with_capacity(B2A_GRID.pow(3) * 4); + for i in 0..B2A_GRID.pow(3) { + let [l, a, b] = [2, 1, 0].map(|d| unit(i / B2A_GRID.pow(d) % B2A_GRID, B2A_GRID)); + b2a.extend(from_lab(lab::Lab::new(l * 100.0, a * 255.0 - 128.0, b * 255.0 - 128.0)).map(q)); + } + b2a + }; + let (b2a_mapped, b2a) = (b2a_of(&mapped), b2a_of(&colorimetric)); // Gamut: 0 where a colour separates and comes back within a ΔE of 3, else out of gamut. let mut gamut = Vec::with_capacity(GAMUT_GRID.pow(3)); for i in 0..GAMUT_GRID.pow(3) { let [l, a, b] = [2, 1, 0].map(|d| unit(i / GAMUT_GRID.pow(d) % GAMUT_GRID, GAMUT_GRID)); let want = lab::Lab::new(l * 100.0, a * 255.0 - 128.0, b * 255.0 - 128.0); - gamut.push(if lab::delta_e2000(want, to_lab(from_lab(want))) <= 3.0 { 0 } else { u16::MAX }); + gamut.push(if lab::delta_e2000(want, to_lab(colorimetric(want))) <= 3.0 { 0 } else { u16::MAX }); } let identity = |n: usize| vec![ToneReprCurve::Parametric(vec![1.0]); n]; let table = |inputs: usize, outputs: usize, grid: usize, clut: Vec<u16>| { @@ -490,6 +503,7 @@ pub(super) fn cmyk_profile(name: &str, to_lab: impl Fn([f32; 4]) -> lab::Lab, fr }) }; let a2b = table(4, 3, A2B_GRID, a2b); + let b2a_mapped = table(3, 4, B2A_GRID, b2a_mapped); let b2a = table(3, 4, B2A_GRID, b2a); let gamut = table(3, 1, GAMUT_GRID, gamut); let mut p = ColorProfile::default(); @@ -498,12 +512,12 @@ pub(super) fn cmyk_profile(name: &str, to_lab: impl Fn([f32; 4]) -> lab::Lab, fr p.pcs = DataColorSpace::Lab; p.rendering_intent = RenderingIntent::RelativeColorimetric; p.white_point = moxcms::WHITE_POINT_D50.to_xyzd(); - p.media_white_point = Some(p.white_point); + p.media_white_point = Some(moxcms::Xyzd::new(f64::from(paper[0]), f64::from(paper[1]), f64::from(paper[2]))); p.lut_a_to_b_perceptual = Some(a2b.clone()); p.lut_a_to_b_saturation = Some(a2b.clone()); p.lut_a_to_b_colorimetric = Some(a2b); - p.lut_b_to_a_perceptual = Some(b2a.clone()); - p.lut_b_to_a_saturation = Some(b2a.clone()); + p.lut_b_to_a_perceptual = Some(b2a_mapped.clone()); + p.lut_b_to_a_saturation = Some(b2a_mapped); p.lut_b_to_a_colorimetric = Some(b2a); p.gamut = Some(gamut); labelled(p, name) diff --git a/crates/color/src/cms/tests_icc.rs b/crates/color/src/cms/tests_icc.rs index bee0f0f9fa..e49e67082a 100644 --- a/crates/color/src/cms/tests_icc.rs +++ b/crates/color/src/cms/tests_icc.rs @@ -30,11 +30,43 @@ fn cmyk_profiles_convert_like_the_cms() { let de = delta_e2000(lab::srgb_to_lab(want), lab::srgb_to_lab(got)); assert!(de < 2.5, "{name} {cmyk:?}: {want:?} vs {got:?} (ΔE {de})"); } - // And back: an in-gamut colour separates to about the same inks. - let srgb = cms.cmyk_to_srgb([0.1, 0.6, 0.8, 0.0], false); - let back = p.from_srgb(srgb, Intent::RelativeColorimetric).unwrap(); - let again = cms.cmyk_to_srgb([back[0], back[1], back[2], back[3]], false); - assert!(delta_e2000(lab::srgb_to_lab(srgb), lab::srgb_to_lab(again)) < 3.0, "{back:?}"); + // And back: in-gamut colours separate to inks that print them. The Lab → CMYK table is + // the colorimetric inverse of the CMYK → Lab table, with no black-point compensation. + for inks in [ + [0.1, 0.6, 0.8, 0.0], + [0.5, 0.1, 0.3, 0.1], + [0.3, 0.3, 0.3, 0.2], + [0.05, 0.05, 0.4, 0.0], + [0.4, 0.3, 0.3, 0.6], + [0.6, 0.5, 0.5, 0.4], + [0.2, 0.2, 0.2, 0.8], + [0.0, 0.0, 0.0, 0.5], + ] { + let srgb = cms.cmyk_to_srgb(inks, false); + let back = p.from_srgb(srgb, Intent::RelativeColorimetric).unwrap(); + let again = cms.cmyk_to_srgb([back[0], back[1], back[2], back[3]], false); + let de = delta_e2000(lab::srgb_to_lab(srgb), lab::srgb_to_lab(again)); + assert!(de < 1.5, "{name} {inks:?}: {srgb:?} -> {back:?} -> {again:?} (ΔE {de})"); + } + // The perceptual table keeps black-point compensation: source black separates to inks + // that print the press's black point, as the CMS separates it with compensation. + let compensated = Cms::new(&ColorSettings { cmyk: name.into(), bpc: true, ..Default::default() }).unwrap(); + let want = compensated.srgb_to_cmyk([0.0; 3], Intent::RelativeColorimetric); + let got = p.from_srgb([0.0; 3], Intent::Perceptual).unwrap(); + let printed = |inks: &[f32]| cms.cmyk_to_lab([inks[0], inks[1], inks[2], inks[3]]); + let de = delta_e2000(printed(&want), printed(&got)); + assert!(de < 1.5, "{name}: perceptual black {got:?} prints {:?}, want {want:?} ({:?})", printed(&got), printed(&want)); + } +} + +#[test] +fn cmyk_profiles_carry_their_paper_as_the_media_white() { + let generic = generic::swop_like(); + let p = parse(&icc_bytes(GENERIC_CMYK).unwrap()); + let white = p.media_white_point.unwrap(); + let paper = lab::lab_to_xyz(generic.paper); + for (got, want) in [white.x, white.y, white.z].iter().zip(paper) { + assert!((*got - f64::from(want)).abs() < 2e-3, "{white:?} vs {paper:?}"); } } @@ -116,9 +148,10 @@ fn black_point_compensation_maps_the_darkest_ink_to_rgb_black() { let rich = [0.75, 0.68, 0.67, 0.9]; let (on, off) = (icc_cmyk(true).cmyk_to_rgb(rich, Intent::RelativeColorimetric), icc_cmyk(false).cmyk_to_rgb(rich, Intent::RelativeColorimetric)); // Without compensation the profile's black is a dark grey; with it, rich black goes most of - // the way to RGB black (not all: it isn't quite the darkest ink the profile prints). + // the way to RGB black (not all: it isn't quite the darkest ink the profile prints, and the + // profile's Lab → CMYK table carries no compensation of its own). assert!(off.iter().all(|v| *v > 0.1), "without: {off:?}"); - assert!(on.iter().zip(off).all(|(a, b)| *a < 0.08 && *a < b * 0.5), "with: {on:?}, without: {off:?}"); + assert!(on.iter().zip(off).all(|(a, b)| *a < 0.09 && *a < b * 0.55), "with: {on:?}, without: {off:?}"); // The screen shows what an sRGB conversion writes, compensated alike. let srgb = |bpc| { let c = icc_cmyk(bpc); diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index e9fc9a6820..a1d4bd4576 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1762,7 +1762,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Eyedropper sources (#1251):** ordinary and Shift clicks, Shift+Alt appearance append, raster pixels and gradient-stop sampling can read visible locked/template art and sources outside isolation. Sampling leaves the source and selection intact; Alt reverse still uses editable hits, and hidden art stays excluded. Engine/tool/hit regressions cover the editing boundary, color models and one-step Undo/Redo. The general object/image workflow is described in [public HelpX](https://helpx.adobe.com/illustrator/using/tool-techniques/eyedropper-tool.html); the lock/isolation expectations come from the user report and these regressions, without a new full-parity measurement. - **Eyedropper colors in a CMYK document (#2276):** a CMYK image (a four-component JPEG, or an 8- or 16-bit chunky CMYK TIFF) gives its ink amounts as they are, and an RGB image's pixel or an RGB color given to `paint.setFill`, `paint.setStroke`, `paint.sampleColor` or `swatch.new {color}` (hex input and gradient stops included) is separated through the color settings' CMYK working space and intent, as Document Color Mode converts it. With the default Generic CMYK, RGB 83/170/223 separates to C62 M19 Y0 K0, where the profile-free formula gave C63 M24 Y0 K13. - **RGB input to other commands in a CMYK document:** type colors (`text.create`, `text.setStyle`, `text.setRangeStyle`), a Shape Builder hex fill, `paint.editGradient` stops, freeform gradient points, gradient mesh points (the Mesh tool gives a new point the fill's color in its own model), the Symbol Stainer's color and the swatch commands (`swatch.new {colors}`, `swatch.newGroup`, `swatch.editGroup`, `swatch.edit`) separate RGB through the color settings as `paint.setFill` does: with Generic CMYK, `text.setStyle {fill: "#53aadf"}` gives C62 M19 Y0 K0. A color a swatch already has keeps its model, and a swatch color given with `mode` is converted into that mode only. - - **Generic CMYK (SWOP-like):** each ink's 40% and 50% tints gain as [CGATS TR 001](https://registry.color.org/cmyk-registry/cgats_tr_001) gives for SWOP printing, and separations stay within SWOP's [300% total ink limit](https://en.wikipedia.org/wiki/Specifications_for_Web_Offset_Publications). The paper, solid and overprint colors, the black-generation curve and the black point are VectorCraft's own values: RGB black separates to 90% black under neutral cyan, magenta and yellow that fill the ink limit (C75 M68 Y67 K90). + - **Generic CMYK (SWOP-like):** each ink's 40% and 50% tints gain as [CGATS TR 001](https://registry.color.org/cmyk-registry/cgats_tr_001) gives for SWOP printing, and separations stay within SWOP's [300% total ink limit](https://en.wikipedia.org/wiki/Specifications_for_Web_Offset_Publications). The paper, solid and overprint colors, the black-generation curve and the black point are VectorCraft's own values: RGB black separates to 90% black under neutral cyan, magenta and yellow that fill the ink limit (C75 M68 Y67 K90). The ICC profile written for it (embedded in exports) gives the paper as its media white point, and its colorimetric Lab → CMYK table is the inverse of its CMYK → Lab table, without black-point compensation; the perceptual and saturation tables keep compensation. - **Swatches made from a shown color in a CMYK document:** the Color panel menu's Create New Swatch, an Alt-click on the Swatches panel's New Swatch button, the New Swatch dialog for a gradient, a Fill or Stroke proxy or the Gradient panel's thumbnail dropped on the Swatches panel (or Alt-dropped on a swatch of its kind), and the Gradient panel's Add to Swatches and Save to Swatches keep each color's model, as the Color Guide's and Color Themes' saved colors do: an RGB object's color gives an RGB swatch, and a gradient's RGB stops stay RGB. - **Sample Color from Screen:** an eyedropper button in the Color Picker and `ui.sampleScreenColor` (which can be given a key in Keyboard Shortcuts) pick a color anywhere on the screen with the system's sampler: `NSColorSampler` on macOS, the XDG desktop portal's [PickColor](https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.Screenshot.html) on Linux, a still copy of every monitor under a crosshair on Windows, and the EyeDropper API in browsers that have it. The color becomes the fill or the stroke as one undo step, or the Color Picker's color, converted from display sRGB into the working RGB space. On Linux, a session without a portal that has PickColor, a portal that does not return from the call within 25 seconds (VectorCraft's own limit) or leaves the bus before it answers, and a portal that ends the request another way each show a status message and end the wait. On Windows, the copy is read as sRGB, so the colors of HDR and wide-gamut displays are not converted; Escape, a click of another mouse button or switching to another window cancels (VectorCraft's own rules). The BSDs and other browsers have no sampler yet; the button is gray there. - **Color Guide color groups:** with variation cells selected, the Color Guide's Save Color Group to Swatches button saves those cells as one swatch group, and with none selected it saves the harmony colors, as the [help page](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf) describes saving several selected variations together (printed page 135). The group takes the cells in grid order (row by row, left to right, each cell once), is named after the harmony rule and is one undo step; these are VectorCraft's own rules. A selection lasts until the base, the Color Guide Options, the variation mode, the harmony rule, the library limit or the colors the grid shows (for example after a new swatch while the guide is limited to the document's swatches) change. From 6e44c63cc3470065e74e364d2845733adc775345 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 17 Nov 2026 07:23:31 -0800 Subject: [PATCH 090/176] Undo: undo and redo keep the settings changed without an undo step Undo and redo put back the whole document a step stored, so settings that change without an undo step went back with it. Undoing any earlier edit turned the perspective grid's Lock Grid off again, turned its Snap to Grid back on, showed a hidden grid and switched the active plane back. It also reset the grid from Gridline every and Subdivisions, the export settings assets.settings.set stores, and the current brush and symbol. Each undo step now also records these settings as the step left them. Undo and redo compare that record with the document they bring back: a setting the step did not change stays as it is now, and a setting the step changed comes back with the step. So undoing a perspective grid preset still hides the grid the preset showed, and undoing a grid definition that locked the grid unlocks it. The point Automatic Plane Positioning holds still follows the steps, and is let go when the active plane kept is another one. --- crates/engine/src/cmd.rs | 2 +- crates/engine/src/cmd/edit.rs | 82 +++++++++++++++++++++++++++ crates/engine/src/history.rs | 7 +++ crates/engine/src/tests/assets.rs | 17 ++++++ crates/engine/src/tests/brushsym.rs | 34 +++++++++++ crates/engine/src/tests/menucmds.rs | 17 ++++++ crates/engine/src/tests/perspgrid.rs | 85 ++++++++++++++++++++++++++++ crates/engine/src/tests/prefs.rs | 17 ++++++ docs/mcp.md | 2 +- 9 files changed, 261 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index c4a86dd3a5..4089c5c0e6 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -824,7 +824,7 @@ pub(crate) use addons::{DecodedImages, refresh_color_masks}; /// Document Info's category titles and the Objects category's count labels. pub use docinfo::{CATEGORIES, OBJECT_LABELS}; pub use docmenu::guide_indexes; -pub(crate) use edit::{settle_interaction, typing_in_progress}; +pub(crate) use edit::{Unrecorded, settle_interaction, typing_in_progress}; pub(crate) use object::bounds_rewrite; pub(crate) use object::{keep_aligned_in, refresh_pixel_aligned}; pub use plugin_call::{Location, ParamsPlace, key_location, location_in, location_keys}; diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index fbf5deb568..656ea1ccb2 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -6,6 +6,7 @@ use std::sync::Arc; use serde_json::{Value, json}; use vectorcraft_doc::{Document, Node, NodeId, NodeKind, RulerMode, Unit}; use vectorcraft_geom::{Affine, Point, Vec2}; +use vectorcraft_tools::distort::perspective::{PerspectiveGrid, Plane}; use super::clipboard::SwatchChoices; use super::{ @@ -713,6 +714,85 @@ pub(crate) fn settle_interaction(s: &mut Session) -> Result<()> { Ok(()) } +/// The document state that commands also change without an undo step: the perspective grid's view +/// options (whether it shows, Lock Grid, Lock Station Point, Snap to Grid and Show Rulers), its +/// active plane, the grid preferences, the export settings, and the current brush and symbol. Each +/// undo and redo step keeps it as the document on its other side had it +/// ([`crate::HistoryEntry::unrecorded`]). +#[derive(Clone, Debug, PartialEq)] +pub(crate) struct Unrecorded { + grid: vectorcraft_doc::GridPrefs, + export_settings: serde_json::Map<String, Value>, + brush: Option<Value>, + symbol: Option<Value>, + options: [bool; 5], + plane: Plane, +} + +impl Unrecorded { + pub(crate) fn of(d: &Document) -> Self { + let g = PerspectiveGrid::current(d); + Unrecorded { + grid: d.grid.clone(), + export_settings: d.export_settings.clone(), + brush: d.unknown.get(vectorcraft_brush::CURRENT_KEY).cloned(), + symbol: d.unknown.get(super::brushsym::CURRENT_SYMBOL).cloned(), + options: [g.visible, g.locked, g.lock_station, g.snap, g.rulers], + plane: g.plane, + } + } +} + +/// Undo and redo bring back `d`; `step` is that state as the document on the step's other side had +/// it. A part the step did not change (`d` has it as `step` does) stays as it is in `now`, the +/// document before the undo or redo, since it changed after the step without an undo step. A part +/// the step changed comes back with `d`. A current brush or symbol that `d` does not hold also +/// comes back with `d`. The point Automatic Plane Positioning holds comes back with `d`, and is let go when the +/// active plane kept is not the one it holds. +fn keep_unrecorded(now: &Document, step: &Unrecorded, d: &mut Arc<Document>) { + fn pick<T: Clone + PartialEq>(back: &T, step: &T, now: &T) -> T { + if back == step { now.clone() } else { back.clone() } + } + let back = Unrecorded::of(d); + let cur = Unrecorded::of(now); + let mut want = Unrecorded { + grid: pick(&back.grid, &step.grid, &cur.grid), + export_settings: pick(&back.export_settings, &step.export_settings, &cur.export_settings), + brush: pick(&back.brush, &step.brush, &cur.brush), + symbol: pick(&back.symbol, &step.symbol, &cur.symbol), + options: std::array::from_fn(|i| pick(&back.options[i], &step.options[i], &cur.options[i])), + plane: pick(&back.plane, &step.plane, &cur.plane), + }; + if want.brush != back.brush && want.brush.as_ref().and_then(Value::as_str).is_some_and(|n| vectorcraft_brush::find(d, n).is_none()) { + want.brush = back.brush.clone(); + } + if want.symbol != back.symbol && want.symbol.as_ref().and_then(Value::as_str).is_some_and(|n| !d.symbols.iter().any(|s| s.name == n)) { + want.symbol = back.symbol.clone(); + } + if want == back { + return; + } + let m = Arc::make_mut(d); + for (key, v) in [(vectorcraft_brush::CURRENT_KEY, &want.brush), (super::brushsym::CURRENT_SYMBOL, &want.symbol)] { + match v { + Some(v) => m.unknown.insert(key.into(), v.clone()), + None => m.unknown.remove(key), + }; + } + if (want.options, want.plane) != (back.options, back.plane) { + let mut g = PerspectiveGrid::current(m); + [g.visible, g.locked, g.lock_station, g.snap, g.rulers] = want.options; + if g.plane != want.plane { + g.plane = want.plane; + g.inferred = None; + } + g.keep_positioning_valid(); + super::distortcmds::store_grid(m, &g); + } + m.grid = want.grid; + m.export_settings = want.export_settings; +} + fn undo(s: &mut Session, _: &Value) -> Result<Value> { settle_interaction(s)?; let menu = s.menu.clone(); @@ -723,6 +803,7 @@ fn undo(s: &mut Session, _: &Value) -> Result<Value> { let editing = st.doc.mask_edit.map(|m| m.layer); let editing_symbol = st.doc.symbol_edit.clone(); let doc = std::mem::replace(&mut st.doc, e.doc); + keep_unrecorded(&doc, &e.unrecorded, &mut st.doc); let selection = std::mem::replace(&mut st.selection, Arc::unwrap_or_clone(e.selection)); let selection = shared_selection(selection, st.history.redo.last()); let mut turned = crate::HistoryEntry::turned(e.label, doc, selection, &st.doc, costs); @@ -758,6 +839,7 @@ fn redo(s: &mut Session, _: &Value) -> Result<Value> { let editing = st.doc.mask_edit.map(|m| m.layer); let editing_symbol = st.doc.symbol_edit.clone(); let doc = std::mem::replace(&mut st.doc, e.doc); + keep_unrecorded(&doc, &e.unrecorded, &mut st.doc); let selection = std::mem::replace(&mut st.selection, Arc::unwrap_or_clone(e.selection)); let selection = shared_selection(selection, st.history.undo.last()); let mut turned = crate::HistoryEntry::turned(e.label, doc, selection, &st.doc, costs); diff --git a/crates/engine/src/history.rs b/crates/engine/src/history.rs index 3ab6a7dcb8..d472ec760c 100644 --- a/crates/engine/src/history.rs +++ b/crates/engine/src/history.rs @@ -32,6 +32,9 @@ pub struct HistoryEntry { pub(crate) color_mode_paints: Option<(vectorcraft_tools::PaintDefaults, vectorcraft_tools::PaintDefaults)>, /// Owned new-art snapshots included in both directional estimates. color_mode_bytes: usize, + /// The state that changes without an undo step as the next state had it: undo and redo compare + /// it with `doc` to tell what the step changed. + pub(crate) unrecorded: Arc<crate::cmd::Unrecorded>, } impl Clone for HistoryEntry { @@ -49,6 +52,7 @@ impl Clone for HistoryEntry { serial: self.serial, color_mode_paints: self.color_mode_paints.clone(), color_mode_bytes: self.color_mode_bytes, + unrecorded: self.unrecorded.clone(), } } } @@ -94,6 +98,7 @@ impl HistoryEntry { serial: next_serial(), color_mode_paints: None, color_mode_bytes: 0, + unrecorded: Arc::new(crate::cmd::Unrecorded::of(next)), } } @@ -126,6 +131,7 @@ impl HistoryEntry { serial: next_serial(), color_mode_paints: None, color_mode_bytes: 0, + unrecorded: Arc::new(crate::cmd::Unrecorded::of(now)), } } @@ -337,6 +343,7 @@ impl History { e.next_bytes = after.saturating_add(e.color_mode_bytes); e.next = std::ptr::from_ref(now) as usize; e.serial = next_serial(); + e.unrecorded = Arc::new(crate::cmd::Unrecorded::of(now)); } } } diff --git a/crates/engine/src/tests/assets.rs b/crates/engine/src/tests/assets.rs index 1d571884a0..fff9ed9588 100644 --- a/crates/engine/src/tests/assets.rs +++ b/crates/engine/src/tests/assets.rs @@ -302,6 +302,23 @@ fn the_shared_settings_drive_the_export_and_arent_an_undo_step() { assert_eq!(run(&mut s, "document.exportSettings", json!({}))["settings"]["formats"][0]["format"], "jpg"); } +/// The shared settings are not an undo step, so undo and redo of the steps before them leave them +/// as they are. +#[test] +fn undo_and_redo_keep_the_shared_settings() { + let mut s = session(); + let a = rect(&mut s, 10.0, 10.0, 20.0, 20.0); + run(&mut s, "assets.add", json!({"ids": [a]})); + run(&mut s, "assets.settings.set", json!({"formats": [{"format": "svg"}], "prefix": "ic_"})); + let settings = run(&mut s, "document.exportSettings", json!({}))["settings"].clone(); + run(&mut s, "edit.undo", json!({})); + assert_eq!(run(&mut s, "document.exportSettings", json!({}))["settings"], settings); + run(&mut s, "assets.settings.set", json!({"formats": [{"format": "jpg"}], "prefix": ""})); + let settings = run(&mut s, "document.exportSettings", json!({}))["settings"].clone(); + run(&mut s, "edit.redo", json!({})); + assert_eq!(run(&mut s, "document.exportSettings", json!({}))["settings"], settings); +} + /// An export preset sets the shared settings as the Asset Export panel applies one: its rows (or /// mobile/density), its format settings over the saved ones, its prefix and its sub-folders. #[test] diff --git a/crates/engine/src/tests/brushsym.rs b/crates/engine/src/tests/brushsym.rs index 77258b7eb7..ba895f6800 100644 --- a/crates/engine/src/tests/brushsym.rs +++ b/crates/engine/src/tests/brushsym.rs @@ -1182,6 +1182,40 @@ fn paintbrush_tool_uses_the_current_brush() { assert!(s.execute("brush.setCurrent", &json!({"name": "Nope"})).is_err()); } +/// The current brush and symbol are not undo steps, so undo and redo of other steps leave them as +/// they are. With nothing else changed outside the history, undo back to the saved document leaves +/// it saved. +#[test] +fn undo_and_redo_keep_the_current_brush_and_symbol() { + let mut s = session(); + rect(&mut s, 10.0, 10.0, 20.0, 20.0); + s.execute("symbol.new", &json!({"name": "A"})).unwrap(); + rect(&mut s, 40.0, 10.0, 20.0, 20.0); + s.execute("symbol.new", &json!({"name": "B"})).unwrap(); + s.doc_mut().unwrap().mark_saved(); + rect(&mut s, 70.0, 10.0, 20.0, 20.0); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(!s.doc().unwrap().is_dirty(), "back at the saved document"); + s.execute("edit.redo", &json!({})).unwrap(); + s.execute("brush.setCurrent", &json!({"name": "Arrow"})).unwrap(); + s.execute("symbol.setCurrent", &json!({"name": "A"})).unwrap(); + let current = |s: &mut Session| { + let brush = s.execute("brush.list", &json!({})).unwrap()["current"].clone(); + (brush, s.execute("symbol.list", &json!({})).unwrap()["current"].clone()) + }; + let want = (json!("Arrow"), json!("A")); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(current(&mut s), want); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(current(&mut s), want); + // A symbol made current between undoing and redoing its deletion is not kept as current. + s.execute("symbol.delete", &json!({"name": "B"})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("symbol.setCurrent", &json!({"name": "B"})).unwrap(); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc.unknown.get("currentSymbol"), Some(&json!("A"))); +} + /// A Size: Pressure variant of "3 pt. Round" (3 ± 3 pt). fn pressure_round(s: &mut Session) { let params = json!({"variation": [0, 0, 3], "modes": ["fixed", "fixed", "pressure"]}); diff --git a/crates/engine/src/tests/menucmds.rs b/crates/engine/src/tests/menucmds.rs index ae40324b9e..652a09f65c 100644 --- a/crates/engine/src/tests/menucmds.rs +++ b/crates/engine/src/tests/menucmds.rs @@ -5608,3 +5608,20 @@ fn crop_image_trim_leaves_a_cmyk_image_alone() { let r = s.execute("object.cropImage", &json!({"trim": true})).unwrap(); assert_eq!((r["trimmed"].as_bool(), r["width"].as_u64(), r["height"].as_u64()), (Some(false), Some(4), Some(2)), "{r}"); } + +/// Lock Guides is not an undo step: it adds none, and undo and redo of the steps before it leave +/// the guides locked. +#[test] +fn lock_guides_is_not_an_undo_step() { + let mut s = session(); + let g = rect(&mut s, 200.0, 0.0, 10.0, 10.0); + sel(&mut s, &[g]); + s.execute("view.guides.make", &json!({})).unwrap(); + let steps = s.doc().unwrap().history.undo.len(); + s.execute("view.guides.lock", &json!({"locked": true})).unwrap(); + assert_eq!(s.doc().unwrap().history.undo.len(), steps); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(s.guides_locked()); + s.execute("edit.redo", &json!({})).unwrap(); + assert!(s.guides_locked()); +} diff --git a/crates/engine/src/tests/perspgrid.rs b/crates/engine/src/tests/perspgrid.rs index 4b7c1c2ae4..b4f8d89ca3 100644 --- a/crates/engine/src/tests/perspgrid.rs +++ b/crates/engine/src/tests/perspgrid.rs @@ -312,6 +312,91 @@ fn view_options_toggle_without_undo_steps_and_survive_presets() { assert_eq!(PerspectiveGrid::from_doc(&back), Some(g)); } +/// The view options are not undo steps, so undo and redo of other steps leave them as they are: +/// Lock Grid, Lock Station Point, Snap to Grid, Show Rulers and whether the grid shows. Undoing a +/// grid definition brings back the old grid with the current view options. +#[test] +fn undo_and_redo_keep_the_view_options() { + let mut s = session(); + run(&mut s, "perspective.grid.preset", json!({"kind": 2})); + let old = grid(&s); + run(&mut s, "shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 40})); + run(&mut s, "perspective.grid.preset", json!({"kind": 1})); + let n = undo_len(&s); + for (id, on) in + [("perspective.grid.lock", true), ("perspective.grid.lockStation", true), ("perspective.grid.snap", false), ("perspective.grid.rulers", true)] + { + run(&mut s, id, json!({"on": on})); + } + run(&mut s, "perspective.grid.show", json!({"visible": false})); + assert_eq!(undo_len(&s), n); + let view = |g: &PerspectiveGrid| (g.locked, g.lock_station, g.snap, g.rulers, g.visible); + let want = (true, true, false, true, false); + assert_eq!(view(&grid(&s)), want); + // Undo the one-point preset: the two-point grid comes back with today's view options. + s.execute("edit.undo", &json!({})).unwrap(); + let g = grid(&s); + assert_eq!((g.kind, g.vp_left, view(&g)), (old.kind, old.vp_left, want)); + // Undo the rectangle, which left the grid alone. + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(view(&grid(&s)), want); + // An option changed now holds through the redo steps. + run(&mut s, "perspective.grid.lock", json!({"on": false})); + s.execute("edit.redo", &json!({})).unwrap(); + s.execute("edit.redo", &json!({})).unwrap(); + let g = grid(&s); + assert_eq!((g.kind, view(&g)), (1, (false, true, false, true, false))); +} + +/// The view options set on a document whose steps hold no grid yet stay as they are when undo +/// brings back a step without one, and the active plane chosen without an undo step stays too. +#[test] +fn undo_keeps_the_view_options_of_a_grid_no_step_defined() { + let mut s = session(); + run(&mut s, "shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 40})); + run(&mut s, "shape.rectangle", json!({"x": 100, "y": 10, "width": 50, "height": 40})); + assert!(!s.doc().unwrap().doc.unknown.contains_key(vectorcraft_tools::distort::perspective::DOC_KEY)); + run(&mut s, "perspective.grid.show", json!({"visible": true})); + run(&mut s, "perspective.grid.lock", json!({"on": true})); + run(&mut s, "perspective.grid.snap", json!({"on": false})); + run(&mut s, "perspective.plane.set", json!({"plane": "ground"})); + let view = |g: &PerspectiveGrid| (g.visible, g.locked, g.snap, g.plane); + let want = (true, true, false, vectorcraft_tools::distort::perspective::Plane::Ground); + assert_eq!(view(&grid(&s)), want); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(view(&grid(&s)), want); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(view(&grid(&s)), want); +} + +/// A step that changed a view option itself takes it back on undo and sets it again on redo: a +/// preset shows the grid, and a grid definition can lock it. +#[test] +fn undo_takes_back_the_view_options_a_step_changed() { + let mut s = session(); + run(&mut s, "perspective.grid.preset", json!({"kind": 2})); + run(&mut s, "perspective.grid.show", json!({"visible": false})); + run(&mut s, "perspective.grid.preset", json!({"kind": 1})); + assert!(grid(&s).visible); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(!grid(&s).visible, "the preset showed the grid"); + s.execute("edit.redo", &json!({})).unwrap(); + assert!(grid(&s).visible); + let cell = grid(&s).cell; + run(&mut s, "perspective.grid.set", json!({"locked": true, "cell": cell + 10.0})); + assert!(grid(&s).locked); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!((grid(&s).locked, grid(&s).cell), (false, cell)); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!((grid(&s).locked, grid(&s).cell), (true, cell + 10.0)); + // An option the step left alone and changed after it stays as it is. + run(&mut s, "perspective.grid.snap", json!({"on": false})); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!((grid(&s).locked, grid(&s).snap), (false, false)); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!((grid(&s).locked, grid(&s).snap), (true, false)); +} + /// Lock Grid, Lock Station Point, Snap to Grid and Show Rulers refuse an `on` given as text or as /// another value that is not true or false: the grid and the undo history stay as they were. Null is /// read as the key left out, so it toggles the option. diff --git a/crates/engine/src/tests/prefs.rs b/crates/engine/src/tests/prefs.rs index 521d2eabde..3e1302d71d 100644 --- a/crates/engine/src/tests/prefs.rs +++ b/crates/engine/src/tests/prefs.rs @@ -109,6 +109,23 @@ fn grid_prefs_apply_to_open_documents() { assert_eq!((g.spacing, g.subdivisions), (36.0, 4)); } +/// The grid preferences are not an undo step in the documents they apply to, so undo and redo +/// leave the grid as the preferences set it. +#[test] +fn undo_and_redo_keep_the_grid_prefs() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 40})).unwrap(); + s.execute("prefs.set", &json!({"values": {"gridlineEvery": 36, "gridSubdivisions": 4}})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + let g = &s.doc().unwrap().doc.grid; + assert_eq!((g.spacing, g.subdivisions), (36.0, 4)); + s.execute("prefs.set", &json!({"values": {"gridlineEvery": 18, "gridSubdivisions": 3}})).unwrap(); + s.execute("edit.redo", &json!({})).unwrap(); + let g = &s.doc().unwrap().doc.grid; + assert_eq!((g.spacing, g.subdivisions), (18.0, 3)); +} + /// Guides & Grid › Gridline every and Subdivisions (#394): set with no document open, as the /// desktop app restores them at launch, they give `file.new`'s document their grid. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index a27f99feba..80cea993e4 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -699,7 +699,7 @@ ends the wait, so the sampler can be shown again. The BSDs and headless sessions | `transform` | `{ids?, dx?, dy?, rotate?, scale?, scaleX?, scaleY?, reflect?, shear?, origin?, copy?}` | Runs move, rotate, scale, reflect, shear in that order. `rotate` is in degrees counter-clockwise; a positive `shear` moves the top to the right. With `copy`, the first step duplicates. | | `create_graph` | `{type?, x, y, width, height, csv? \| series?, categories?, rows?}` | The nine Illustrator graph types: column, stacked column, bar, stacked bar, line, area, scatter, pie and radar. An empty CSV cell or a `null` in `rows` is a blank value; a number in straight quotes is a label. Edit later with `graph.setData` / `graph.setType` via `run_command`. `graph.column {design, columnType: vertical\|uniform\|repeating\|sliding, each, fractions: chop\|scale}` draws the columns or bars of the series picked with Group Selection (or `seriesIndexes`, or all of them) with a graph design saved by `graph.design`; with no `design` it returns the series' current design and options. Type in the design that holds a `%` followed by two digits shows each column's value, with at least the first digit's places before the decimal point and the second digit's places after it. | | `text_wrap` | `{ids?, offset?, invert?, release?}` | Area type below the objects (same layer) flows around them. `offset` is in points, from -1000 to 1000 (default 6). An offset outside that range or not a number, or an `invert` or `release` that is not true or false, is an error and changes nothing; `object.textWrap.make` and `object.textWrap.options` refuse the same values. | -| `undo` / `redo` | `{}` | Many calls that change nothing record no undo step, for example `object.align` with nothing to move, `object.move` by 0 without `copy` and `object.showAll` with nothing hidden. `undo` (`edit.undo`) after such a call undoes the step before it. `inspect_document` lists the undo steps as `history`. `run_command` with `edit.clearHistory` removes every undo and redo step of the active document and returns `{cleared}`, the number of steps removed; the document stays as it is, and the command records no undo step. `run_command` with `edit.newDocumentFromState` and `{index?, created?}` makes a new document holding the art as it was at that state and makes it the active document, and returns `{index, title}`. `index` is a row of the History panel, with 0 the oldest state kept, and an omitted or null `index` uses the current state. An `index` that names no state fails with `no history state N`, one that is not a whole number with `` `index` must be a whole number ``, and either changes nothing. `created` is File Info's created date in Unix seconds or null, and defaults to now. The new document takes the next `Untitled-N` name, is marked unsaved, has nothing selected and has no steps to undo or redo. It is out of symbol, opacity-mask and pattern editing, and the art drawn in a pattern's tile is stored in the pattern, as `object.pattern.done` stores it. The source document and its steps stay as they are, except that typing or a drag in progress is first kept as a step. When a command keeps a drag whose preview Real-time Drawing off had not applied yet (`edit.undo`, `edit.redo`, `edit.clearHistory`, `edit.newDocumentFromState` and the other commands that end a drag first), and applying that preview gives a warning, the command's result carries it as `previewWarning`, and as `warning` too when the command gives no warning of its own; the app's status bar shows `warning`. While the Type tool edits type, `undo` and `redo` put its caret, with no characters selected, at the end of the text the step changed: after the text it puts back or retypes, or where the text it takes out was. A step that changes no characters, such as a formatting change, leaves the caret and the selection where they are. | +| `undo` / `redo` | `{}` | Many calls that change nothing record no undo step, for example `object.align` with nothing to move, `object.move` by 0 without `copy` and `object.showAll` with nothing hidden. `undo` (`edit.undo`) after such a call undoes the step before it. Settings that change without an undo step stay as they are when `undo` or `redo` brings back a step that did not change them: the perspective grid's view options and active plane, the grid preferences (`gridlineEvery`, `gridSubdivisions`), the export settings (`assets.settings.set`), and the current brush and symbol. A step that changed one of them, such as a perspective grid preset that shows the grid, takes that change back. The point Automatic Plane Positioning holds comes back with the step, and is let go when the active plane kept is another one. `inspect_document` lists the undo steps as `history`. `run_command` with `edit.clearHistory` removes every undo and redo step of the active document and returns `{cleared}`, the number of steps removed; the document stays as it is, and the command records no undo step. `run_command` with `edit.newDocumentFromState` and `{index?, created?}` makes a new document holding the art as it was at that state and makes it the active document, and returns `{index, title}`. `index` is a row of the History panel, with 0 the oldest state kept, and an omitted or null `index` uses the current state. An `index` that names no state fails with `no history state N`, one that is not a whole number with `` `index` must be a whole number ``, and either changes nothing. `created` is File Info's created date in Unix seconds or null, and defaults to now. The new document takes the next `Untitled-N` name, is marked unsaved, has nothing selected and has no steps to undo or redo. It is out of symbol, opacity-mask and pattern editing, and the art drawn in a pattern's tile is stored in the pattern, as `object.pattern.done` stores it. The source document and its steps stay as they are, except that typing or a drag in progress is first kept as a step. When a command keeps a drag whose preview Real-time Drawing off had not applied yet (`edit.undo`, `edit.redo`, `edit.clearHistory`, `edit.newDocumentFromState` and the other commands that end a drag first), and applying that preview gives a warning, the command's result carries it as `previewWarning`, and as `warning` too when the command gives no warning of its own; the app's status bar shows `warning`. While the Type tool edits type, `undo` and `redo` put its caret, with no characters selected, at the end of the text the step changed: after the text it puts back or retypes, or where the text it takes out was. A step that changes no characters, such as a formatting change, leaves the caret and the selection where they are. | For example, create editable Japanese area type with the engine's vertical writing mode: From 8038d7bf3a9571ca5560dbbb07fb91e619dfad6e Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 17 Nov 2026 08:46:06 -0800 Subject: [PATCH 091/176] Symbols: drawn art keeps its evaluation as an Evaluated The drawn-art store that main added for clicks now keeps its entries as the shared Evaluated type, so a kept entry is also measured again when a symbol's 9-slice guides or natural size change. Evaluated::new builds an entry for both stores. --- crates/doc/src/hit.rs | 44 ++++++++++++++++++++----------------------- 1 file changed, 20 insertions(+), 24 deletions(-) diff --git a/crates/doc/src/hit.rs b/crates/doc/src/hit.rs index a0b6703726..eecd0bf0c8 100644 --- a/crates/doc/src/hit.rs +++ b/crates/doc/src/hit.rs @@ -214,18 +214,7 @@ fn keep<T>(store: &'static Store<T>, doc: &Document, n: &Node, inputs: u64, art: if size > LIVE_KEPT_SIZE || holds_placed(doc, n) { return; } - let symbols = doc.symbols.iter().map(|s| (s.name.clone(), s.art.clone())).collect(); - let e = Evaluated { - node: n.clone(), - symbols, - patterns: doc.patterns.clone(), - swatches: doc.swatches.clone(), - swatch_groups: doc.swatch_groups.clone(), - unknown: doc.unknown.clone(), - inputs, - art: art.clone(), - size, - }; + let e = Evaluated::new(doc, n, inputs, art, size); store.with_borrow_mut(|kept| { kept.insert(0, e); kept.truncate(most); @@ -238,6 +227,21 @@ fn keep<T>(store: &'static Store<T>, doc: &Document, n: &Node, inputs: u64, art: } impl<T> Evaluated<T> { + /// `art`, of size `size`, the evaluation of `n` in `doc` with inputs `inputs`, as they are now. + fn new(doc: &Document, n: &Node, inputs: u64, art: &Rc<T>, size: usize) -> Self { + Self { + node: n.clone(), + symbols: doc.symbols.iter().map(|s| (s.name.clone(), s.art.clone())).collect(), + patterns: doc.patterns.clone(), + swatches: doc.swatches.clone(), + swatch_groups: doc.swatch_groups.clone(), + unknown: doc.unknown.clone(), + inputs, + art: art.clone(), + size, + } + } + /// Is this the evaluation of `n` in `doc`, with inputs `inputs`, as they are now? fn is_of(&self, doc: &Document, n: &Node, inputs: u64) -> bool { self.inputs == inputs @@ -326,7 +330,7 @@ pub fn set_drawn_art(f: DrawnArt) { /// The art of an object found by [`drawn`] (none, or one object), with what it was found from, and /// the box round everything that art can paint. struct EvaluatedDrawn { - of: EvaluatedLive, + of: Evaluated<Vec<Node>>, reach: Option<Rect>, } @@ -379,7 +383,8 @@ fn plain<T>(mask: bool, f: impl FnOnce() -> T) -> T { /// nothing is registered, while a [`DrawnOff`] guard lives, for objects whose art is not evaluated /// ([`evaluates`]), and when nothing in `n`, nor the art of a symbol an instance in it shows, has a /// visible effect ([`draws_effects`]). The art is evaluated again when `n`, a symbol of the -/// document, its patterns, swatches or color groups, or the [`LiveInputs`] have changed since, and +/// document or its 9-slice guides or natural size, its patterns, swatches or color groups, or the +/// [`LiveInputs`] have changed since, and /// on every call while it holds a placed document ([`holds_placed`]). When the art kept is full, new /// art replaces as much other art as it needs room for, and art larger than [`LIVE_KEPT_SIZE`] is /// kept alone. @@ -401,16 +406,7 @@ fn drawn(symbols: &SymbolBoxes, n: &Node) -> Option<(Rc<Vec<Node>>, Option<Rect> let art = Rc::new(art.into_iter().collect::<Vec<_>>()); let size = art_size(&art).saturating_add(art_size(std::slice::from_ref(n))); if !holds_placed(doc, n) { - let of = EvaluatedLive { - node: n.clone(), - symbols: doc.symbols.iter().map(|s| (s.name.clone(), s.art.clone())).collect(), - patterns: doc.patterns.clone(), - swatches: doc.swatches.clone(), - swatch_groups: doc.swatch_groups.clone(), - inputs, - art: art.clone(), - size, - }; + let of = Evaluated::new(doc, n, inputs, &art, size); DRAWN.with_borrow_mut(|(kept, total)| { if let Some(old) = kept.remove(&n.id) { *total = total.saturating_sub(old.of.size); From 22d44c6fae716c3501316299662c5609daff03f0 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 17 Nov 2026 08:55:24 -0800 Subject: [PATCH 092/176] Tools: the Spiral and Arc tools refuse the values they would keep as others The Spiral tool's option check took a decay up to 150 while the tool keeps at most 99.99, so `tool.setOption` reported success with another value. It now takes 5 to 99.99. The Arc tool's lengths are checked from 1e-9 to 1e6, the lengths it keeps. The Spiral dialog sends a typed decay past 99.99 as 99.99, the decay the spiral was already drawn with. The Arc dialog test now expects OK to refuse a slope outside -100 to 100 and a Base Along other than X or Y, leaving the dialog open and the options unchanged. The Slope field and its slider keep a typed value within that range. --- crates/engine/src/tests/toolsettings.rs | 7 ++++- crates/tools/src/draw2/family.rs | 29 +++++++++++++++-- crates/ui-egui/src/dialogs/shapes.rs | 41 +++++++++++++++++-------- 3 files changed, 60 insertions(+), 17 deletions(-) diff --git a/crates/engine/src/tests/toolsettings.rs b/crates/engine/src/tests/toolsettings.rs index ee8f2aa6e7..fbde9edca7 100644 --- a/crates/engine/src/tests/toolsettings.rs +++ b/crates/engine/src/tests/toolsettings.rs @@ -246,7 +246,12 @@ fn spiral_decay_is_normalized_for_active_and_inactive_tools_and_preferences() { let mut s = session(); for active in [false, true] { select(&mut s, if active { "spiral" } else { "selection" }); - let options = s.set_tool_option_cmd(&json!({"tool": "spiral", "values": {"decay": 150, "segments": 4, "clockwise": false}})).unwrap(); + // A decay past the 99.99 % a spiral draws is refused, and nothing changes. + let before = s.tool_options_of("spiral"); + let refused = s.set_tool_option_cmd(&json!({"tool": "spiral", "values": {"decay": 150, "segments": 4, "clockwise": false}})); + assert_eq!(refused.err(), Some("tool `spiral`: `decay` must be a number from 5 to 99.99".to_string())); + assert_eq!(s.tool_options_of("spiral"), before); + let options = s.set_tool_option_cmd(&json!({"tool": "spiral", "values": {"decay": 99.99, "segments": 4, "clockwise": false}})).unwrap(); assert_eq!(options["decay"], json!(99.99)); assert_eq!(s.tool_options_of("spiral")["decay"], json!(99.99)); assert_eq!(s.prefs.tool_settings["spiral"]["decay"], json!(99.99)); diff --git a/crates/tools/src/draw2/family.rs b/crates/tools/src/draw2/family.rs index e6662630d6..06b7fa7105 100644 --- a/crates/tools/src/draw2/family.rs +++ b/crates/tools/src/draw2/family.rs @@ -519,11 +519,12 @@ impl Tool for FamilyTool { } let skew = vectorcraft_geom::shapes::GRID_SKEW_MAX; match key { - "lengthX" | "lengthY" | "width" | "height" => c::positive(key, v, 1e6), + "lengthX" | "lengthY" => c::number(key, v, 1e-9, 1e6), + "width" | "height" => c::positive(key, v, 1e6), "reference" => c::whole(key, v, 0, 8), "baseAlong" => c::one_of(key, v, &["x", "y", "X", "Y"]), "slope" => c::number(key, v, -100.0, 100.0), - "decay" => c::number(key, v, 5.0, 150.0), + "decay" => c::number(key, v, 5.0, 99.99), "segments" => c::whole(key, v, 2, 1000), "rows" | "concentric" | "columns" | "radial" => c::whole(key, v, 0, 999), "rowSkew" | "concentricSkew" | "columnSkew" | "radialSkew" => c::number(key, v, -skew, skew), @@ -532,7 +533,7 @@ impl Tool for FamilyTool { } } -/// Arc segment length from a dialog or preference value, at most 1e6 pt (as the option check +/// Arc segment length from a dialog or preference value, from 1e-9 to 1e6 pt (as the option check /// takes it). fn arc_length(v: &Value, current: f64) -> f64 { v.as_f64().filter(|n| n.is_finite()).map_or(current, |n| n.abs().clamp(1e-9, 1e6)) @@ -580,6 +581,28 @@ mod tests { } } + /// A number `tool.setOption` takes is kept as given, and a number the tool would keep as + /// another value is refused: `decay` past 99.99 is an error. + #[test] + fn family_tools_keep_the_numbers_their_option_check_takes() { + let tries = [-1e9, -150.0, -100.0, -1.0, 0.0, 1e-12, 0.5, 1.0, 2.0, 5.0, 8.0, 99.99, 100.0, 120.0, 150.0, 999.0, 1000.0, 1e6, 1e9]; + for id in ["arc", "spiral", "rectangularGrid", "polarGrid"] { + let defaults = FamilyTool::new(id).options(); + for (k, _) in defaults.as_object().into_iter().flatten().filter(|(_, v)| v.is_number()) { + for n in tries { + let mut t = FamilyTool::new(id); + if t.check_option(k, &json!(n)).is_ok() { + t.set_option(k, &json!(n)); + assert_eq!(t.options()[k].as_f64(), Some(n), "{id} `{k}` = {n}"); + } + } + } + } + let t = FamilyTool::new("spiral"); + assert_eq!(t.check_option("decay", &json!(120.0)).err(), Some("`decay` must be a number from 5 to 99.99".into())); + assert!(t.check_option("decay", &json!(99.99)).is_ok()); + } + #[test] fn normalized_spiral_decay_preserves_existing_capped_paths_within_roundoff() { for requested in [100.0, 150.0] { diff --git a/crates/ui-egui/src/dialogs/shapes.rs b/crates/ui-egui/src/dialogs/shapes.rs index be7193e978..e077ff1d26 100644 --- a/crates/ui-egui/src/dialogs/shapes.rs +++ b/crates/ui-egui/src/dialogs/shapes.rs @@ -270,8 +270,8 @@ fn arc_form(ui: &mut egui::Ui, d: &mut Dialog, unit: Unit) { const ARC_PREVIEW: egui::Vec2 = egui::vec2(160.0, 120.0); const ARC_PREVIEW_MARGIN: f32 = 12.0; -/// The arc the Arc tool draws with the options OK sets from `d` ([`arc_options`], kept as the tool -/// keeps them: a slope from -100 to 100, a Base Along of Y or else X), as `shape.arc` draws it +/// The arc the Arc tool draws with the options OK sets from `d` ([`arc_options`]; a slope past -100 +/// or 100, which OK refuses, is drawn at that end, and a Base Along other than Y along X), as `shape.arc` draws it /// with its reference point at the origin and General › Constrain Angle `constrain` (degrees) /// turning it about that point. `None` when a length or the slope is not finite. fn arc_preview_path(d: &Dialog, constrain: f64) -> Option<vectorcraft_geom::path::PathData> { @@ -523,7 +523,7 @@ fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> { "cx": x, "cy": y, "radius": d.f64("radius", 50.0).max(0.01), - "decay": d.f64("decay", 80.0).clamp(5.0, 150.0), + "decay": d.f64("decay", 80.0).clamp(5.0, 99.99), "segments": (d.f64("segments", 10.0) as u64).clamp(2, 1000), "clockwise": d.bool("clockwise"), }), @@ -646,6 +646,15 @@ mod tests { assert!(app.ui.dialog.is_none()); assert_eq!(app.session.doc().unwrap().doc.layers[0].children().unwrap().len(), 1); assert_eq!(app.session.tool_options_of("spiral"), json!({"decay": 65.0, "segments": 12, "clockwise": true})); + + // A decay typed past 99.99 % draws the spiral at 99.99 %, the most a spiral draws, and + // keeps that decay. + super::super::open_tool_dialog(&mut app, "spiral", json!({"x": 40.0, "y": 60.0})); + app.ui.dialog.as_mut().unwrap().fields.insert("decay".into(), json!(120.0)); + super::super::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(app.session.doc().unwrap().doc.layers[0].children().unwrap().len(), 2); + assert_eq!(app.session.tool_options_of("spiral")["decay"], json!(99.99)); } #[test] @@ -731,21 +740,27 @@ mod tests { } } - /// For values the Arc tool does not keep as typed, the picture shows the arc of the options OK - /// sets: the same picture as a dialog holding those options. + /// For values the dialog reads as other values, the picture shows the arc of the options OK + /// sets: the same picture as a dialog holding those options. A slope outside -100 to 100 or a + /// Base Along other than X or Y is refused: OK leaves the dialog open and keeps the options. #[test] fn the_arc_preview_shows_the_options_ok_sets() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); - for typed in [ - json!({"slope": 140.0}), - json!({"slope": -250.0}), - json!({"slope": "steep"}), - json!({"lengthX": "wide"}), - json!({"lengthY": null}), - json!({"baseAlong": "z"}), - json!({"reference": 12}), + for (typed, error) in [ + (json!({"slope": 140.0}), "`slope` must be a number from -100 to 100"), + (json!({"slope": -250.0}), "`slope` must be a number from -100 to 100"), + (json!({"baseAlong": "z"}), "`baseAlong` must be one of"), ] { + let before = app.session.tool_options_of("arc"); + app.ui.dialog = Some(arc_dialog(typed.clone())); + let r = super::super::confirm(&mut app); + assert!(r.as_ref().is_err_and(|e| e.contains(error)), "{typed}: {r:?}"); + assert!(app.ui.dialog.is_some(), "{typed}"); + assert_eq!(app.session.tool_options_of("arc"), before, "{typed}"); + app.ui.dialog = None; + } + for typed in [json!({"slope": "steep"}), json!({"lengthX": "wide"}), json!({"lengthY": null}), json!({"reference": 12})] { let d = arc_dialog(typed.clone()); let shown = arc_preview_path(&d, 0.0).expect("an arc"); app.ui.dialog = Some(d); From 55590e1131f937defc162580ab99deb35e12688e Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 17 Nov 2026 09:02:39 -0800 Subject: [PATCH 093/176] Symbols: Delete Symbol tests carry the dragged symbol's document The Delete Symbol drop tests that landed on main set the dragged symbol's document through the removed panel state key and built the old tuple payload. They now build PanelDrag::Symbol with the active document's uid, as the New Symbol tests do. --- crates/ui-egui/src/panels/symbols.rs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/panels/symbols.rs b/crates/ui-egui/src/panels/symbols.rs index a0741810d4..b98ec88c9a 100644 --- a/crates/ui-egui/src/panels/symbols.rs +++ b/crates/ui-egui/src/panels/symbols.rs @@ -2217,14 +2217,14 @@ mod tests { let ctx = egui::Context::default(); crate::theme::install_fonts(&ctx); // The payloads are set directly, as if dragged from this document's panel. - set_pstate(&ctx, DRAG_DOC, uid(&app)); + let document = uid(&app).expect("an active document"); let trash = button_rect(&ctx, &mut app, "Delete Symbol"); let elsewhere = trash.center() - vec2(0.0, 60.0); let cases = [ ("a library symbol", PanelDrag::LibrarySymbol { library: "basic-shapes".into(), name: "Leaf".into() }, trash.center()), ("art", PanelDrag::Art(vec![leaf]), trash.center()), - ("a stale name", PanelDrag::Symbol("Gone".into()), trash.center()), - ("a symbol released elsewhere", PanelDrag::Symbol("Dot".into()), elsewhere), + ("a stale name", PanelDrag::Symbol { document, name: "Gone".into() }, trash.center()), + ("a symbol released elsewhere", PanelDrag::Symbol { document, name: "Dot".into() }, elsewhere), ]; for (case, drag, at) in cases { egui::DragAndDrop::set_payload(&ctx, drag); @@ -2241,7 +2241,7 @@ mod tests { frame(&ctx, &mut app, vec![egui::Event::PointerMoved(tile), button(tile, true)]); frame(&ctx, &mut app, vec![egui::Event::PointerMoved(tile + vec2(40.0, 40.0))]); frame(&ctx, &mut app, vec![egui::Event::PointerMoved(tile + vec2(80.0, 80.0))]); - assert_eq!(egui::DragAndDrop::payload::<PanelDrag>(&ctx).as_deref(), Some(&PanelDrag::Symbol("Leaf".into()))); + assert_eq!(egui::DragAndDrop::payload::<PanelDrag>(&ctx).as_deref(), Some(&PanelDrag::Symbol { document, name: "Leaf".into() })); app.run("symbol.delete", json!({"name": "Leaf"})).unwrap(); let undo = app.session.active().unwrap().history.undo.len(); let out = frame_held(&ctx, &mut app, vec![egui::Event::PointerMoved(trash.center())], egui::Modifiers::NONE); @@ -2253,7 +2253,7 @@ mod tests { frame(&ctx, &mut app, vec![egui::Event::PointerMoved(tile), button(tile, true)]); frame(&ctx, &mut app, vec![egui::Event::PointerMoved(tile + vec2(40.0, 40.0))]); frame(&ctx, &mut app, vec![egui::Event::PointerMoved(tile + vec2(80.0, 80.0))]); - assert_eq!(egui::DragAndDrop::payload::<PanelDrag>(&ctx).as_deref(), Some(&PanelDrag::Symbol("Dot".into()))); + assert_eq!(egui::DragAndDrop::payload::<PanelDrag>(&ctx).as_deref(), Some(&PanelDrag::Symbol { document, name: "Dot".into() })); app.run("file.new", json!({"width": 300, "height": 200})).unwrap(); app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 30, "height": 30})).unwrap(); app.run("symbol.new", json!({"name": "Dot"})).unwrap(); From b4cd6b6fa0393a38e8f1c9a9134028d499239e53 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Mon, 16 Nov 2026 13:52:29 -0800 Subject: [PATCH 094/176] .ai save: read each embedded image's pixels once a save The .ai writer kept only the image it read last, so a document that placed two images in turn decoded each again at every placement. The writer now keeps every image it reads during a save, by the address of its data and its MIME type, up to 256 MiB of samples and 256 images, with the image read last kept beside them when they are full. The file written is unchanged; the tests compare the whole output and warnings with the old one-image policy. Two 2048 x 2048 images placed in turn 25 times each, release build, thread CPU time, median of 7 alternating runs: 3774 ms with 50 decodes before, 748 ms with 2 decodes after. --- crates/eps/src/ai_editing/tests.rs | 159 +++++++++++++++++++++ crates/eps/src/ai_editing/writer.rs | 10 +- crates/eps/src/ai_editing/writer/images.rs | 111 ++++++++++++-- 3 files changed, 267 insertions(+), 13 deletions(-) diff --git a/crates/eps/src/ai_editing/tests.rs b/crates/eps/src/ai_editing/tests.rs index f8e39a4048..3828bc3961 100644 --- a/crates/eps/src/ai_editing/tests.rs +++ b/crates/eps/src/ai_editing/tests.rs @@ -3811,6 +3811,165 @@ fn images_that_cant_be_decoded_are_mid_gray_boxes() { assert_eq!(paint(n.appearance.items[0].paint()), paint(&solid(Color::gray(0.5)))); } +/// A `w` × `h` RGB image whose pixels follow from `seed`, no two of its pixels gray. +fn seeded_png(seed: u32, (w, h): (u32, u32)) -> Vec<u8> { + let px = |x: u32, y: u32| { + let v = (x.wrapping_mul(73_856_093) ^ y.wrapping_mul(19_349_663) ^ seed.wrapping_mul(83_492_791)).to_le_bytes(); + image::Rgb([v[0], v[1] | 1, v[2] & 0xfe]) + }; + png_of(image::DynamicImage::ImageRgb8(image::RgbImage::from_fn(w, h, px))) +} + +/// A document placing `blobs` in turn on one layer, each `times` times: the first, the second and +/// so on, then the first again. Each blob is kept under `keys`' key at its index. +fn images_in_turn(blobs: &[ImageBlob], keys: &[&str], times: usize) -> Document { + let mut doc = Document::new(200.0, 100.0); + let layer = doc.layers[0].id; + for (blob, key) in blobs.iter().zip(keys) { + doc.images.insert((*key).to_string(), blob.clone()); + } + for i in 0..times * blobs.len() { + let key = keys[i % blobs.len()].to_string(); + let xf = Affine::translate((f64::from(u32::try_from(i).unwrap()), 10.0)) * Affine::scale(2.0); + let im = ImageObject { key, width: 4, height: 4, xf, link: None, placement: Default::default(), pixels: None }; + let node = Node::new(doc.alloc_id(), NodeKind::Image(Box::new(im))); + doc.insert(Some(layer), usize::MAX, node).unwrap(); + } + doc +} + +/// `doc` written keeping the pixels of each image read (`last_only` false) or of the image read +/// last alone, and how many times an image's pixels were read. +fn export_reading(doc: &Document, last_only: bool) -> (AiEditingOutput, usize) { + writer::LAST_SAMPLES_ONLY.with(|l| l.set(last_only)); + writer::SAMPLE_READS.with(|n| n.set(0)); + let out = export_ai_editing(doc, &opts()); + writer::LAST_SAMPLES_ONLY.with(|l| l.set(false)); + (out.unwrap(), writer::SAMPLE_READS.with(std::cell::Cell::get)) +} + +/// `doc` written both ways ([`export_reading`]), the files and warnings compared whole, and the +/// reads of each way. +fn reads_for_the_same_file(doc: &Document) -> (usize, usize) { + let (kept, kept_reads) = export_reading(doc, false); + let (last, last_reads) = export_reading(doc, true); + assert!(kept.program == last.program, "the files differ"); + assert_eq!(kept.header, last.header); + assert_eq!(kept.warnings, last.warnings); + (kept_reads, last_reads) +} + +/// Two images placed one after the other 25 times each are each read once in a save, and the file +/// is the same as when only the image read last is kept. +#[test] +fn images_placed_in_turn_are_read_once_a_save() { + // GUARDS: each image was read again whenever the other was placed between its copies. + let blobs = [ImageBlob::png(seeded_png(1, (4, 4))), ImageBlob::png(seeded_png(2, (4, 4)))]; + let doc = images_in_turn(&blobs, &["a", "b"], 25); + assert_eq!(reads_for_the_same_file(&doc), (2, 50)); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert_eq!(String::from_utf8_lossy(&out.program).matches("%AI5_BeginRaster").count(), 50); +} + +/// A document of one image placed many times reads it once, and one without images reads none. +#[test] +fn one_image_is_read_once_and_no_image_never() { + let doc = images_in_turn(&[ImageBlob::png(seeded_png(3, (4, 4)))], &["a"], 10); + assert_eq!(reads_for_the_same_file(&doc), (1, 1)); + assert_eq!(reads_for_the_same_file(&Document::new(200.0, 100.0)), (0, 0)); +} + +/// An image that can't be read, placed between copies of another, is read once too, and each copy +/// is still its gray outline with the same warning. +#[test] +fn an_image_that_cant_be_read_is_read_once_a_save() { + // GUARDS: an image that can't be read was read again whenever another image came between. + let blobs = [ImageBlob::png(b"not an image".to_vec()), ImageBlob::png(seeded_png(4, (4, 4)))]; + let doc = images_in_turn(&blobs, &["bad", "good"], 3); + assert_eq!(reads_for_the_same_file(&doc), (2, 6)); + let out = export_ai_editing(&doc, &opts()).unwrap(); + assert_eq!(out.warnings, [writer::IMAGES]); + assert_eq!(String::from_utf8_lossy(&out.program).matches("%AI5_BeginRaster").count(), 3); +} + +/// The same data under two MIME types is two images: each is read once, apart from the other. +#[test] +fn the_same_data_of_another_type_is_read_apart() { + let png = ImageBlob::png(seeded_png(5, (4, 4))); + let other = ImageBlob { mime: "image/x-other".into(), ..png.clone() }; + assert!(Arc::ptr_eq(&png.bytes, &other.bytes)); + let doc = images_in_turn(&[png, other], &["png", "other"], 3); + assert_eq!(reads_for_the_same_file(&doc), (2, 6)); +} + +/// Past the limits on the samples kept (bytes and images), an image is kept beside them in place +/// of the one before it, and the others are read again where they come: what is kept stays within +/// both limits, and the file is the same. +#[test] +fn images_past_the_limits_are_read_again_and_written_the_same() { + // Images of 48, 75 and 108 bytes of samples, then two of 48: 123 bytes and two images fit. + let sizes = [(4, 4), (5, 5), (6, 6), (4, 4), (4, 4)]; + let blobs: Vec<_> = (0u32..).zip(sizes).map(|(i, s)| ImageBlob::png(seeded_png(10 + i, s))).collect(); + let doc = images_in_turn(&blobs, &["a", "b", "c", "d", "e"], 3); + for (limits, kept_most, reads) in [((130, 8), (123, 2), 2 + 3 * 3), ((10_000, 3), (48 + 75 + 108, 3), 3 + 2 * 3)] { + writer::SAMPLE_LIMITS.with(|l| l.set(limits)); + writer::SAMPLES_KEPT.with(|k| k.set((0, 0, false))); + let (kept_reads, last_reads) = reads_for_the_same_file(&doc); + let (bytes, images, beside) = writer::SAMPLES_KEPT.with(std::cell::Cell::get); + writer::SAMPLE_LIMITS.with(|l| l.set((256 << 20, 256))); + assert!(bytes <= limits.0 && images <= limits.1, "{limits:?}: kept {bytes} bytes of {images} images"); + assert_eq!((bytes, images, beside), (kept_most.0, kept_most.1, true), "{limits:?}"); + assert_eq!((kept_reads, last_reads), (reads, 15), "{limits:?}"); + } +} + +/// The time this thread has run, and how it was measured. +fn thread_time() -> (std::time::Duration, &'static str) { + if let Some(ns) = std::fs::read_to_string("/proc/thread-self/schedstat").ok().and_then(|s| s.split_whitespace().next()?.parse::<u64>().ok()) { + return (std::time::Duration::from_nanos(ns), "thread CPU time"); + } + static START: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new(); + (START.get_or_init(std::time::Instant::now).elapsed(), "wall-clock time") +} + +/// The time to write two 2048 × 2048 images placed one after the other 25 times each, keeping the +/// pixels of each image read and of the image read last alone: the median of 7 runs of each, +/// alternating, with the files compared. Run with +/// `cargo test --release -p vectorcraft-eps --lib -- --ignored --nocapture images_placed_in_turn_are_written_quickly`. +#[test] +#[ignore = "timing"] +fn images_placed_in_turn_are_written_quickly() { + let blobs = [ImageBlob::png(seeded_png(1, (2048, 2048))), ImageBlob::png(seeded_png(2, (2048, 2048)))]; + let doc = images_in_turn(&blobs, &["a", "b"], 25); + let mut times = [vec![], vec![]]; + let mut files: [Option<Vec<u8>>; 2] = [None, None]; + let mut reads = [0, 0]; + let mut how = ""; + for _ in 0..7 { + for (k, last_only) in [false, true].into_iter().enumerate() { + let (start, h) = thread_time(); + let (out, n) = export_reading(&doc, last_only); + times[k].push(thread_time().0.saturating_sub(start)); + how = h; + reads[k] = n; + files[k].get_or_insert(out.program); + } + } + assert!(files[0] == files[1], "the files differ"); + assert_eq!(reads, [2, 50]); + for t in &mut times { + t.sort(); + } + let ms = |d: std::time::Duration| d.as_secs_f64() * 1000.0; + println!("50 placements of two 2048 x 2048 images, median of 7 runs ({how}):"); + println!("| pixels kept | images read | median (ms) | runs (ms) |"); + println!("|---|---:|---:|---|"); + for (k, label) in ["each image read", "the image read last"].into_iter().enumerate() { + let runs: Vec<String> = times[k].iter().map(|d| format!("{:.0}", ms(*d))).collect(); + println!("| {label} | {} | {:.0} | {} |", reads[k], ms(times[k][3]), runs.join(", ")); + } +} + #[test] fn sixteen_bit_images_are_written_at_eight_bits() { let mut doc = Document::new(200.0, 100.0); diff --git a/crates/eps/src/ai_editing/writer.rs b/crates/eps/src/ai_editing/writer.rs index bea247262b..6595f11ffd 100644 --- a/crates/eps/src/ai_editing/writer.rs +++ b/crates/eps/src/ai_editing/writer.rs @@ -35,7 +35,7 @@ pub(super) use texts::wraps_held; pub(super) use images::PAYLOAD; #[cfg(test)] -pub(super) use images::{IMAGE_DEPTH, IMAGES, LINKS_EMBEDDED}; +pub(super) use images::{IMAGE_DEPTH, IMAGES, LAST_SAMPLES_ONLY, LINKS_EMBEDDED, SAMPLE_LIMITS, SAMPLE_READS, SAMPLES_KEPT}; #[cfg(test)] pub(super) use paints::{GRADIENT_HUE, GRADIENT_MIX, GRADIENT_SHAPES, GRADIENTS, STOP_LINKS, SWATCH_PLACEMENT, free_gradient_name}; #[cfg(test)] @@ -308,9 +308,9 @@ pub(super) struct Writer<'a> { /// How many more envelopes and images with a Warp may be written live: as many as the reader /// checks in one file ([`crate::import::ENVELOPE_CHECKS`]), which it spends on both. checks_left: usize, - /// The image read last and its pixels ([`images::Samples::of`], `None` when they can't be - /// read): the pieces of a warped image, which follow one another, read them once. - last_samples: Option<(vectorcraft_doc::ImageBlob, Option<images::Read>)>, + /// The images read so far and their pixels: an image placed again, and each piece of a warped + /// image, is read once. + read_samples: images::SampleCache, /// The images written whole so far, by the address of their data (which each entry keeps), each /// with the index of its samples in [`Self::payloads`]. whole_images: HashMap<usize, (Arc<Vec<u8>>, usize)>, @@ -401,7 +401,7 @@ impl<'a> Writer<'a> { definition_links: 0, definition_symbol_nodes: 0, max_objects: crate::import::MAX_EDITING_OBJECTS, - last_samples: None, + read_samples: images::SampleCache::default(), whole_images: HashMap::new(), shown: vec![], windowed: None, diff --git a/crates/eps/src/ai_editing/writer/images.rs b/crates/eps/src/ai_editing/writer/images.rs index 3813deccf9..408827663f 100644 --- a/crates/eps/src/ai_editing/writer/images.rs +++ b/crates/eps/src/ai_editing/writer/images.rs @@ -1,6 +1,9 @@ //! Images: embedded ones as a raster with its samples, linked ones as a placed file with a preview //! (see [`crate::ai_editing`] for the form). +#[cfg(test)] +use std::cell::Cell; +use std::collections::HashMap; use std::fmt::Write; use std::sync::Arc; @@ -30,6 +33,87 @@ pub(super) const SAMPLES_LINE: &str = "XI\u{1}"; /// An image's pixels as the data holds them, and whether it had 16 bits a channel ([`Samples::of`]). pub(super) type Read = Arc<(Samples, bool)>; +/// The most bytes of samples a save keeps read ([`SampleCache`]): color and alpha together. +const KEPT_SAMPLE_BYTES: usize = 256 << 20; +/// The most images whose samples a save keeps read ([`SampleCache`]), those that can't be read +/// included. +const KEPT_IMAGES: usize = 256; + +#[cfg(test)] +thread_local! { + /// How many times [`Samples::of`] has read an image on this thread. + pub(in crate::ai_editing) static SAMPLE_READS: Cell<usize> = const { Cell::new(0) }; + /// Whether [`Writer::samples`] keeps only the image read last on this thread, to compare its + /// file with the one [`SampleCache`] gives. + pub(in crate::ai_editing) static LAST_SAMPLES_ONLY: Cell<bool> = const { Cell::new(false) }; + /// The bytes of samples and the images [`SampleCache`] keeps at most on this thread. + pub(in crate::ai_editing) static SAMPLE_LIMITS: Cell<(usize, usize)> = const { Cell::new((KEPT_SAMPLE_BYTES, KEPT_IMAGES)) }; + /// The most bytes of samples and images a [`SampleCache`] kept on this thread, and whether one + /// held an image beside them. + pub(in crate::ai_editing) static SAMPLES_KEPT: Cell<(usize, usize, bool)> = const { Cell::new((0, 0, false)) }; +} + +/// The bytes of samples and the images [`SampleCache`] keeps at most. +#[cfg(not(test))] +const fn sample_limits() -> (usize, usize) { + (KEPT_SAMPLE_BYTES, KEPT_IMAGES) +} + +#[cfg(test)] +fn sample_limits() -> (usize, usize) { + SAMPLE_LIMITS.with(Cell::get) +} + +/// The images read during a save and their pixels ([`Samples::of`], `None` when they can't be +/// read), so that an image placed again is read once: up to [`KEPT_IMAGES`] images and +/// [`KEPT_SAMPLE_BYTES`] of samples, and beside them the image read last that they have no room +/// for. An image is known by the address of its data and its MIME type; each entry keeps the +/// image, so no other data takes that address while the entry is kept. +#[derive(Default)] +pub(super) struct SampleCache { + /// By the address of the image's data, each image with that data and its pixels. + kept: HashMap<usize, Vec<(ImageBlob, Option<Read>)>>, + /// How many images `kept` holds. + images: usize, + /// The bytes of samples `kept` holds. + bytes: usize, + /// The image read last that `kept` had no room for, and its pixels. + last: Option<(ImageBlob, Option<Read>)>, +} + +/// Whether `a` is the image `b`: the same data and MIME type. +fn same_image(a: &ImageBlob, b: &ImageBlob) -> bool { + Arc::ptr_eq(&a.bytes, &b.bytes) && a.mime == b.mime +} + +impl SampleCache { + /// The pixels kept for `blob`, when it was read. + fn get(&self, blob: &ImageBlob) -> Option<Option<Read>> { + let kept = self.kept.get(&(Arc::as_ptr(&blob.bytes) as usize)).and_then(|v| v.iter().find(|(b, _)| same_image(b, blob))); + kept.or(self.last.as_ref().filter(|(b, _)| same_image(b, blob))).map(|(_, read)| read.clone()) + } + + /// Keep `read`, the pixels of `blob`: with the others while both limits allow, else beside them + /// in place of the image read last. + fn keep(&mut self, blob: &ImageBlob, read: Option<Read>) { + let size = read.as_deref().map_or(0, |(s, _)| s.color.len().saturating_add(s.alpha.as_ref().map_or(0, Vec::len))); + let (most_bytes, most_images) = sample_limits(); + match self.bytes.checked_add(size).filter(|b| *b <= most_bytes) { + Some(bytes) if self.images < most_images => { + self.bytes = bytes; + self.images += 1; + self.kept.entry(Arc::as_ptr(&blob.bytes) as usize).or_default().push((blob.clone(), read)); + } + _ => self.last = Some((blob.clone(), read)), + } + #[cfg(test)] + SAMPLES_KEPT.with(|k| { + let (b, n, last) = k.get(); + k.set((b.max(self.bytes), n.max(self.images), last || self.last.is_some())); + }); + } +} + /// A copy of an image written as the part of it that its regions show ([`Writer::image`]). pub(super) struct Windowed { /// Where its raster is in the body. @@ -61,6 +145,8 @@ impl Samples { /// or RGB samples, with an alpha channel when they need one. `None` when they can't be decoded or are more than /// [`MAX_PIXELS`]; the flag is set when the image had 16 bits a channel. fn of(blob: &ImageBlob) -> Option<(Samples, bool)> { + #[cfg(test)] + SAMPLE_READS.with(|n| n.set(n.get() + 1)); // The header's size is checked before the inks are decoded. if blob.is_cmyk() && blob.header_size().is_some_and(|(w, h)| u64::from(w) * u64::from(h) <= MAX_PIXELS) @@ -301,17 +387,26 @@ impl Writer<'_> { ); } - /// The pixels of `blob` ([`Samples::of`]), read once for images that follow one another with - /// the same data. + /// The pixels of `blob` ([`Samples::of`]), read once in a save for each image the + /// [`SampleCache`] has room for. fn samples(&mut self, blob: &ImageBlob) -> Option<Read> { - if let Some((last, read)) = &self.last_samples - && Arc::ptr_eq(&last.bytes, &blob.bytes) - && last.mime == blob.mime - { - return read.clone(); + #[cfg(test)] + if LAST_SAMPLES_ONLY.with(Cell::get) { + if let Some((last, read)) = &self.read_samples.last + && Arc::ptr_eq(&last.bytes, &blob.bytes) + && last.mime == blob.mime + { + return read.clone(); + } + let read = Samples::of(blob).map(Arc::new); + self.read_samples.last = Some((blob.clone(), read.clone())); + return read; + } + if let Some(read) = self.read_samples.get(blob) { + return read; } let read = Samples::of(blob).map(Arc::new); - self.last_samples = Some((blob.clone(), read.clone())); + self.read_samples.keep(blob, read.clone()); read } From 8d7708f1c0760b8ffdc1367ce041f6b5af64febb Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 17 Nov 2026 09:04:01 -0800 Subject: [PATCH 095/176] Graphic Styles: art or an appearance dropped on a style with Alt replaces that style Art dragged off the canvas, or the Appearance panel's thumbnail, dropped on a style in the Graphic Styles panel with Alt held runs graphicStyle.redefine with that style's name and the object's id (the first object of the art), in one undo step. The style keeps its name, id and place in the list, and the art still linked to it takes the new look. The style is outlined while one is held over it with Alt. An object already linked to the style with its look changes nothing. Without Alt the drop still makes a new style, and a style dropped on a style still moves it. --- crates/engine/src/cmd/style.rs | 8 +- crates/ui-egui/src/panels/graphic_styles.rs | 129 +++++++++++++++++++- crates/ui-egui/src/widgets/drag.rs | 6 +- docs/mcp.md | 5 +- docs/target-app-parity.md | 1 + 5 files changed, 143 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/style.rs b/crates/engine/src/cmd/style.rs index 33c9ec67bb..76287e490d 100644 --- a/crates/engine/src/cmd/style.rs +++ b/crates/engine/src/cmd/style.rs @@ -318,8 +318,14 @@ impl Session { /// it is still linked (still has that style's look). A graph series group that holds nothing of its own stands /// for the topmost path directly inside it, which a style applied to the group links. pub fn selection_graphic_style(&self) -> Option<(&GraphicStyle, bool)> { + self.graphic_style_of(*self.active()?.selection.subjects().first()?) + } + + /// The graphic style of object `id` of the active document, as [`Self::selection_graphic_style`] + /// gives it for the first selected object. + pub fn graphic_style_of(&self, id: NodeId) -> Option<(&GraphicStyle, bool)> { let st = self.active()?; - let n = super::appearance::look_holder(&st.doc, st.doc.node(*st.selection.subjects().first()?)?); + let n = super::appearance::look_holder(&st.doc, st.doc.node(id)?); let g = st.doc.graphic_style_by_id(n.extras().graphic_style?)?; Some((g, in_sync(n, g))) } diff --git a/crates/ui-egui/src/panels/graphic_styles.rs b/crates/ui-egui/src/panels/graphic_styles.rs index 59d518cb1b..6ff2243cfb 100644 --- a/crates/ui-egui/src/panels/graphic_styles.rs +++ b/crates/ui-egui/src/panels/graphic_styles.rs @@ -6,7 +6,9 @@ //! double-click opens Graphic Style Options. Dragging a style moves it in the list, applies it //! to the art it is dropped on (`canvas::panel_drop`), or, dropped on New Graphic Style, adds a //! copy of it and of the styles highlighted with it at the end of the list; art dragged off the -//! canvas or the Appearance panel's thumbnail dropped on the panel becomes a new style. Holding the right button on a style +//! canvas or the Appearance panel's thumbnail dropped on the panel becomes a new style, and +//! dropped on a style with Alt held replaces that style with its look (`graphicStyle.redefine`). +//! Holding the right button on a style //! shows it large, on the selected object when there is one. The Control bar's Style picker lists //! the same tiles ([`picker`]). Graphic style libraries open in library panels //! ([`GraphicStyleLibraries`]). @@ -364,6 +366,8 @@ struct Events { moved: Option<(String, usize)>, /// Art or an appearance dropped on the panel: a new style from this object. new_from: Option<NodeId>, + /// Art or an appearance dropped on a style with Alt held: the style takes this object's look. + replaced: Option<(String, NodeId)>, /// The style the right button is held on. large: Option<usize>, /// A style is dragged over a tile or row. @@ -383,10 +387,26 @@ fn clicked(ui: &Ui, resp: &Response, name: &str) -> Option<Click> { /// Clicks, drags and the right button on the tile or row `resp` of style `i` of `d` (`list`: rows /// stack downwards). A drag from it carries the style ([`PanelDrag::GraphicStyle`]); a style -/// dragged over it lands before or after it by the pointer's half. +/// dragged over it lands before or after it by the pointer's half. Art (its first object) or the +/// Appearance panel's thumbnail held over it with Alt outlines it, and released there replaces the +/// style with that object's look; without Alt it is left to the list ([`zone_input`]). fn cell_input(ui: &Ui, resp: &Response, d: &Document, i: usize, list: bool, ev: &mut Events) { let name = &d.graphic_styles[i].name; widgets::drag_source(ui, resp, || PanelDrag::GraphicStyle(name.clone())); + let source = resp.dnd_hover_payload::<PanelDrag>().and_then(|drag| match &*drag { + PanelDrag::Art(ids) => ids.first().copied(), + PanelDrag::Appearance(id) => Some(*id), + _ => None, + }); + if let Some(id) = source + && alt_held(ui) + { + ev.over = true; + widgets::drop_target_outline(ui, resp.rect); + if resp.dnd_release_payload::<PanelDrag>().is_some() { + ev.replaced = Some((name.clone(), id)); + } + } if let Some(drag) = resp.dnd_hover_payload::<PanelDrag>() && let PanelDrag::GraphicStyle(moving) = &*drag { @@ -505,6 +525,12 @@ fn act(app: &mut VectorcraftApp, ui: &Ui, s: &Shown, ev: Events, picker: bool) { if let Some(id) = ev.new_from { run(app, "graphicStyle.new", json!({ "id": id.0 })); } + // An object that is linked to the style and still has its look leaves the style as it is. + if let Some((name, id)) = ev.replaced + && !app.session.graphic_style_of(id).is_some_and(|(g, linked)| linked && g.name == name) + { + run(app, "graphicStyle.redefine", json!({ "name": name, "id": id.0 })); + } match ev.click { Some(Click::Pick(name, _)) if picker => { app.run("graphicStyle.apply", json!({"name": name, "add": alt_held(ui)})).ok(); @@ -1432,6 +1458,105 @@ mod tests { } } + /// Art or the Appearance panel's thumbnail dropped on a style with Alt held replaces that style + /// with the object's look, in one undo step: the style keeps its name, its place and its id, the + /// objects still linked to it take the new look, and the object becomes linked. The style is + /// outlined while one is held over it with Alt. Without Alt the drop makes a new style; a style + /// dragged with Alt still only moves; an object linked to the style with its look, an empty art + /// drag and an object that is gone change nothing and record no undo step. + #[test] + fn art_or_an_appearance_dropped_on_a_style_with_alt_replaces_that_style() { + let mut app = app(); + let rect = app.session.active().unwrap().doc.layers[0].children().unwrap()[0].id; + app.run("paint.setFill", json!({"color": "#ff0000", "ids": [rect.0]})).unwrap(); + app.run("graphicStyle.new", json!({"name": "Red", "id": rect.0})).unwrap(); + app.run("graphicStyle.move", json!({"name": "Red", "to": 0})).unwrap(); + app.run("shape.ellipse", json!({"x": 60, "y": 60, "width": 20, "height": 20})).unwrap(); + let oval = app.session.active().unwrap().selection.objects[0]; + app.run("paint.setFill", json!({"color": "#00ff00", "ids": [oval.0]})).unwrap(); + let ctx = egui::Context::default(); + let screen = Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(260.0, 600.0))); + // One frame of the panel with `events` and `modifiers` held: whether a drop-target outline + // the size of one style's tile or row is drawn around `at`. + let frame_at = |app: &mut VectorcraftApp, at: egui::Pos2, events: Vec<egui::Event>, modifiers: egui::Modifiers| { + let events = std::iter::once(egui::Event::ModifiersChanged(modifiers)).chain(events).collect(); + let mut out = ctx.run_ui(egui::RawInput { screen_rect: screen, events, ..Default::default() }, |ui| show(app, ui)); + out.textures_delta.clear(); + let accent = Tokens::get(&ctx).accent; + out.shapes.iter().any(|c| match &c.shape { + egui::Shape::Rect(r) => r.stroke.width == 1.5 && r.stroke.color == accent && r.rect.contains(at) && r.rect.height() < 45.0, + _ => false, + }) + }; + let release = |at: egui::Pos2, modifiers: egui::Modifiers| { + let up = egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed: false, modifiers }; + vec![egui::Event::PointerMoved(at), up] + }; + let (none, alt) = (egui::Modifiers::default(), egui::Modifiers::ALT); + let doc = |app: &VectorcraftApp| app.session.active().unwrap().doc.clone(); + let steps = |app: &VectorcraftApp| app.session.doc().unwrap().history.undo.len(); + let red = doc(&app).graphic_style("Red").unwrap().clone(); + let green = doc(&app).node(oval).unwrap().appearance.fill_paint(); + assert_ne!(red.appearance.fill_paint(), green); + // The first style: the top of the list's first row, or its first tile. + for (view, at) in [(View::SmallList, pos2(60.0, 9.0)), (View::Thumbnail, pos2(20.0, 20.0))] { + app.ui.graphic_styles_view = view; + frame_at(&mut app, at, vec![], none); + for payload in [PanelDrag::Art(vec![oval]), PanelDrag::Appearance(oval)] { + let n = names(&app); + let before = steps(&app); + // Held over the style with Alt it is outlined; without Alt it is not. + egui::DragAndDrop::set_payload(&ctx, payload.clone()); + assert!(!frame_at(&mut app, at, vec![egui::Event::PointerMoved(at)], none), "{view:?} {payload:?}: no outline without Alt"); + assert!(frame_at(&mut app, at, vec![egui::Event::PointerMoved(at)], alt), "{view:?} {payload:?}: outlined with Alt"); + assert_eq!(names(&app), n, "{view:?} {payload:?}: holding it there changes nothing"); + // Released there with Alt: Red takes the oval's look and keeps its name, place and id. + frame_at(&mut app, at, release(at, alt), alt); + let d = doc(&app); + assert_eq!(names(&app), n, "{view:?} {payload:?}"); + let g = d.graphic_style("Red").unwrap(); + assert_eq!((g.id, g.appearance.fill_paint()), (red.id, green.clone()), "{view:?} {payload:?}"); + assert_eq!(d.node(rect).unwrap().appearance.fill_paint(), green, "{view:?} {payload:?}: the linked rectangle follows"); + assert_eq!(d.node(rect).unwrap().extras().graphic_style, Some(red.id)); + assert_eq!(d.node(oval).unwrap().extras().graphic_style, Some(red.id), "{view:?} {payload:?}: the oval is linked"); + assert_eq!(steps(&app), before + 1, "{view:?} {payload:?}: one undo step"); + app.run("edit.undo", json!({})).unwrap(); + let d = doc(&app); + assert_eq!(d.graphic_style("Red").unwrap().appearance, red.appearance, "{view:?} {payload:?}: undo restores the style"); + assert_eq!(d.node(oval).unwrap().extras().graphic_style, None); + assert_eq!(d.node(rect).unwrap().appearance.fill_paint(), red.appearance.fill_paint()); + } + + // Without Alt the oval becomes a new style at the end, and Red stays as it was. + let n = names(&app); + egui::DragAndDrop::set_payload(&ctx, PanelDrag::Art(vec![oval])); + frame_at(&mut app, at, release(at, none), none); + assert_eq!(names(&app).len(), n.len() + 1, "{view:?}"); + assert_eq!(doc(&app).graphic_style("Red").unwrap().appearance, red.appearance, "{view:?}"); + app.run("edit.undo", json!({})).unwrap(); + + // A style dragged onto Red with Alt moves and replaces nothing. + let last = n.last().unwrap().clone(); + egui::DragAndDrop::set_payload(&ctx, PanelDrag::GraphicStyle(last.clone())); + frame_at(&mut app, at, release(at, alt), alt); + assert_eq!(names(&app)[0], last, "{view:?}"); + assert_eq!(doc(&app).graphic_style("Red").unwrap().appearance, red.appearance, "{view:?}"); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(names(&app), n, "{view:?}"); + + // The rectangle that is linked to Red with its look, an empty drag of art and an object + // that is gone change nothing and record nothing. + let before = steps(&app); + for payload in [PanelDrag::Art(vec![rect]), PanelDrag::Appearance(rect), PanelDrag::Art(vec![]), PanelDrag::Art(vec![NodeId(9999)])] { + egui::DragAndDrop::set_payload(&ctx, payload.clone()); + frame_at(&mut app, at, release(at, alt), alt); + assert_eq!(names(&app), n, "{view:?} {payload:?}"); + assert_eq!(doc(&app).graphic_style("Red").unwrap().appearance, red.appearance, "{view:?} {payload:?}"); + assert_eq!(steps(&app), before, "{view:?} {payload:?}"); + } + } + } + #[test] fn shift_click_selects_a_range_and_cmd_click_adds_or_removes_one_style() { let mut app = app(); diff --git a/crates/ui-egui/src/widgets/drag.rs b/crates/ui-egui/src/widgets/drag.rs index a3df5a4098..d801bcfa14 100644 --- a/crates/ui-egui/src/widgets/drag.rs +++ b/crates/ui-egui/src/widgets/drag.rs @@ -13,13 +13,15 @@ pub enum PanelDrag { /// it is dropped. Paint { paint: Paint, params: serde_json::Value, rows: Option<SwatchRows>, library: Option<(String, String)> }, /// The Appearance panel's thumbnail: art it is dropped on takes object `0`'s appearance - /// (`appearance.copyFrom`); the Graphic Styles panel makes a style of it. + /// (`appearance.copyFrom`); the Graphic Styles panel makes a style of it, or with Alt held + /// replaces the style it is dropped on with it (`graphicStyle.redefine`). Appearance(vectorcraft_doc::NodeId), /// A Graphic Styles panel style: art it is dropped on takes it (`graphicStyle.apply` with its /// `ids`); the panel moves it to where it is dropped. GraphicStyle(String), /// The selected art, dragged off the canvas with the Selection tool: the Graphic Styles panel - /// makes a style of the first object (`graphicStyle.new`), the Symbols panel a symbol of it all + /// makes a style of the first object (`graphicStyle.new`), or with Alt held replaces the style + /// it is dropped on with that object's look (`graphicStyle.redefine`), the Symbols panel a symbol of it all /// (`symbol.new`), the Swatches panel a pattern swatch of a copy (`object.pattern.make`) and the /// Brushes panel an Art brush (`brush.new`). Art(Vec<vectorcraft_doc::NodeId>), diff --git a/docs/mcp.md b/docs/mcp.md index 0fd0c9231c..246727af50 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -4287,7 +4287,10 @@ A graphic style holds an appearance (fills, strokes, effects) plus opacity, blen object's, type its characters'). `graphicStyle.apply {name, ids?}` gives the objects the style and links them; `add: true` adds the style on top of the existing appearance instead. Linked objects stay linked while they keep the style's look: editing their appearance or transparency breaks the link, and `graphicStyle.redefine {name?, id?}` -updates only the objects still linked. The art of a column or marker design in a graph series is never linked: +updates only the objects still linked. Art dragged off the canvas, or the Appearance panel's thumbnail, dropped on a +style in the Graphic Styles panel with Alt held runs `graphicStyle.redefine` with that style's `name` and the object's +`id` (the first object of the art); an object already linked to the style with its look changes nothing. The art of a +column or marker design in a graph series is never linked: `graphicStyle.new` can make a style from it, and `graphicStyle.redefine` leaves its look as it was and unlinks it, whether it is the source or a linked object. `graphicStyle.list` returns each style with the ids linked to it and the style of the first selected object; `select.same.graphicStyle` selects an object's fellow users. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index c51ae4e88f..a13d796d9f 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1796,6 +1796,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur In the Graphic Styles panel, Shift-click selects a range of styles and Ctrl/Cmd-click adds or removes one. A graphic style dragged onto the Graphic Styles panel's New Graphic Style button is duplicated, as the panel menu's Duplicate Graphic Style does, and both put the copy at the end of the list, as the help page describes ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=391)). VectorCraft's own rules: the button takes the drop with no art selected; a dragged style that is highlighted brings the other highlighted styles, copied in panel order in one undo step, and the copies are highlighted; the copy is named `<name> copy`, with a number when that is taken, and no art is linked to it (`a_style_dropped_on_new_graphic_style_is_duplicated_at_the_end` in `crates/ui-egui/src/panels/graphic_styles.rs`, `tests::styles::duplicate_puts_the_copy_at_the_end_of_the_list_in_one_undo_step`). A graphic style dragged onto the Graphic Styles panel's Delete Graphic Style button is deleted, which the help page gives as another way to delete a style besides the panel menu's Delete Graphic Style; art that used the style keeps its look and is no longer linked to it ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=392)). VectorCraft's own rules: the drop asks first as the button does, and with Alt held it deletes without asking; the button takes the drop with no style highlighted; a dragged style that is highlighted brings the other highlighted styles, deleted in one undo step (`a_style_dropped_on_delete_graphic_style_is_deleted_as_the_button_deletes` in `crates/ui-egui/src/panels/graphic_styles.rs`). + The Appearance panel's thumbnail dropped on a graphic style with Alt held replaces that style with the look of the object the panel shows; the style keeps its name and the art that uses it takes the new look, as the help page describes ([the help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=568)). VectorCraft's own rules: art dragged off the canvas does the same with its first object; the style keeps its place in the list, is outlined while one is held over it with Alt, and the replacement is one undo step; an object already linked to the style with its look changes nothing; without Alt the drop makes a new style (`art_or_an_appearance_dropped_on_a_style_with_alt_replaces_that_style` in `crates/ui-egui/src/panels/graphic_styles.rs`). In the Graphic Styles panel's thumbnail and list views, a style with no fill and no stroke, one with only effects or transparency included, shows its preview shape with a black outline, a white fill and a red slash, as the help page describes for the panel's thumbnails ([Graphic styles](https://helpx.adobe.com/illustrator/using/graphic-styles.html)); its effects still draw on that shape. The Control bar's Style picker and chip, graphic style library panels and the large preview on the selected object show the same marker. A fill or stroke row that paints None does not count as a fill or stroke, and a hidden row or one with zero opacity does; these rules, the marker outside the panel's thumbnails and the slash's direction and size are VectorCraft's own (`a_style_with_no_fill_and_no_stroke_shows_an_outlined_shape_and_a_red_slash` in `crates/ui-egui/src/panels/graphic_styles.rs`). Applying a style to several objects, and Redefine Graphic Style, give the objects one shared copy of the style's appearance instead of a copy each; an object that is edited later gets its own copy, and an object whose placed gradients are fitted to its own bounds gets its own. The undo history's memory estimate counts a shared appearance once. Saved files are unchanged (`crates/engine/src/tests/styles.rs`). - **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). From 9e18b39ec671d2ea034d29a9e84fbf433b753aca Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 17 Nov 2026 09:15:14 -0800 Subject: [PATCH 096/176] Save PDF: choosing PDF/X-3 or PDF/X-4 unsets Profile inclusion Profile inclusion is disabled with a standard. A Don't Include Profiles choice made before picking PDF/X-3 or PDF/X-4 stayed in the dialog and wrote every CMYK color as DeviceCMYK, which the PDF/X note does not describe. Choosing either standard now sets it back to unset. --- crates/ui-egui/src/dialogs/save_pdf.rs | 6 +++++- crates/ui-egui/src/dialogs/save_pdf/tests.rs | 15 +++++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/dialogs/save_pdf.rs b/crates/ui-egui/src/dialogs/save_pdf.rs index e07980196d..048861d799 100644 --- a/crates/ui-egui/src/dialogs/save_pdf.rs +++ b/crates/ui-egui/src/dialogs/save_pdf.rs @@ -452,7 +452,8 @@ pub(super) fn section_list(ui: &mut egui::Ui, d: &mut Dialog, sections: &[&str], /// What choosing `standard` changes: the compatibility, to its version unless it allows the one /// chosen, and off what files of a standard can't have (editing data, passwords; layers in PDF/X-1a -/// and PDF/X-3). +/// and PDF/X-3). In PDF/X-3 and PDF/X-4, Profile inclusion goes back to unset: the picker is +/// disabled there, and `none` would write every CMYK color as DeviceCMYK. fn standard_chosen(d: &mut Dialog, standard: Standard) { if choice::<Compatibility>(d, "compatibility").is_some_and(|c| !standard.allows(c)) { set(d, "compatibility", json!(standard.version().id())); @@ -466,6 +467,9 @@ fn standard_chosen(d: &mut Dialog, standard: Standard) { if !standard.allows_layers() { set(d, "createLayers", json!(false)); } + if standard.is_pdfx() && !standard.cmyk_only() { + set(d, "output.profiles", json!(vectorcraft_pdf::UNSET_CHOICE)); + } } /// The Preset row (the presets, built-in and saved, and Save Preset…) and, while Save Preset… diff --git a/crates/ui-egui/src/dialogs/save_pdf/tests.rs b/crates/ui-egui/src/dialogs/save_pdf/tests.rs index 656d88b870..8967e13977 100644 --- a/crates/ui-egui/src/dialogs/save_pdf/tests.rs +++ b/crates/ui-egui/src/dialogs/save_pdf/tests.rs @@ -537,6 +537,21 @@ fn choosing_a_pdfx_standard_sets_its_version_and_writes_the_standard() { assert_eq!((get(d, "compatibility"), get(d, "createLayers")), (&json!("1.6"), &json!(true))); } +/// Profile inclusion is disabled with a standard, so choosing PDF/X-3 or PDF/X-4 sets it back to +/// unset: a `none` chosen before would write every CMYK color as DeviceCMYK. +#[test] +fn choosing_pdfx3_or_pdfx4_unsets_profile_inclusion() { + let (mut app, _, _) = app(); + for standard in [Standard::PdfX3, Standard::PdfX4] { + app.run("ui.savePdfDialog", json!({"path": "/tmp/x.pdf", "output": {"profiles": "none"}})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + assert_eq!(get(d, "output.profiles"), &json!("none")); + set(d, "standard", json!(standard.id())); + standard_chosen(d, standard); + assert_eq!(get(d, "output.profiles"), &json!(vectorcraft_pdf::UNSET_CHOICE), "{}", standard.id()); + } +} + /// "Write pages longer than 200 in at full size in points" is enabled only without a standard, at /// PDF 1.5 and later: PDF/X files and PDF 1.3 and 1.4 files write long pages in points anyway, and /// PDF/A files keep the `UserUnit`. From ea782ca87e68045227ee537bd6abcfbd337cfdc9 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 17 Nov 2026 09:22:26 -0800 Subject: [PATCH 097/176] Swatches: a user swatch whose name starts with [ can be deleted and edited The panel's Delete Swatch and Swatch Options, in the footer and the panel menu, treated every selected name starting with "[" as reserved, so a user swatch such as [Mine] or a color group such as [Team] could not be deleted or edited there, and New Color Group and Save Swatch Library left them out. The checks now use Swatch::is_reserved, as the engine's swatch.delete and swatch.edit and the item context menu already do, so only None and [Registration] stay protected. Selected names the document no longer holds are left out instead of reaching the command as errors. --- crates/ui-egui/src/panels/swatches/actions.rs | 21 ++++++++++-------- .../ui-egui/src/panels/swatches/libraries.rs | 2 +- crates/ui-egui/src/panels/swatches/tests.rs | 22 ++++++++++++++++++- docs/target-app-parity.md | 1 + 4 files changed, 35 insertions(+), 11 deletions(-) diff --git a/crates/ui-egui/src/panels/swatches/actions.rs b/crates/ui-egui/src/panels/swatches/actions.rs index b183787366..b3ecb774a7 100644 --- a/crates/ui-egui/src/panels/swatches/actions.rs +++ b/crates/ui-egui/src/panels/swatches/actions.rs @@ -2,16 +2,19 @@ use super::dnd::{group_of, selection}; use super::libraries::SwatchLibraries; use super::{Kind, LibraryKind, Ui, Value, VectorcraftApp, View, active_paint, json, library_panel, menu_item, pstate, set_pstate, widgets}; -/// The selected swatches and groups that can be deleted (all but None and Registration). -pub(super) fn deletable(sel: &[String]) -> Vec<String> { - sel.iter().filter(|n| !n.starts_with('[')).cloned().collect() +/// The selected swatches and groups that can be deleted: every color group in the document and +/// every swatch that `Swatch::is_reserved` does not reserve (None and Registration). Names the +/// document does not hold are left out. +pub(super) fn deletable(app: &VectorcraftApp, sel: &[String]) -> Vec<String> { + let Some(d) = app.session.active().map(|st| &st.doc) else { return vec![] }; + sel.iter().filter(|n| d.swatch(n).map_or_else(|| d.swatch_groups.iter().any(|g| g.name == **n), |w| !w.is_reserved())).cloned().collect() } /// The selected swatch when exactly one swatch with an editor is selected (not None, Registration /// or a group). -fn editable(app: &VectorcraftApp, sel: &[String]) -> Option<String> { +pub(super) fn editable(app: &VectorcraftApp, sel: &[String]) -> Option<String> { match sel { - [n] if !n.starts_with('[') && app.session.active().is_some_and(|st| st.doc.swatch(n).is_some()) => Some(n.clone()), + [n] if app.session.active().and_then(|st| st.doc.swatch(n)).is_some_and(|w| !w.is_reserved()) => Some(n.clone()), _ => None, } } @@ -77,7 +80,7 @@ pub(super) fn bottom(app: &mut VectorcraftApp, ui: &mut Ui, sel: &[String]) { } ui.add_space((ui.available_width() - 3.0 * 28.0).max(0.0)); if widgets::icon_button(ui, "dc-folder", tl!("New Color Group"), false, 24.0).clicked() { - app.run("ui.newColorGroup", json!({"swatches": deletable(sel)})).ok(); + app.run("ui.newColorGroup", json!({"swatches": deletable(app, sel)})).ok(); } // Alt-click skips the dialog; Ctrl/Cmd-click makes a spot color, and Ctrl/Cmd+Shift-click // makes a global process color. @@ -85,7 +88,7 @@ pub(super) fn bottom(app: &mut VectorcraftApp, ui: &mut Ui, sel: &[String]) { new_swatch(app, sel, ui.input(|i| i.modifiers)); } // Alt-click deletes without asking. - let del = deletable(sel); + let del = deletable(app, sel); if widgets::icon_button_enabled(ui, "trash-2", tl!("Delete Swatch"), false, !del.is_empty(), 24.0).clicked() { delete(app, del, ui.input(|i| i.modifiers.alt)); } @@ -123,7 +126,7 @@ pub(super) fn new_swatch(app: &mut VectorcraftApp, sel: &[String], m: egui::Modi pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { let view = app.ui.swatches_view; let selected = selection(app, ui); - let del = deletable(&selected); + let del = deletable(app, &selected); let opts = editable(app, &selected); if menu_item(ui, tl!("New Swatch…"), true, false) { new_swatch(app, &selected, egui::Modifiers::NONE); @@ -198,6 +201,6 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { ui.separator(); ui.menu_button(tl!("Open Swatch Library"), |ui| library_panel::library_menu::<SwatchLibraries>(app, ui)); if menu_item(ui, tl!("Save Swatch Library…"), true, false) { - app.run("ui.saveSwatchLibrary", json!({ "names": deletable(&selected) })).ok(); + app.run("ui.saveSwatchLibrary", json!({ "names": deletable(app, &selected) })).ok(); } } diff --git a/crates/ui-egui/src/panels/swatches/libraries.rs b/crates/ui-egui/src/panels/swatches/libraries.rs index 864f6ae7e0..3e1049c9df 100644 --- a/crates/ui-egui/src/panels/swatches/libraries.rs +++ b/crates/ui-egui/src/panels/swatches/libraries.rs @@ -142,7 +142,7 @@ impl LibraryKind for SwatchLibraries { app.status(e); } if menu_item(ui, tl!("Save Swatch Library…"), app.session.active().is_some(), false) { - let names = deletable(&selection(app, ui)); + let names = deletable(app, &selection(app, ui)); app.run("ui.saveSwatchLibrary", json!({ "names": names })).ok(); } } diff --git a/crates/ui-egui/src/panels/swatches/tests.rs b/crates/ui-egui/src/panels/swatches/tests.rs index 8e313e9d77..ab010df57e 100644 --- a/crates/ui-egui/src/panels/swatches/tests.rs +++ b/crates/ui-egui/src/panels/swatches/tests.rs @@ -281,7 +281,27 @@ fn delete_asks_then_removes_the_selection_and_unlinks_art() { assert!(app.session.doc().unwrap().doc.swatch("Orange").is_some()); delete(&mut app, vec!["Orange".into()], true); assert!(app.ui.dialog.is_none() && app.session.doc().unwrap().doc.swatch("Orange").is_none()); - assert_eq!(deletable(&["[None]".into(), REGISTRATION.into(), "Grays".into()]), ["Grays"]); + assert_eq!(deletable(&app, &["[None]".into(), REGISTRATION.into(), "Grays".into()]), ["Grays"]); +} + +/// Only None and Registration are reserved: a user swatch or color group whose name starts with +/// `[` can be deleted, the swatch can be edited, and names the document does not hold are left out. +#[test] +fn bracketed_user_swatches_and_groups_can_be_deleted_and_edited() { + let mut app = app(); + app.run("swatch.new", json!({"name": "[Mine]", "color": "#336699"})).unwrap(); + app.run("swatch.newGroup", json!({"name": "[Team]", "colors": ["#ff0000"]})).unwrap(); + let names = |v: &[&str]| v.iter().map(|n| n.to_string()).collect::<Vec<String>>(); + assert_eq!(deletable(&app, &names(&["[None]", REGISTRATION, "[Mine]", "[Team]", "Gone"])), ["[Mine]", "[Team]"]); + assert_eq!(actions::editable(&app, &names(&["[Mine]"])).as_deref(), Some("[Mine]")); + for name in ["[None]", REGISTRATION, "[Team]", "Gone"] { + assert_eq!(actions::editable(&app, &names(&[name])), None, "{name}"); + } + let doomed = deletable(&app, &names(&["[Mine]"])); + delete(&mut app, doomed, false); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.str("message")).as_deref(), Some("Delete “[Mine]”?")); + crate::dialogs::confirm(&mut app).unwrap(); + assert!(app.session.doc().unwrap().doc.swatch("[Mine]").is_none()); } /// The prompt for several swatches and groups gives the form the language's plural rule picks for the count. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index e9fc9a6820..f82cd5a236 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1723,6 +1723,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Swatches:** names follow the colour model and are unique; Swatch Options (process/spot, Global, Gray/RGB/HSB/CMYK/Web, live preview); editing a global or spot swatch recolours every linked fill, stroke and text run in one undo step; multi-select and delete with confirmation; New Swatch and New Color Group dialogs (a group from the selected artwork's colours); swatches in colour groups convert, separate and count like any other. The Swatches panel selects ranges and whole groups, has a find field, and drags swatches to reorder, regroup or paint art; Add Used Colors, Select All Unused, Merge, Ungroup and Sort by Kind; a CMYK document keeps applied colours in CMYK. Swatch libraries: nine generated colour libraries, seven gradient libraries (among them Organic Fades, soft perceptually mixed multi-stop fades that thin out to transparent, and Holographic, seven opaque linear foils of narrow pastel and pearl bands and seven radial glows that fade out to a clear edge) and three pattern libraries (Geometric Patterns; Grit Textures with eight seamless grain, speckle, stipple, scratch and fleck tiles; and Optical Effects with eight of VectorCraft's own seamless wave, ring, warped-check, stripe, chevron and lens tiles; their swatches bring their patterns) in a library panel, saved as `.vcswatches`, `.gpl`, swatch exchange (`.ase`) or CSS, and loaded from `.vcswatches`, `.gpl` and `.ase` files (`.ase` both ways: RGB, CMYK, Lab and Gray; global, spot and process; groups) and from color books (`.acb`, read only: the RGB, CMYK or Lab colors of a book such as a Pantone book a user owns, named with its prefix and suffix, spot unless it says process, #831); `swatch.library.copyToUser` copies a loaded library into the User Defined folder without replacing a file, and a file with the same extension and bytes as a User Defined library opens as that library. Tints of global and spot colours ("Name 40%") stay linked and separate as a percentage of their plate. Spot colours can be defined in Lab (Spot Colors options). A built-in [Registration] swatch prints on every plate. Right-clicking a swatch in either list or thumbnail view selects it without applying paint and offers Swatch Options…, Duplicate Swatch and Delete Swatch for that item. None, [Registration] and missing swatches disable these actions. Existing active-item multiselection is retained; actions still target only the clicked item. Evidence: `panels::swatches::tests::context_menu` harness tests cover all five views, selection, dialog dispatch, duplicate/delete and Undo. All 39 Swatches tests pass; the regression fails with the menu hooks removed. Rendered headless list and thumbnail menus were inspected, and a fresh local deep CodeRabbit review reported zero findings. Full workspace CI passed on Linux/WSL on the merged branch (all 13 gates), including the test-helper correction for the upstream compile error tracked in #7727; native Windows full CI has two unchanged engine-test failures. Scores and estimates unchanged. Validation on 2026-11-15: native Windows formatting, workspace Clippy and all 39 focused Swatches tests passed. Windows full CI stopped at unchanged engine tests `tests::package::a_confined_package_names_files_outside_the_read_root_by_name` (slash-sensitive report assertion) and `tests::plugins::plugin_storage_behind_a_link_is_left_alone` (storage-link setup returned AlreadyExists). Both cases pass in the Linux/WSL full CI run, which passed all 13 gates. No engine or CI workflow changes are included. + The panel's Delete Swatch and Swatch Options (footer buttons and panel menu), New Color Group and Save Swatch Library treat only None and [Registration] as reserved, so a user swatch or color group whose name starts with `[` can be deleted, edited, grouped and saved; selected names the document no longer holds are left out (`panels::swatches::tests::bracketed_user_swatches_and_groups_can_be_deleted_and_edited`). Editing, renaming, deleting or merging a global swatch also changes the colors linked to it in graph designs, the art of brushes and the tile that pattern editing's Cancel puts back, in the same undo step as the rest of the art; Default Swatches with replace unlinks them there too. A swatch step in `command.batch` (Delete, Swatch Options, Merge, Edit Color Group) changes the fill and stroke for new art as the command run on its own does, so art drawn later in the batch or after it takes the same paint; a batch that fails, and a canceled batch preview, put back the paints it started with, and a canceled Swatch Options preview leaves them as they were. These swatch commands also change the fills and strokes of the appearance new art takes, and Undo and Redo of the command or the batch put the paints for new art back with the swatches. Spot Colors options (`swatch.spotOptions`) and Default Swatches with replace (`swatch.resetDefaults {replace: true}`) as `command.batch` steps also change the fill and stroke for new art as each command run on its own does: a fill or stroke linked to a Lab spot swatch keeps its link and tint and takes the Lab values or their CMYK equivalent, and one linked to a swatch the replace removes keeps its color and loses the link. Evidence: `swatch_steps_in_a_batch_change_the_new_art_paints_as_commands_do`, `spot_colors_options_in_a_batch_change_the_new_art_paints_as_the_command_does`, `default_swatches_replace_in_a_batch_unlinks_the_new_art_paints_as_the_command_does`, `undo_and_redo_of_a_swatch_edit_put_back_the_new_art_paints`, `swatch_edits_reach_the_paints_of_the_new_art_template`, `a_failed_batch_puts_back_the_new_art_paints_a_swatch_step_changed` and `canceling_a_swatch_options_preview_keeps_the_new_art_paints` in `crates/engine/src/tests/swatches.rs`. Add Used Colors (`swatch.addUsedColors`) and Select All Unused (`swatch.unused`) look colors, swatch names, links, tints and gradients up in hash sets instead of searching every swatch and color for each color or linked paint (New Color Group from artwork too), and New Swatch with several colors (`swatch.new`), New Color Group (`swatch.newGroup`) and Edit Color Group (`swatch.editGroup`) name their new swatches from one set of the names already taken. The new swatches keep their names, order and links, and Select All Unused lists the same swatches. Evidence: `add_used_colors_adds_each_new_color_once_with_free_names`, `add_used_colors_global_links_every_paint_of_a_new_color`, `unused_matches_links_tints_colors_gradients_and_patterns_exactly`, `new_swatches_from_colors_are_numbered_after_names_already_taken`, `new_color_group_numbers_its_colors_after_the_group_and_its_moved_swatches`, `new_color_group_from_artwork_lists_each_color_once_with_free_names` and `edit_color_group_numbers_extra_colors_after_the_names_it_keeps` in `crates/engine/src/tests/swatchcmds.rs`; `free_swatch_names_match_naming_each_swatch_as_it_is_added` and `free_swatch_names_match_new_swatch_names_as_swatches_are_added` in `crates/doc/src/swatches.rs`. From 99cb4f41908011d9a491786647381bbf1f2e18b7 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 17 Nov 2026 09:30:55 -0800 Subject: [PATCH 098/176] Import PDF: All checks Import PDF pages as links and Range clears it File > Open's Import PDF dialog now starts with Import PDF pages as links checked for All, so every page of a PDF opened from its file opens linked, and clears the box when Range is picked, so a range opens as art. A box checked or cleared by hand keeps that state until the other of All and Range is picked; ui.dialog.set of allPages does the same. The box stays clear for a file without its path, with a password, or over the 256 MB that linkPages takes (fileio::pages_can_link). Docs: docs/mcp.md, docs/target-app-parity.md, docs/file-format-parity.md. --- crates/engine/src/cmd/fileio.rs | 2 +- crates/engine/src/cmd/fileio/pdfimport.rs | 7 +++ .../engine/src/cmd/fileio/tests_pdfimport.rs | 13 +++++ crates/ui-egui/src/dialogs.rs | 6 ++- crates/ui-egui/src/dialogs/import_pdf.rs | 50 +++++++++++++++---- .../ui-egui/src/dialogs/tests_import_pdf.rs | 46 ++++++++++++++++- docs/file-format-parity.md | 2 +- docs/mcp.md | 6 ++- docs/target-app-parity.md | 1 + 9 files changed, 116 insertions(+), 17 deletions(-) diff --git a/crates/engine/src/cmd/fileio.rs b/crates/engine/src/cmd/fileio.rs index 6817f28b35..dd16393640 100644 --- a/crates/engine/src/cmd/fileio.rs +++ b/crates/engine/src/cmd/fileio.rs @@ -93,7 +93,7 @@ pub use naming::{NameParts as FileNameParts, parse_date as parse_file_date, rend pub(crate) use native::preview_png; pub use native::with_compression_pref; pub(crate) use pdfimport::opened_page_document; -pub use pdfimport::{LoadOptions, page_document}; +pub use pdfimport::{LoadOptions, page_document, pages_can_link}; pub(crate) use psdlayers::import_active as psd_layers; pub use psdlayers::{PsdInfo, info as psd_info}; pub(crate) use psdslices::over as psd_slices; diff --git a/crates/engine/src/cmd/fileio/pdfimport.rs b/crates/engine/src/cmd/fileio/pdfimport.rs index 189274a31f..ea37575135 100644 --- a/crates/engine/src/cmd/fileio/pdfimport.rs +++ b/crates/engine/src/cmd/fileio/pdfimport.rs @@ -222,6 +222,13 @@ fn page_options(page: usize, o: &LoadOptions) -> ImportOptions { ImportOptions { pages: Some(vec![page]), crop: o.crop, password: o.password.clone(), text_as: o.text_as, layers: false, ..Default::default() } } +/// Whether `document.open`'s `linkPages` takes the file `name` holding `bytes`: a PDF or a +/// PDF-compatible `.ai` or `.ait` of at most [`document::MAX_FILE`] bytes. Its path, a password +/// and `textAs` are checked apart ([`linked_pages`]). +pub fn pages_can_link(name: &str, bytes: &[u8]) -> bool { + bytes.len() <= document::MAX_FILE && document::is_pdf(name, bytes) +} + /// `document.open` with `linkPages`: the pages `o` picks of the PDF (or PDF-compatible `.ai` or /// `.ait`) `name`, read from `path`, as a document holding one placed document per page, linked to /// that page of the file as File › Place with Link places one ([`document::source`]). Each page diff --git a/crates/engine/src/cmd/fileio/tests_pdfimport.rs b/crates/engine/src/cmd/fileio/tests_pdfimport.rs index 703c29fe74..63b70c48c7 100644 --- a/crates/engine/src/cmd/fileio/tests_pdfimport.rs +++ b/crates/engine/src/cmd/fileio/tests_pdfimport.rs @@ -410,3 +410,16 @@ fn a_placeholder_only_pdf_part_is_detected() { assert!(open(&mut s, &two, json!({"pages": "1"})).is_err()); open(&mut s, &two, json!({})).unwrap(); } + +/// `linkPages` takes a PDF up to the largest file placed, and nothing else. +#[test] +fn pages_can_link_a_pdf_up_to_the_largest_file_placed() { + let small = three_pages(); + assert!(pages_can_link("pages.pdf", &small)); + assert!(!pages_can_link("pages.svg", b"<svg xmlns=\"http://www.w3.org/2000/svg\"/>")); + let mut big = vec![0u8; crate::cmd::place::document::MAX_FILE + 1]; + big[..small.len()].copy_from_slice(&small); + assert!(!pages_can_link("pages.pdf", &big), "over the limit"); + big.pop(); + assert!(pages_can_link("pages.pdf", &big), "at the limit"); +} diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 9e54eb12f6..361987dc23 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -597,7 +597,8 @@ pub fn accepts_field(d: &Dialog, field: &str) -> bool { /// Options setting set this way for several rows is sent to every row (Template also sets Lock /// and Dim Images, as its checkbox does). A DXF Options preset set this way sets its fields, as /// one picked from its menu does, and the preset it shows follows the DXF options set this way. -/// A Graph Data Column Width set this way sets every column, as Cell Style's does. +/// A Graph Data Column Width set this way sets every column, as Cell Style's does. An Import PDF +/// `allPages` set this way to the other pick sets Import PDF pages as links back to its default. pub fn set_field(d: &mut Dialog, field: String, value: Value) { if d.kind == brush_options::KIND { brush_art_options::note_set(d, &field); @@ -608,6 +609,9 @@ pub fn set_field(d: &mut Dialog, field: String, value: Value) { if d.kind == layer_options::KIND { layer_options::note_set(d, &field, &value); } + if d.kind == import_pdf::KIND { + import_pdf::note_set(d, &field, &value); + } if d.kind == "preferences" { crate::prefs_dialog::note_set(d, &field, &value); } diff --git a/crates/ui-egui/src/dialogs/import_pdf.rs b/crates/ui-egui/src/dialogs/import_pdf.rs index 4ef8c925d8..bedd3387c2 100644 --- a/crates/ui-egui/src/dialogs/import_pdf.rs +++ b/crates/ui-egui/src/dialogs/import_pdf.rs @@ -3,7 +3,10 @@ //! //! Fields: `mode` (`open` | `place`), `name`, `path?`, `pageCount`, `page` (the page shown, and the //! one placed; 1-based), `allPages`, `range` and `linkPages` (open: Import PDF Pages as Links, for -//! a file read from a path and opened without a password), `cropTo` and `password`. `__locked` is set +//! a file read from a path and opened without a password; `null` until it is checked or cleared, +//! when it follows the pages picked: on for All, off for a range; picking the other of All and +//! Range sets it back to `null`; `__linkable` is false for a file `linkPages` does not take, such as +//! one over its size limit), `cropTo` and `password`. `__locked` is set //! until the password is accepted: OK then unlocks the file, and with `__passwordOnly` (Place with //! Show Import Options off) places its first page at once. `__place` keeps the other `file.place` //! params (Link, Template, `at`…). The file's bytes stay out of the fields, in @@ -144,10 +147,11 @@ pub fn offer(app: &mut VectorcraftApp, name: &str, bytes: &[u8], path: Option<St "page": 1, "allPages": true, "range": "", - "linkPages": false, + "linkPages": null, "cropTo": CropTo::default().id(), "password": "", "__locked": locked, + "__linkable": fileio::pages_can_link(name, bytes), }); if let Some(p) = path { fields["path"] = json!(p); @@ -214,14 +218,40 @@ fn password(d: &Dialog) -> Option<String> { } /// Can the pages open linked: the file was read from a path (a linked page is read from its -/// file again) and opens without a password (`document.open`'s `linkPages` refuses one). +/// file again), `document.open`'s `linkPages` takes its size, and it opens without a password +/// (`linkPages` refuses one). fn can_link(d: &Dialog) -> bool { - d.fields.get("path").and_then(Value::as_str).is_some() && password(d).is_none() + d.fields.get("path").and_then(Value::as_str).is_some() && d.bool("__linkable") && password(d).is_none() +} + +/// Import PDF Pages as Links as checked or cleared, or, when it is `null`, as the pages picked +/// default it: on for All, off for a range. +fn link_pages(d: &Dialog) -> bool { + d.fields.get("linkPages").and_then(Value::as_bool).unwrap_or_else(|| d.bool("allPages")) } /// Import PDF Pages as Links is checked, and can be. -fn links_on(d: &Dialog) -> bool { - d.bool("linkPages") && can_link(d) +pub(super) fn links_on(d: &Dialog) -> bool { + link_pages(d) && can_link(d) +} + +/// Picks All (true) or Range. A change of pick sets Import PDF Pages as Links back to that pick's +/// default; picking the one already picked keeps the box as it is. +fn pick_all_pages(d: &mut Dialog, all: bool) { + if d.bool("allPages") != all { + d.fields.insert("allPages".into(), json!(all)); + d.fields.insert("linkPages".into(), Value::Null); + } +} + +/// Records that `ui.dialog.set` sets `field` to `value`: a change of `allPages` sets Import PDF +/// Pages as Links back to its default, as a click on All or Range does. +pub(super) fn note_set(d: &mut Dialog, field: &str, value: &Value) { + if field == "allPages" + && let Some(all) = value.as_bool() + { + pick_all_pages(d, all); + } } /// OK: unlock the file with the password, else open the pages or place the page. @@ -330,20 +360,20 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { ui.label(egui::RichText::new(tl!("Pages")).color(t.text)); let all = d.bool("allPages"); if widgets::radio(ui, tl!("All"), all, true) { - d.fields.insert("allPages".into(), json!(true)); + pick_all_pages(d, true); } ui.horizontal(|ui| { if widgets::radio(ui, tl!("Range:"), !all, true) { - d.fields.insert("allPages".into(), json!(false)); + pick_all_pages(d, false); } if super::form::text_edit_named(ui, d, "range", tl!("Range:"), 90.0).gained_focus() { - d.fields.insert("allPages".into(), json!(false)); + pick_all_pages(d, false); } }); widgets::dim_label(ui, tl!("e.g. 1-3, 5")); ui.add_space(10.0); if widgets::check(ui, tl!("Import PDF pages as links"), links_on(d), can_link(d)) { - d.fields.insert("linkPages".into(), json!(!d.bool("linkPages"))); + d.fields.insert("linkPages".into(), json!(!link_pages(d))); } } }); diff --git a/crates/ui-egui/src/dialogs/tests_import_pdf.rs b/crates/ui-egui/src/dialogs/tests_import_pdf.rs index 62e783c267..5ecd7734cb 100644 --- a/crates/ui-egui/src/dialogs/tests_import_pdf.rs +++ b/crates/ui-egui/src/dialogs/tests_import_pdf.rs @@ -95,12 +95,19 @@ fn import_pdf_pages_as_links_opens_each_page_linked() { let path = dir.join("three.pdf").to_string_lossy().into_owned(); std::fs::write(&path, three_pages()).unwrap(); let mut app = app(); + // All pages: checked without a click. io::open_bytes(&mut app, &path, &three_pages(), Some(path.clone())).unwrap(); - assert_eq!(field(&app, "linkPages"), false, "off by default"); frame(&mut app); - set(&mut app, "linkPages", json!(true)); + confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(artboard_widths(&app), [100.0, 200.0, 300.0]); + assert_eq!(placed_pages(&app), [true, true, true], "All opens the pages linked"); + // A range: cleared, and checked by hand it opens the range linked. + io::open_bytes(&mut app, &path, &three_pages(), Some(path.clone())).unwrap(); set(&mut app, "allPages", json!(false)); set(&mut app, "range", json!("1, 3")); + assert!(!import_pdf::links_on(app.ui.dialog.as_ref().unwrap()), "Range: cleared"); + set(&mut app, "linkPages", json!(true)); frame(&mut app); confirm(&mut app).unwrap(); assert!(app.ui.dialog.is_none()); @@ -124,6 +131,41 @@ fn import_pdf_pages_as_links_opens_each_page_linked() { assert_eq!(placed_pages(&app), [false, false]); } +/// Picking All checks Import PDF pages as links and picking Range clears it. A click on the box +/// stands until the other one is picked; picking the one already picked or editing the range keeps +/// it. `ui.dialog.set` picks the way the buttons do. +#[test] +fn picking_all_or_a_range_sets_the_links_default() { + let mut app = app(); + io::open_bytes(&mut app, "three.pdf", &three_pages(), Some("/tmp/three.pdf".into())).unwrap(); + let pick = |app: &mut VectorcraftApp, k: &str, v: serde_json::Value| set_field(app.ui.dialog.as_mut().unwrap(), k.into(), v); + let on = |app: &VectorcraftApp| import_pdf::links_on(app.ui.dialog.as_ref().unwrap()); + assert!(on(&app), "All: checked"); + pick(&mut app, "allPages", json!(false)); + assert!(!on(&app), "Range: cleared"); + pick(&mut app, "linkPages", json!(true)); + pick(&mut app, "allPages", json!(false)); + pick(&mut app, "range", json!("1-2")); + frame(&mut app); + assert!(on(&app), "checked by hand, picking Range again and editing the range keep it"); + pick(&mut app, "allPages", json!(true)); + assert!(on(&app), "All: checked"); + pick(&mut app, "linkPages", json!(false)); + pick(&mut app, "allPages", json!(true)); + frame(&mut app); + assert!(!on(&app), "cleared by hand, picking All again keeps it"); + pick(&mut app, "allPages", json!(false)); + pick(&mut app, "allPages", json!(true)); + assert!(on(&app), "All picked after Range: checked again"); + // A file `linkPages` does not take (one over its size limit) leaves the box clear. + assert_eq!(field(&app, "__linkable"), true); + set(&mut app, "__linkable", json!(false)); + assert!(!on(&app), "a file linkPages does not take"); + // A file given without its path can't link its pages: the box stays clear. + io::open_bytes(&mut app, "three.pdf", &three_pages(), None).unwrap(); + assert!(!on(&app)); +} + #[test] fn single_page_pdfs_open_directly() { let mut app = app(); diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index 198f36f3f2..77ab54b3c9 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -315,7 +315,7 @@ Gradient meshes in the editing data keep each point's own color where a patch's | VectorCraft `.vectorcraft` / `.vctemplate` | — | yes | yes | lossless JSON, versioned, save down to v1; property-tested round trips (`format/tests/prop_format.rs`); documents with a lot of path data are written as compact JSON, about a fifth of the size (#1492); a save falls back to a plain fsync and to writing elsewhere and copying in when the folder refuses the usual steps (#1625, #1649, part of #1620; not confirmed on a real network share); the size limits on embedded data also apply to files read from memory (#1783), and saving over a private file on Unix leaves no readable temporary copy beside it (#1778); a dynamic symbol's type (`dynamic` on the symbol) and an instance's appearance changes to its art (`symbol_overrides`, each path at most 64 deep, counted against the object budget) are written only when set, so documents without them save as before (#4938) | | Illustrator template `.ait` | open, save | yes | PDF-compatible only, from Save as Template (`.vctemplate` stays its default) | New from Template opens a saved `.ait` untitled with its layers and art (`tests_pdfedit.rs`) | | Illustrator `.ai` | open, save | yes (PDF-compatible + editing-data structure with template layers and ruler guides, File Info) | PDF-compatible, or legacy version 7 (layers and groups) | see above; no real-file corpus | -| 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; Import PDF pages as links opens each page as a placed document linked to it, on its own artboard, `tests/placed_document.rs`) | 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. | +| 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; Import PDF pages as links opens each page as a placed document linked to it, on its own artboard, `tests/placed_document.rs`, and is checked when All is picked and cleared when Range is picked) | 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 CMap (`UniJIS-UCS2-H`, `90ms-RKSJ-H`, `GBK-EUC-H`, `KSCms-UHC-H`, `ETen-B5-H`), set as type in the font of the CIDFont's name, vertical over a `-V` CMap; a name that ends in the row-and-cell CMap `H` or `V` splits off the CMap only when the file defines the CIDFont of that name, the CIDFont is `Ryumin-Light` or `GothicBBB-Medium` (the Japanese CIDFonts a printer carries), or the name has a hyphen and an installed face that covers Japanese has it; 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` | | DCS 1.0 / 2.0 | place linked | place linked only (one image of the plates; spot plates as spot swatches; the composite's clipping path; each plate on its own ink in Separations Preview and print separations) | no | `crates/eps/src/dcs/tests.rs`, `crates/engine/src/tests/dcs.rs` | diff --git a/docs/mcp.md b/docs/mcp.md index 092faabc4c..f6a7d5e77d 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1439,9 +1439,11 @@ a layer named after the page (`Page 2`). A PDF-compatible `.ai` with `cropTo: "c when it opens as art. A page on its trim box shows its bleed box round the artboard, and the pages give the document their bleed; the artboards are then 36 pt apart plus the bleed on both sides. The document opens in CMYK when most of those pages are painted mostly in CMYK, unless `colorMode` names a mode. All the pages' objects share one copy of the file. The Links panel lists each -page, and `links.embed` makes a page editable art. +page, and `links.embed` makes a page editable art. The command's `linkPages` defaults to false; the dialog checks the +box when All is picked and clears it when Range is picked, for a file it can link, and `ui.dialog.set` of `allPages` +does the same. A box checked or cleared by hand keeps that state until the other of All and Range is picked. `document.open` refuses `linkPages` for a file that is not a PDF or a PDF-compatible `.ai`, for a file given as -`dataBase64` without a path, with a `password`, and with `textAs: "outlines"`, and rejects a `linkPages` that is not +`dataBase64` without a path, with a `password`, with `textAs: "outlines"` and for a file over 256 MB, and rejects a `linkPages` that is not true or false. Save then asks for a name. `document.open`, `file.place` and `document.pdfInfo` reject a `cropTo`, `crop`, `password`, `colorMode` or `textAs` that is not a string, and `document.pdfInfo` rejects a `thumbnailSize` that is not a number. The error names the param, diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index e9fc9a6820..475213bf24 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2059,6 +2059,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Placed documents: File › Place of a `.vectorcraft` file links to it by default (`file.place`'s `link`): one locked object showing an artboard of the document (or its art's bounds), read the way placing it without Link reads it, its symbols, patterns and images kept apart from the document's; without Link (or from bytes, not a file) it is an editable copy as before. It stays vectors in every output (SVG, PDF, EPS, EMF, DXF), and so do placed documents inside it, read from their own files up to 8 levels deep (documents that place each other stop there). On screen they draw from bitmaps cached per file and zoom step, shared by every copy and made in the background (a placeholder until ready), so a sheet of them redraws in about a millisecond; exports and prints draw them exactly. Like linked images, a save keeps only a preview of each (JPEG when opaque) unless Include Linked Files; output, and zooming past the preview, read the file again, falling back to the preview with a warning when it is gone or changed. Saves for older versions write them as plain art. Links check, update, relink, Update Links on open, Link Info (the artboard's size), Placement Options, Break Link (also Embed, Object › Expand: the editable copy placing without Link gives, its resources joining the document), Edit Original (the document in a new tab) and the Links panel cover them; saving a document updates the open documents that place it. The native format (v4) keeps data of 8 KB or more after the JSON instead of base64 in it. - Placed documents' bitmaps on screen: when a bitmap made in the background is ready, the desktop app renders the canvas again only where the objects that show its file are, when the frame shown was rendered on the UI thread and that part is at most half the canvas. Bitmaps drawn or made since a frame began are kept for that frame past the 512 MiB budget, up to 2 GiB, so a view showing more than the budget does not make them again in every frame. A bitmap that would take them past 2 GiB is not kept, and its file draws exactly at that zoom. A bitmap that can't be made (the file can't be read and there is no preview) shows the light placeholder and is not asked for again. Each ready bitmap used to render the whole canvas again, and bitmaps past the budget and bitmaps that could not be made were asked for again in every frame (`crates/render/src/tests/placed_document.rs`). - Linked PDF and `.ai` pages: File › Place with Link (the default) places a page of a PDF, `.ai` or `.ait` file read as PDF pages as a placed document, as it links an image, the page and its box (`crop`) kept with the link: Links check, update and relink it, Break Link and Object › Expand give the group placing it without Link gives, every output draws the page's vectors, and Package copies the file. Without Link, or with a password or `textAs: "outlines"`, the page is embedded. An EPS file, a PostScript file or a PostScript `.ai` placed from a file with Link is a placed document the same way, showing the art placing it without Link gives (clipped to its bounding box, or its art's bounds with `crop: "bounding"`); Links lists it as `EPS` or `PostScript`, and a save, Package, Break Link and Object › Expand treat it as they treat a placed PDF page. Package also copies the files that the native document of an EPS file written by VectorCraft links, beside the EPS file's copy, which finds them there by name. Placing one keeps the file linked rather than embedding it, as [the help page](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-other-file-types/eps-and-dcs-file-import-in-illustrator.html) describes; a DCS file stays a linked image (`crates/engine/src/tests/placed_document.rs`, `crates/engine/src/tests/package.rs`). + - File › Open's Import PDF dialog checks Import PDF pages as links when All is picked and clears it when Range is picked: every page of a PDF opened from its file opens linked unless the box is cleared, and a range of pages opens as art unless the box is checked ([the help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=444)). A box checked or cleared by hand keeps that state until the other of All and Range is picked; picking the one already picked, or editing the range, does not change it, and `ui.dialog.set` of `allPages` changes it as the buttons do (VectorCraft's own rules). A file opened without its path, with a password or over the 256 MB that linked pages take still opens its pages as art. The box used to start cleared for All as well (`crates/ui-egui/src/dialogs/tests_import_pdf.rs`). - The place cursor keeps an encrypted PDF, `.ai` or `.ait` file, at a letter page's size (VectorCraft's own size) and without a thumbnail, and a click or drag on it asks for its password, with the Place dialog's Show Import Options on or off; such a file was left out of the cursor before (`crates/engine/src/tests/place.rs`, `crates/ui-egui/src/tests/place.rs`). - File › Place with Bounding Box (`file.place {crop: "bounding"}`) measures the art that shows, with its strokes and effects, as an export does: hidden objects, guides and template layers do not count, a group whose only part on the page or artboard is hidden is not placed, and symbol instances are measured by their art, for `at`, `rect`, the place cursor and `file.place.info` (`crates/engine/src/tests/place.rs`). - The Place dialog has a Show Import Options checkbox after Link, Template and Replace ([Place multiple files in a document](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-other-file-types/place-multiple-files-in-a-document.html)). On (VectorCraft's default, saved with the preferences), each PDF, DXF or text file asks for its import options before it is placed, also in the place cursor; off (`file.place {showImportOptions: false}`), it is placed with the options last confirmed for its format, and only an encrypted PDF asks, for its password. Text Import Options now starts from the options confirmed last (`crates/ui-egui/src/tests/place.rs`). From 6f121031479457accbcb7441da01c11d8f536634 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 17 Nov 2026 09:45:03 -0800 Subject: [PATCH 099/176] .ai import: Scatter brush art turns over with its unlinked opacity masks Scatter brush art is read turned over, as Art brush art is. The turn now goes through the same helper as Art brushes, so the art of opacity masks that don't move with their objects is turned over too and stays lined up with the art. Fixes the "Unlinked spray" case of scatter_and_art_brush_mask_art_round_trips. --- crates/eps/src/import/ai/brush.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/eps/src/import/ai/brush.rs b/crates/eps/src/import/ai/brush.rs index dab29a3f72..23982759a0 100644 --- a/crates/eps/src/import/ai/brush.rs +++ b/crates/eps/src/import/ai/brush.rs @@ -577,7 +577,7 @@ pub(super) fn finish_brushes_within( DraftKind::Scatter { brush, art: name } => copy(&name).map(|mut a| { // Each copy is the section turned over: its side with y up draws down the page // before the copy's rotation, and a brush draws art's y (down here) down the page. - a.transform(Affine::scale_non_uniform(1.0, -1.0), false); + turn_over(&mut a); BrushKind::Scatter(Scatter { art: a, ..brush }) }), DraftKind::Art { mut brush, art: name, settings } => copy(&name).map(|mut a| { From f40f085d21d7d6fbd6dd10be36ba4f582d880a2d Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 17 Nov 2026 09:49:10 -0800 Subject: [PATCH 100/176] Stroke panel: stroke.set collects its targets through a set A Stroke panel edit with no item lists the selected groups and layers that have a stroke of their own, then adds the leaves of the other targets, and it checked each leaf against the growing list, so collecting the targets took time that grows with the square of the object count. The command now checks each leaf against a set seeded with the listed groups and layers. The list is the same: its order is kept, a group or layer named twice is still listed twice, and a leaf is listed once. crates/engine/examples/stroke_targets_bench.rs times both merges on the same leaves in one process. With 20,000 paths in one group, collecting the targets takes 0.66 ms of thread CPU time against 55 ms with the list search, and the whole command takes 60 ms. --- .../engine/examples/stroke_targets_bench.rs | 146 ++++++++++++++++++ crates/engine/src/cmd/stroke.rs | 94 ++++++++++- docs/target-app-parity.md | 1 + 3 files changed, 240 insertions(+), 1 deletion(-) create mode 100644 crates/engine/examples/stroke_targets_bench.rs diff --git a/crates/engine/examples/stroke_targets_bench.rs b/crates/engine/examples/stroke_targets_bench.rs new file mode 100644 index 0000000000..b576968e49 --- /dev/null +++ b/crates/engine/examples/stroke_targets_bench.rs @@ -0,0 +1,146 @@ +//! `cargo run --release -p vectorcraft-engine --example stroke_targets_bench` prints the time `stroke.set` +//! takes to list its targets on documents of 2,000, 10,000 and 20,000 rectangles, all in one group. For +//! each size it times, on the same leaves, the merge that checks each leaf against the growing list and +//! the merge that checks it against a set, checks that the two lists are equal, and then times the whole +//! `stroke.set {weight: 3}` command twice: once with the group named and once with every rectangle named. +//! The whole-command rows include the document copy the command makes for undo; each run is undone +//! before the next, outside the timed part. +//! On Linux each row is the thread's CPU time, read from `/proc/thread-self/schedstat`; elsewhere +//! it is wall time, and the first line says which. `ITERS` sets the runs per row (default 7); each +//! row is the median in ms. A run of the two merge rows repeats the merge 1,000,000 / paths times +//! and gives the time of one. +// Example (dev tool): unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness). +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::collections::HashSet; +use std::hint::black_box; +use std::time::Instant; + +use serde_json::{Value, json}; +use vectorcraft_color::Color; +use vectorcraft_doc::{Document, NodeId}; +use vectorcraft_engine::Session; +use vectorcraft_geom::Rect; +use vectorcraft_testkit::fixtures::DocBuilder; + +fn iters() -> usize { + std::env::var("ITERS").ok().and_then(|v| v.parse().ok()).unwrap_or(7).max(1) +} + +/// The thread's CPU time in ns, or `None` where `/proc/thread-self/schedstat` cannot be read. +fn cpu_ns() -> Option<u64> { + std::fs::read_to_string("/proc/thread-self/schedstat").ok()?.split_whitespace().next()?.parse().ok() +} + +/// The time `f` takes in ms: CPU time when [`cpu_ns`] reads, wall time otherwise. +fn ms(f: impl FnOnce()) -> f64 { + let (cpu, wall) = (cpu_ns(), Instant::now()); + f(); + match (cpu, cpu_ns()) { + (Some(a), Some(b)) => (b - a) as f64 / 1e6, + _ => wall.elapsed().as_secs_f64() * 1000.0, + } +} + +fn median(mut v: Vec<f64>) -> f64 { + v.sort_by(f64::total_cmp); + v[v.len() / 2] +} + +/// `n` 10 pt squares in one group, and the squares' ids in stacking order. +fn document(n: usize) -> (Document, NodeId, Vec<NodeId>) { + let mut b = DocBuilder::new(4000.0, 4000.0); + let kids: Vec<_> = (0..n) + .map(|i| { + let (x, y) = ((i % 200) as f64 * 12.0, (i / 200) as f64 * 12.0); + b.rect_node(Rect::new(x, y, x + 10.0, y + 10.0), Color::rgb(0.2, 0.4, 0.6)) + }) + .collect(); + let leaves = kids.iter().map(|k| k.id).collect(); + let group = b.group(kids, false); + (b.build(), group, leaves) +} + +/// The merge that checks each leaf against the growing list. +fn listed(mut out: Vec<NodeId>, leaves: Vec<NodeId>) -> Vec<NodeId> { + for id in leaves { + if !out.contains(&id) { + out.push(id); + } + } + out +} + +/// The merge that checks each leaf against a set seeded with `out`. +fn with_set(mut out: Vec<NodeId>, leaves: Vec<NodeId>) -> Vec<NodeId> { + let mut seen: HashSet<NodeId> = out.iter().copied().collect(); + for id in leaves { + if seen.insert(id) { + out.push(id); + } + } + out +} + +fn row(name: &str, ms: f64) { + println!(" {name:<52} {ms:>10.3} ms"); +} + +/// The median time of `stroke.set {weight: 3}` on `ids`, each run undone outside the timed part. +fn whole_command(s: &mut Session, ids: &[NodeId], n: usize) -> f64 { + let p: Value = json!({"ids": ids.iter().map(|id| id.0).collect::<Vec<_>>(), "weight": 3}); + let runs = (0..iters()) + .map(|_| { + let mut r = Value::Null; + let t = ms(|| r = black_box(s.execute("stroke.set", &p).unwrap())); + assert_eq!(r["objects"], n, "{r}"); + s.execute("edit.undo", &json!({})).unwrap(); + t + }) + .collect(); + median(runs) +} + +fn bench(n: usize) { + println!("{n} paths in one group"); + let (doc, group, leaves) = document(n); + + // Each run merges `reps` times, on copies made before the clock starts, and gives the time of one. + let reps = (1_000_000 / n).max(1); + let time = |f: fn(Vec<NodeId>, Vec<NodeId>) -> Vec<NodeId>| -> (f64, Vec<NodeId>) { + let mut last = Vec::new(); + let runs = (0..iters()) + .map(|_| { + let mut work: Vec<Vec<NodeId>> = (0..reps).map(|_| leaves.clone()).collect(); + let mut done = Vec::with_capacity(reps); + let t = ms(|| { + for input in &mut work { + done.push(f(Vec::new(), black_box(std::mem::take(input)))); + } + }); + last = done.pop().unwrap(); + t / reps as f64 + }) + .collect(); + (median(runs), last) + }; + let (old, a) = time(listed); + let (new, b) = time(with_set); + assert_eq!(a, b, "both merges give the same list"); + assert_eq!(a, leaves); + row("target merge, list search", old); + row("target merge, set", new); + println!(" {:<52} {:>10.1}x", "ratio", old / new); + + let mut s = Session::new(); + s.add_document(doc, None); + row("stroke.set, whole command, the group named", whole_command(&mut s, &[group], n)); + row("stroke.set, whole command, every path named", whole_command(&mut s, &leaves, n)); +} + +fn main() { + println!("{}", if cpu_ns().is_some() { "thread CPU time, median of runs" } else { "wall time, median of runs" }); + for n in [2_000, 10_000, 20_000] { + bench(n); + } +} diff --git a/crates/engine/src/cmd/stroke.rs b/crates/engine/src/cmd/stroke.rs index e8fb1349c3..f163e8865e 100644 --- a/crates/engine/src/cmd/stroke.rs +++ b/crates/engine/src/cmd/stroke.rs @@ -220,8 +220,10 @@ fn own_stroke_or_leaves(s: &Session, p: &Value) -> Result<Vec<vectorcraft_doc::N }) }; let (mut out, rest): (Vec<_>, Vec<_>) = picked.into_iter().partition(own); + // A leaf already listed is skipped; a set keeps this linear in the number of leaves. + let mut seen: std::collections::HashSet<vectorcraft_doc::NodeId> = out.iter().copied().collect(); for id in super::leaf_targets(s, &rest)? { - if !out.contains(&id) { + if seen.insert(id) { out.push(id); } } @@ -674,6 +676,7 @@ fn profile_list(s: &mut Session, _: &Value) -> Result<Value> { #[cfg(test)] mod tests { use super::*; + use vectorcraft_doc::NodeId; #[test] fn weight_steps_follow_units_and_stop_at_their_bounds() { @@ -689,4 +692,93 @@ mod tests { assert!((step_weight(mm, Unit::Millimeters, true) - 2.0 * mm).abs() < 1e-9); assert!((step_weight(mm, Unit::Millimeters, false) - 0.75 * mm).abs() < 1e-9); } + + fn run(s: &mut Session, id: &str, p: Value) -> Value { + s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}")) + } + + fn made(v: Value) -> NodeId { + NodeId(v["id"].as_u64().unwrap_or_else(|| panic!("no id in {v}"))) + } + + /// The targets of [`own_stroke_or_leaves`] merged by a linear search of the growing list. + fn listed_merge(s: &Session, p: &Value) -> Vec<NodeId> { + let d = &s.doc().unwrap().doc; + let own = |id: &NodeId| { + d.node(*id).is_some_and(|n| { + matches!(n.kind, NodeKind::Group { .. } | NodeKind::Layer { .. }) && !n.is_compound_shape() && n.appearance.stroke().is_some() + }) + }; + let (mut out, rest): (Vec<_>, Vec<_>) = super::super::targets(s, p).unwrap().into_iter().partition(own); + for id in super::super::leaf_targets(s, &rest).unwrap() { + if !out.contains(&id) { + out.push(id); + } + } + out + } + + /// `stroke.set` with no `item` lists the same targets in the same order as a linear merge: + /// groups and layers with a stroke of their own (repeats kept), the leaves of plain groups and + /// layers, compound paths and compound shapes for their members, and each leaf once, also + /// when it is named both directly and through its group. + #[test] + fn stroke_targets_match_the_listed_merge() { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 2000, "height": 400})); + let base = s.doc().unwrap().doc.layers[0].id; + let mut x = 0.0; + let mut rect = |s: &mut Session| { + x += 120.0; + made(run(s, "shape.rectangle", json!({"x": x, "y": 100, "width": 100, "height": 100}))) + }; + let (a, b) = (rect(&mut s), rect(&mut s)); + let plain = made(run(&mut s, "object.group", json!({"ids": [a.0, b.0]}))); + let (c, d) = (rect(&mut s), rect(&mut s)); + let owned = made(run(&mut s, "object.group", json!({"ids": [c.0, d.0]}))); + run(&mut s, "appearance.addStroke", json!({"ids": [owned.0]})); + let (e, f) = (rect(&mut s), rect(&mut s)); + run(&mut s, "select.set", json!({"ids": [e.0, f.0]})); + let compound = made(run(&mut s, "object.compoundPath.make", json!({}))); + let (g, h) = (rect(&mut s), rect(&mut s)); + run(&mut s, "select.set", json!({"ids": [g.0, h.0]})); + let shape = made(run(&mut s, "object.compoundShape.make", json!({}))); + let lone = rect(&mut s); + let layer = made(run(&mut s, "layer.new", json!({}))); + let (j, k) = (rect(&mut s), rect(&mut s)); + run(&mut s, "appearance.addStroke", json!({"ids": [layer.0]})); + { + let doc = &s.doc().unwrap().doc; + assert_eq!((doc.parent_of(j), doc.parent_of(k)), (Some(layer), Some(layer)), "the new layer holds the last two"); + assert_eq!((doc.parent_of(e), doc.parent_of(g)), (Some(compound), Some(shape))); + assert!(doc.node(owned).unwrap().appearance.stroke().is_some() && doc.node(layer).unwrap().appearance.stroke().is_some()); + } + let named = json!({"ids": [plain.0, a.0, owned.0, owned.0, c.0, e.0, compound.0, g.0, lone.0, layer.0, j.0]}); + let cases = [ + named.clone(), + json!({"ids": [j.0, h.0, f.0, b.0, plain.0, layer.0, owned.0, k.0, shape.0]}), + json!({"ids": [base.0, layer.0, base.0]}), + json!({"ids": [d.0, owned.0, base.0]}), + json!({"ids": []}), + ]; + for p in &cases { + assert_eq!(own_stroke_or_leaves(&s, p).unwrap(), listed_merge(&s, p), "{p}"); + } + run(&mut s, "select.set", json!({"ids": [lone.0, owned.0, f.0, plain.0, b.0, layer.0]})); + assert_eq!(own_stroke_or_leaves(&s, &json!({})).unwrap(), listed_merge(&s, &json!({})), "the selection"); + + // The edit reaches every listed target, counting a repeated one once, and leaves the other + // member of the group with its own stroke alone. + let want = listed_merge(&s, &named); + assert_eq!(want.iter().filter(|id| **id == owned).count(), 2, "{want:?}"); + let distinct: std::collections::HashSet<_> = want.iter().collect(); + let before = s.doc().unwrap().doc.node(d).unwrap().clone(); + let r = run(&mut s, "stroke.set", json!({"ids": named["ids"], "weight": 3})); + let doc = &s.doc().unwrap().doc; + assert_eq!(r["objects"], distinct.len(), "{r} {want:?}"); + for id in &want { + assert_eq!(doc.node(*id).unwrap().appearance.stroke().map(|st| st.width), Some(3.0), "{id:?}"); + } + assert_eq!(doc.node(d), Some(&before), "a member reached only through its group's own stroke is left alone"); + } } diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index e9fc9a6820..4c7cc411ef 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1815,6 +1815,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - The [About brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html) page describes up to five Pattern brush tiles: sides, inner corner, outer corner, beginning and end. The archived [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page says to add pattern tiles to the Swatches panel and select a swatch from the scroll list for each tile. Pattern Brush Options offers document pattern swatches in all five tile menus, including swatches named like built-in choices. The brush copies each swatch's whole art and tile frame. Side requires art; explicit None on a corner prevents fallback to the other corner's art. After a swatch is deleted, the brush keeps drawing its copied art and shows it as Original. The cited pages do not describe copying the whole art, requiring Side, suppressing corner fallback after explicit None, or showing deleted swatch art as Original. `brush.options` accepts swatch names and an object form for names that match built-in choices, and rejects unknown patterns before editing. Evidence: `tests::brushsym::pattern_tile_choices_copy_whole_swatch_art_and_reject_invalid_side` and `tests::brushsym::pattern_tile_object_selects_reserved_swatch_names` (vectorcraft-engine), `tests::pattern_corner_source_none_leaves_that_kind_of_corner_empty` (vectorcraft-brush), and `dialogs::brush_options::tests::pattern_tile_menus_use_document_patterns_and_side_none_keeps_dialog_open`, `dialogs::brush_options::tests::pattern_options_borrowed_swatch_corner_keeps_its_frame`, and `dialogs::brush_options::tests::pattern_options_selects_swatches_with_reserved_names` (vectorcraft-ui-egui). - **Appearance:** the Appearance panel's selected row drives every paint, stroke, gradient and transparency edit (`item` on the commands); effects apply to one fill or stroke; per-item Opacity popups, whose blend-mode list and opacity slider stay open inside them (#430; the Control bar's Stroke popover too); Mixed Appearances, Layers target dots and basic-appearance rules. Effects can be reordered, moved between items and copied by dragging; Show All Hidden Attributes; clicking an effect edits it in place; the object thumbnail drags onto art; effects render on type, images, symbols, blends, envelopes, meshes and repeats, and per-item raster effects export. Groups, layers and type have their own fills, strokes and effects (Contents and Characters rows); the Layers panel's target circles target layers, groups and objects; Expand Appearance turns fills, strokes, effects and brushes into objects. Fill and stroke paint (Fill, Stroke, None, Apply Last Color and Apply Last Gradient, also on characters selected with the Type tool), the Stroke panel's options, gradient and freeform point edits, Swap Fill and Stroke, Default Fill and Stroke, the Eyedropper, and the Appearance panel's item edits, Clear Appearance, Reduce to Basic Appearance, Remove Item, item reordering and Move Appearance record no undo step when they change nothing. + A Stroke panel edit (`stroke.set` with no `item`) checks each object it collects against a set of the objects already listed, so collecting its targets takes time in step with the number of objects, and the list and its order are the same as before. With 20,000 paths in one group, collecting the targets takes 0.66 ms of thread CPU time on Linux, against 55 ms when each object is looked up in the list, and the whole command takes 60 ms (`crates/engine/examples/stroke_targets_bench.rs`; `cmd::stroke::tests::stroke_targets_match_the_listed_merge`). A Layers panel target circle dropped on the panel's Delete Selection button reduces that layer, group or object to basic appearance (`appearance.reduceToBasic`) in one undo step and deletes nothing, as the [Appearance attributes](https://helpx.adobe.com/illustrator/using/appearance-attributes.html) help page describes for that drag. Which fill and stroke stay (the topmost visible ones), that a layer or group keeps only the rows it had, and that the object's opacity and blend mode stay are VectorCraft's own rules (`panels::layers` test `dropping_a_target_circle_on_the_trash_reduces_it_to_basic_appearance`). The Add New Effect popup (Appearance panel, Properties), the Appearance panel's swatch picker, the Gradient panel's gradient swatches menu and the Image Trace button's list of presets stop at the bottom of a short window, and the mouse wheel or the scroll bar reaches their last rows. A list that fits does not scroll (`a_long_swatch_picker_scrolls_inside_a_short_window`). An image's own fills and strokes draw the shape that a Convert to Shape or Outline Object effect on them gives them (the image's box, or the outline of the image's opaque area or its frame, reshaped by the effects after it), under or over the image as its Contents row says, on the canvas, in exports and through Expand Appearance; new fills and strokes on an image go under it. Without one of those effects they draw nothing, and Use Preview Bounds then measures an image by its frame. From c226533bc9ad806df1b032b76de5c73a3618e030 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 17 Nov 2026 09:49:45 -0800 Subject: [PATCH 101/176] Swatches: linking the selection's paints checks ancestors through a set Add Used Colors and New Color Group link the selected art's paints to global swatches through Document::map_solid_paints_in, which drops each id that sits inside another listed id. It searched the whole id list for each ancestor of each id, so the work grew with the square of the selection. It now looks each ancestor up in a set of the ids, as without_inner in crates/engine/src/cmd/edit.rs does. The roots keep the order of the list, duplicates and ids missing from the document, so the same paints are linked in the same order. - mapping_within_ids_matches_a_search_of_the_ids compares the count, the paints visited and the resulting document with the search for every list of up to three ids from a nested tree (nested ids in both orders, duplicates, a missing id and an empty list). - crates/engine/examples/link_colors_bench.rs times both ways in one process. With 20,000 selected rectangles the call takes 16 ms of CPU time instead of 128 ms; with 2,000 it takes 1.4 ms instead of 2.5 ms. --- crates/doc/src/swatches.rs | 74 ++++++- crates/engine/examples/link_colors_bench.rs | 217 ++++++++++++++++++++ docs/target-app-parity.md | 1 + 3 files changed, 291 insertions(+), 1 deletion(-) create mode 100644 crates/engine/examples/link_colors_bench.rs diff --git a/crates/doc/src/swatches.rs b/crates/doc/src/swatches.rs index 9c25427846..0ee84dc32c 100644 --- a/crates/doc/src/swatches.rs +++ b/crates/doc/src/swatches.rs @@ -187,8 +187,9 @@ impl Document { /// [`Document::map_solid_paints`] limited to the art in the subtrees of `ids` (each paint /// visited once even when an id is inside another). pub fn map_solid_paints_in(&mut self, ids: &[NodeId], f: &mut LinkFn) -> usize { + let listed: HashSet<NodeId> = ids.iter().copied().collect(); let roots: Vec<NodeId> = - ids.iter().copied().filter(|id| !self.ancestry(*id).is_some_and(|a| a[..a.len() - 1].iter().any(|p| ids.contains(p)))).collect(); + ids.iter().copied().filter(|id| !self.ancestry(*id).is_some_and(|a| a[..a.len() - 1].iter().any(|p| listed.contains(p)))).collect(); let mut n = 0; let mut g = relink(f); for id in roots { @@ -844,6 +845,77 @@ mod tests { assert_eq!(colors, [(Color::rgb(1.0, 0.0, 0.0), None)]); } + /// [`Document::map_solid_paints_in`] with each ancestor searched for in `ids` rather than looked up in a set. + fn map_solid_paints_in_by_search(d: &mut Document, ids: &[NodeId], f: &mut LinkFn) -> usize { + let roots: Vec<NodeId> = + ids.iter().copied().filter(|id| !d.ancestry(*id).is_some_and(|a| a[..a.len() - 1].iter().any(|p| ids.contains(p)))).collect(); + let mut n = 0; + let mut g = relink(f); + for id in roots { + let Some(node) = d.node(id) else { continue }; + if let Some((new, count)) = map_node(node, &mut g) + && let Some(slot) = d.node_mut(id) + { + *slot = new; + n += count; + } + } + n + } + + #[test] + fn mapping_within_ids_matches_a_search_of_the_ids() { + // Two layers: the first holds group `outer` (group `inner` with two rectangles, and a + // rectangle) and a rectangle; the second holds a rectangle. Each rectangle has its own color. + let mut d = Document::new(100.0, 100.0); + let first = d.layers[0].id; + let second = d.alloc_id(); + d.insert(None, usize::MAX, Node::layer(second, "Second", crate::LayerColor::Preset(1))).unwrap(); + let rect = |d: &mut Document, i: u8| { + let id = d.alloc_id(); + let r = shapes::rectangle(Rect::new(0.0, 0.0, 10.0, 10.0)); + let color = Color::rgb(f32::from(i) / 8.0, 0.0, 0.0); + (id, Arc::new(Node::path(id, r, Appearance::basic(Paint::solid(color), Paint::solid(color), 1.0)))) + }; + let (r1, n1) = rect(&mut d, 1); + let (r2, n2) = rect(&mut d, 2); + let (r3, n3) = rect(&mut d, 3); + let (r4, n4) = rect(&mut d, 4); + let (r5, n5) = rect(&mut d, 5); + let (inner, outer) = (d.alloc_id(), d.alloc_id()); + let outer_node = Node::group(outer, vec![Arc::new(Node::group(inner, vec![n1, n2])), n3]); + d.insert(Some(first), usize::MAX, outer_node).unwrap(); + d.insert(Some(first), usize::MAX, Arc::unwrap_or_clone(n4)).unwrap(); + d.insert(Some(second), usize::MAX, Arc::unwrap_or_clone(n5)).unwrap(); + let missing = NodeId(u64::MAX); + let all = [first, second, outer, inner, r1, r2, r3, r4, r5, missing]; + // Every list of up to three of them: nested ids in both orders, duplicates, a missing id and none. + let mut lists: Vec<Vec<NodeId>> = vec![vec![]]; + let mut shorter: Vec<Vec<NodeId>> = vec![vec![]]; + for _ in 0..3 { + shorter = shorter.iter().flat_map(|l| all.map(|id| [l.as_slice(), &[id]].concat())).collect(); + lists.extend(shorter.iter().cloned()); + } + assert_eq!(lists.len(), 1 + 10 + 100 + 1000); + for ids in &lists { + // A callback that changes every paint it visits, so a paint visited twice counts twice. + let run = |map: &dyn Fn(&mut Document, &[NodeId], &mut LinkFn) -> usize| { + let mut d = d.clone(); + let mut visits = vec![]; + let n = map(&mut d, ids, &mut |c, s, t| { + visits.push((*c, s.clone(), *t)); + *s = Some(format!("{}", visits.len())); + *t *= 0.5; + true + }); + (n, visits, d.layers) + }; + let by_set = run(&|d, ids, f| d.map_solid_paints_in(ids, f)); + let by_search = run(&|d, ids, f| map_solid_paints_in_by_search(d, ids, f)); + assert_eq!(by_set, by_search, "{ids:?}"); + } + } + /// The colors [`node_colors`] visits, in its order, by a [`Node::walk`] that reads the whole subtree. fn full_walk(n: &Node, f: &mut dyn FnMut(&Color, Option<&str>)) { n.walk(&mut |m| { diff --git a/crates/engine/examples/link_colors_bench.rs b/crates/engine/examples/link_colors_bench.rs new file mode 100644 index 0000000000..d403339706 --- /dev/null +++ b/crates/engine/examples/link_colors_bench.rs @@ -0,0 +1,217 @@ +//! `cargo run --release -p vectorcraft-engine --example link_colors_bench` prints the time +//! `Document::map_solid_paints_in` takes to link the paints of selected objects to swatches, as Add Used +//! Colors and New Color Group do for the selection with global swatches, on synthetic documents: 2,000 and +//! 20,000 rectangles in one layer, and 5,000 rectangles in 1,000 groups of groups, selected with and +//! without the groups that hold them. The fills and strokes use 50 colors, each with a swatch to link to. +//! For each it times two ways of finding the selected objects that no other selected object holds: a +//! search of the id list for each ancestor of each id, and a lookup of each ancestor in a set of the ids +//! (as `map_solid_paints_in` does). Both then link the same paints in the same loop. It checks that both +//! give the same count, visit the same paints in the same order and leave the same document as +//! `map_solid_paints_in` before it times them. +//! `ITERS` sets the runs per row (default 7); the two ways run in alternating order, each run links 10 +//! fresh copies of the document, and each row is the median time of one call. On Linux the times are the CPU time of the main thread, which runs +//! everything, in ms; elsewhere they are wall times. +// Example (dev tool): unwrapping and panicking on failure is fine here, unlike in shipped code (AGENTS.md › Robustness). +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::collections::{HashMap, HashSet}; +use std::hint::black_box; +use std::sync::Arc; +use std::time::Instant; + +use vectorcraft_color::{Color, Paint}; +use vectorcraft_doc::swatches::{LinkFn, map_node_solid_paints}; +use vectorcraft_doc::{Appearance, Document, Node, NodeId}; +use vectorcraft_geom::{Rect, shapes}; + +/// The colors the rectangles use, each with a swatch to link to. +const COLORS: usize = 50; + +/// The calls in each timed run; a row gives the time of one call. +const REPS: usize = 10; + +/// A way of finding the ids that no other listed id holds. +type Roots = fn(&Document, &[NodeId]) -> Vec<NodeId>; + +/// A way of applying a link function to the paints of the listed ids, returning the count changed. +type Map<'a> = dyn FnMut(&mut Document, &[NodeId], &mut LinkFn) -> usize + 'a; + +fn iters() -> usize { + std::env::var("ITERS").ok().and_then(|v| v.parse().ok()).unwrap_or(7).max(1) +} + +fn median(mut ms: Vec<f64>) -> f64 { + ms.sort_by(f64::total_cmp); + ms[ms.len() / 2] +} + +/// The CPU time of the calling thread in ns, from `/proc/thread-self/schedstat` (Linux only). +fn thread_cpu_ns() -> Option<u64> { + std::fs::read_to_string("/proc/thread-self/schedstat").ok()?.split_whitespace().next()?.parse().ok() +} + +/// The time `f` takes, in ms: CPU time where the system reports it, wall time otherwise. +fn measure(f: impl FnOnce()) -> f64 { + match thread_cpu_ns() { + Some(start) => { + f(); + thread_cpu_ns().map_or(f64::NAN, |end| end.saturating_sub(start) as f64 / 1e6) + } + None => { + let t = Instant::now(); + f(); + t.elapsed().as_secs_f64() * 1000.0 + } + } +} + +/// Color `i` of [`COLORS`]: each has its own red value. +fn color(i: usize) -> Color { + Color::rgb(i as f32 / COLORS as f32, 0.5, 0.25) +} + +/// The bits of a color's red value, which tell the colors of [`color`] apart; `u32::MAX` for other color models. +fn red_bits(c: &Color) -> u32 { + match c { + Color::Rgb { r, .. } => r.to_bits(), + _ => u32::MAX, + } +} + +/// The ids in the order given, less those with an ancestor in the list: a search of the list for each ancestor. +fn roots_by_search(d: &Document, ids: &[NodeId]) -> Vec<NodeId> { + ids.iter().copied().filter(|id| !d.ancestry(*id).is_some_and(|a| a[..a.len() - 1].iter().any(|p| ids.contains(p)))).collect() +} + +/// [`roots_by_search`] with each ancestor looked up in a set of the ids. +fn roots_by_set(d: &Document, ids: &[NodeId]) -> Vec<NodeId> { + let listed: HashSet<NodeId> = ids.iter().copied().collect(); + ids.iter().copied().filter(|id| !d.ancestry(*id).is_some_and(|a| a[..a.len() - 1].iter().any(|p| listed.contains(p)))).collect() +} + +/// `f` applied to the paints of the subtrees of the ids `roots` finds, each node holding a changed +/// paint put in place: the work of `map_solid_paints_in`. +fn map_in(d: &mut Document, ids: &[NodeId], roots: Roots, f: &mut LinkFn) -> usize { + let mut n = 0; + for id in roots(d, ids) { + let Some(mut node) = d.node(id).cloned() else { continue }; + let count = map_node_solid_paints(&mut node, f); + if count > 0 + && let Some(slot) = d.node_mut(id) + { + *slot = node; + n += count; + } + } + n +} + +/// Link every paint whose color has a swatch to that swatch, as Add Used Colors does for global +/// swatches, recording each paint visited. Returns the count and the visits. +fn link(d: &mut Document, ids: &[NodeId], map: &mut Map) -> (usize, Vec<(Color, Option<String>)>) { + let names: HashMap<u32, String> = (0..COLORS).map(|i| (red_bits(&color(i)), format!("Swatch {i}"))).collect(); + let mut visits = vec![]; + let n = map(d, ids, &mut |c, s, _| { + visits.push((*c, s.clone())); + match names.get(&red_bits(c)) { + Some(name) if s.is_none() => { + *s = Some(name.clone()); + true + } + _ => false, + } + }); + (n, visits) +} + +fn rect(d: &mut Document, i: usize) -> Arc<Node> { + let id = d.alloc_id(); + let (x, y) = ((i % 100) as f64 * 12.0, (i / 100) as f64 * 12.0); + let r = shapes::rectangle(Rect::new(x, y, x + 10.0, y + 10.0)); + let a = Appearance::basic(Paint::solid(color(i % COLORS)), Paint::solid(color((i + 7) % COLORS)), 1.0); + Arc::new(Node::path(id, r, a)) +} + +/// `n` rectangles in the first layer, all selected. +fn flat(n: usize) -> (Document, Vec<NodeId>) { + let mut d = Document::new(1600.0, 1200.0); + let l = d.layers[0].id; + let mut ids = vec![]; + for i in 0..n { + let node = rect(&mut d, i); + ids.push(node.id); + d.insert(Some(l), usize::MAX, Arc::unwrap_or_clone(node)).unwrap(); + } + (d, ids) +} + +/// 1,000 groups in the first layer, each holding a group of 5 rectangles: the rectangles, and with +/// `groups` the two groups above each of them too, listed first. +fn nested(groups: bool) -> (Document, Vec<NodeId>) { + let mut d = Document::new(1600.0, 1200.0); + let l = d.layers[0].id; + let (mut outer_ids, mut leaves) = (vec![], vec![]); + for g in 0..1_000 { + let rects: Vec<Arc<Node>> = (0..5).map(|i| rect(&mut d, g * 5 + i)).collect(); + leaves.extend(rects.iter().map(|r| r.id)); + let inner = Node::group(d.alloc_id(), rects); + let outer = Node::group(d.alloc_id(), vec![Arc::new(inner.clone())]); + if groups { + outer_ids.extend([outer.id, inner.id]); + } + d.insert(Some(l), usize::MAX, outer).unwrap(); + } + outer_ids.extend(leaves); + (d, outer_ids) +} + +fn bench(name: &str, (doc, ids): (Document, Vec<NodeId>)) { + let mut shipped = doc.clone(); + let want = link(&mut shipped, &ids, &mut |d, ids, f| d.map_solid_paints_in(ids, f)); + for roots in [roots_by_search as Roots, roots_by_set] { + let mut d = doc.clone(); + let got = link(&mut d, &ids, &mut |d, ids, f| map_in(d, ids, roots, f)); + assert_eq!(got, want, "{name}: the same count and visits"); + assert_eq!(d.layers, shipped.layers, "{name}: the same document"); + } + let (mut old, mut new, mut real) = (vec![], vec![], vec![]); + let timed = |map: &mut Map| { + let mut docs = vec![doc.clone(); REPS]; + measure(|| { + for d in &mut docs { + black_box(link(d, black_box(&ids), &mut *map)); + } + }) / REPS as f64 + }; + for i in 0..iters() { + let run = |roots: Roots, out: &mut Vec<f64>| out.push(timed(&mut |d, ids, f| map_in(d, ids, roots, f))); + if i % 2 == 0 { + run(roots_by_search, &mut old); + run(roots_by_set, &mut new); + } else { + run(roots_by_set, &mut new); + run(roots_by_search, &mut old); + } + real.push(timed(&mut |d, ids, f| d.map_solid_paints_in(ids, f))); + } + let (old, new, real) = (median(old), median(new), median(real)); + println!(" {name:<46} {:>7} {:>7} {old:>12.3} {new:>12.3} {real:>12.3} {:>8.1}x", ids.len(), want.0, old / new); +} + +fn main() { + let unit = if thread_cpu_ns().is_some() { "CPU ms" } else { "wall ms" }; + println!( + " {:<46} {:>7} {:>7} {:>12} {:>12} {:>12} {:>9}", + "document", + "ids", + "linked", + format!("search, {unit}"), + format!("set, {unit}"), + format!("shipped, {unit}"), + "speedup" + ); + bench("2,000 rectangles in one layer", flat(2_000)); + bench("20,000 rectangles in one layer", flat(20_000)); + bench("5,000 rectangles in 1,000 groups of groups", nested(false)); + bench("the same with the 2,000 groups listed first", nested(true)); +} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index e9fc9a6820..cbc0446812 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1726,6 +1726,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Editing, renaming, deleting or merging a global swatch also changes the colors linked to it in graph designs, the art of brushes and the tile that pattern editing's Cancel puts back, in the same undo step as the rest of the art; Default Swatches with replace unlinks them there too. A swatch step in `command.batch` (Delete, Swatch Options, Merge, Edit Color Group) changes the fill and stroke for new art as the command run on its own does, so art drawn later in the batch or after it takes the same paint; a batch that fails, and a canceled batch preview, put back the paints it started with, and a canceled Swatch Options preview leaves them as they were. These swatch commands also change the fills and strokes of the appearance new art takes, and Undo and Redo of the command or the batch put the paints for new art back with the swatches. Spot Colors options (`swatch.spotOptions`) and Default Swatches with replace (`swatch.resetDefaults {replace: true}`) as `command.batch` steps also change the fill and stroke for new art as each command run on its own does: a fill or stroke linked to a Lab spot swatch keeps its link and tint and takes the Lab values or their CMYK equivalent, and one linked to a swatch the replace removes keeps its color and loses the link. Evidence: `swatch_steps_in_a_batch_change_the_new_art_paints_as_commands_do`, `spot_colors_options_in_a_batch_change_the_new_art_paints_as_the_command_does`, `default_swatches_replace_in_a_batch_unlinks_the_new_art_paints_as_the_command_does`, `undo_and_redo_of_a_swatch_edit_put_back_the_new_art_paints`, `swatch_edits_reach_the_paints_of_the_new_art_template`, `a_failed_batch_puts_back_the_new_art_paints_a_swatch_step_changed` and `canceling_a_swatch_options_preview_keeps_the_new_art_paints` in `crates/engine/src/tests/swatches.rs`. Add Used Colors (`swatch.addUsedColors`) and Select All Unused (`swatch.unused`) look colors, swatch names, links, tints and gradients up in hash sets instead of searching every swatch and color for each color or linked paint (New Color Group from artwork too), and New Swatch with several colors (`swatch.new`), New Color Group (`swatch.newGroup`) and Edit Color Group (`swatch.editGroup`) name their new swatches from one set of the names already taken. The new swatches keep their names, order and links, and Select All Unused lists the same swatches. Evidence: `add_used_colors_adds_each_new_color_once_with_free_names`, `add_used_colors_global_links_every_paint_of_a_new_color`, `unused_matches_links_tints_colors_gradients_and_patterns_exactly`, `new_swatches_from_colors_are_numbered_after_names_already_taken`, `new_color_group_numbers_its_colors_after_the_group_and_its_moved_swatches`, `new_color_group_from_artwork_lists_each_color_once_with_free_names` and `edit_color_group_numbers_extra_colors_after_the_names_it_keeps` in `crates/engine/src/tests/swatchcmds.rs`; `free_swatch_names_match_naming_each_swatch_as_it_is_added` and `free_swatch_names_match_new_swatch_names_as_swatches_are_added` in `crates/doc/src/swatches.rs`. + When Add Used Colors and New Color Group link the selected art's paints to global swatches, they look each selected object's groups and layer up in a set of the selected ids instead of searching the whole selection for each one, so linking 20,000 selected rectangles takes 16 ms of CPU time instead of 128 ms (`cargo run --release -p vectorcraft-engine --example link_colors_bench`). The same paints are linked, in the same order. Evidence: `mapping_within_ids_matches_a_search_of_the_ids` in `crates/doc/src/swatches.rs`. - **Colorized images (#1466):** a fill color applied to a selected grayscale or 1-bit image (`paint.setFill`) colorizes it with black, white, a process color or a spot color, and refuses a process color when the image has an alpha channel ([Convert color modes](https://web.archive.org/web/20251220223850/https://helpx.adobe.com/illustrator/desktop/manage-colors/select-and-adjust-colors/convert-color-modes.html), "Colorize Grayscale or 1-bit images"); black and white are accepted there too. The canvas draws each pixel in the color as far as the pixel is dark, with white pixels transparent; PDF export writes the image in the color (a spot color as its ink, Registration in every ink) with the image as its soft mask; Separations Preview and printed separations show it on its color's plates; native files keep the color. SVG writes the fill color through a coverage mask (or a colorized PNG in Tiny 1.2); EPS writes binary coverage as an image mask in the color's ink, and a grayscale image as ink samples scaled by coverage, with white pixels left out at Level 3 and gray midtones written over white. The prompt for deleting several swatches and groups uses the interface language's plural form for the count. Evidence: `deleting_several_swatches_uses_each_count_form` in `crates/ui-egui/src/panels/swatches/tests.rs`. - **Colorized images (#1466):** a fill color applied to a selected grayscale or 1-bit image (`paint.setFill`) colorizes it with black, white, a process color or a spot color, and refuses a process color when the image has an alpha channel ([Convert color modes](https://web.archive.org/web/20251220223850/https://helpx.adobe.com/illustrator/desktop/manage-colors/select-and-adjust-colors/convert-color-modes.html), "Colorize Grayscale or 1-bit images"); black and white are accepted there too. The canvas draws each pixel in the color as far as the pixel is dark, with white pixels transparent; PDF export writes the image in the color (a spot color as its ink, Registration in every ink) with the image as its soft mask; Separations Preview and printed separations show it on its color's plates; native files keep the color. EPS and SVG write the image's own pixels. From 25592316641f8607ea6224acd8b59ad266a7a847 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 17 Nov 2026 09:49:50 -0800 Subject: [PATCH 102/176] Print: a near black linked to a missing swatch keeps its faint ink off PostScript plates On PostScript separations, up to half a percent of another ink in a color that counts as 100% black is left off that ink's plate, so an overprinting near black does not knock out the ink below it. A color linked to a swatch the document does not have was left out of that rule, although it separates from its own values like an unlinked color and Overprint Black marks it to overprint. A 100% K with 0.4% cyan linked to such a name then stayed on the cyan plate and knocked out the cyan under it. A link to a missing swatch now counts as unlinked for this rule, on solid fills, strokes, character fills and gradient stops. Spot swatches and Registration are still excluded, and PDF plates still draw the faint ink. --- crates/pdf/src/print/plates.rs | 7 ++-- crates/pdf/src/tests/print.rs | 74 ++++++++++++++++++++++++++++++++++ docs/target-app-parity.md | 2 +- 3 files changed, 79 insertions(+), 4 deletions(-) diff --git a/crates/pdf/src/print/plates.rs b/crates/pdf/src/print/plates.rs index 74102373e5..5b33683dcf 100644 --- a/crates/pdf/src/print/plates.rs +++ b/crates/pdf/src/print/plates.rs @@ -171,10 +171,11 @@ impl<'a> Separator<'a> { /// swatch link). Any ink above zero puts ink down, except on PostScript plates for a color that /// counts as 100% black ([`vectorcraft_doc::overprint::is_black_ink`], as /// [`vectorcraft_doc::overprint::OverprintBlack::default`] judges it) and is not linked to a - /// spot swatch, to Registration or to a swatch the document lacks: up to the half a percent of - /// another ink such a black may carry counts as none. + /// spot swatch or to Registration: up to the half a percent of another ink such a black may + /// carry counts as none. A link to a swatch the document lacks separates as the color's own + /// values, so such a black counts as unlinked. fn no_ink(&self, plate: &str, p: &Paint) -> bool { - let process = |swatch: Option<&str>| swatch.is_none_or(|n| n != REGISTRATION && self.doc.swatch(n).is_some_and(|w| !w.spot)); + let process = |swatch: Option<&str>| swatch.is_none_or(|n| n != REGISTRATION && self.doc.swatch(n).is_none_or(|w| !w.spot)); let none = |c: &Color, process: bool, ink: f32| ink <= 0.0 || (self.postscript && process && ink <= 0.005 && is_black_ink(c, 1.0, false)); match p { Paint::Solid { color, swatch, tint } => { diff --git a/crates/pdf/src/tests/print.rs b/crates/pdf/src/tests/print.rs index 49a34ff428..588273faf9 100644 --- a/crates/pdf/src/tests/print.rs +++ b/crates/pdf/src/tests/print.rs @@ -829,6 +829,80 @@ fn overprint_black_keeps_the_cyan_under_near_and_freeform_blacks_on_postscript_p assert_eq!((fills(&p.plates[0]), fills(&p.plates[3])), (1, 4), "the cyan plate, the Black plate"); } +#[test] +fn overprint_black_keeps_the_cyan_under_a_near_black_linked_to_a_missing_swatch_on_postscript_plates() { + // 0.4% cyan beside 100% K, linked to a swatch the document lacks: it separates from its own + // values and the option marks it to overprint, so it counts as black like an unlinked color. + let near = Paint::Solid { color: Color::cmyk(0.004, 0.0, 0.0, 1.0), swatch: Some("Missing".into()), tint: 1.0 }; + let square = + Node::path(vectorcraft_doc::NodeId(0), shapes::rectangle(Rect::new(10.0, 15.0, 30.0, 35.0)), Appearance::basic(near, Paint::None, 0.0)); + let d = over_cyan(vec![square]); + assert!(d.swatch("Missing").is_none()); + let opts = PrintOptions { + settings: settings(json!({"output": {"mode": "separations", "overprintBlack": true}})), + postscript: true, + ..Default::default() + }; + let p = plan(&d, &opts).unwrap(); + let fills = |doc: &Document| { + let mut count = 0; + doc.walk(|n| count += usize::from(n.appearance.fill().is_some_and(|f| !f.paint.is_none()))); + count + }; + assert_eq!((fills(&p.plates[0]), fills(&p.plates[3])), (1, 2), "the cyan plate, the Black plate"); +} + +#[test] +fn overprinting_near_blacks_linked_to_a_missing_swatch_keep_the_cyan_on_postscript_plates() { + // 0.4% cyan beside 100% K, linked to a swatch the document lacks and set to overprint, on a + // fill, a stroke, a character fill and a linear gradient's stops: a PostScript cyan plate draws + // it as nothing, as it does an unlinked black, and a PDF cyan plate draws it. A faint cyan that + // is not black, linked to the same name, stays on both. + let missing = |color: Color| Paint::Solid { color, swatch: Some("Missing".into()), tint: 1.0 }; + let near = Color::cmyk(0.004, 0.0, 0.0, 1.0); + let faint = Color::cmyk(0.004, 0.5, 0.0, 0.0); + let square = |x: f64, fill: Paint, stroke: Paint| { + let mut n = + Node::path(vectorcraft_doc::NodeId(0), shapes::rectangle(Rect::new(x, 15.0, x + 20.0, 35.0)), Appearance::basic(fill, stroke, 2.0)); + if let Some(f) = n.appearance.fill_mut() { + f.overprint = true; + } + if let Some(s) = n.appearance.stroke_mut() { + s.overprint = true; + } + n + }; + let stop = |offset: f32| GradientStop { swatch: Some("Missing".into()), ..GradientStop::new(offset, near) }; + let linear = GradientPaint::new(Gradient::new(GradientKind::Linear, vec![stop(0.0), stop(1.0)])); + let style = vectorcraft_doc::CharStyle { fill: missing(near), overprint_fill: true, ..Default::default() }; + let text = vectorcraft_doc::TextObject::point(vectorcraft_geom::Point::new(20.0, 60.0), "Hi", style); + let d = over_cyan(vec![ + square(10.0, missing(near), Paint::None), + square(40.0, Paint::None, missing(near)), + square(70.0, Paint::Gradient(Box::new(linear)), Paint::None), + square(100.0, missing(faint), Paint::None), + Node::new(vectorcraft_doc::NodeId(0), NodeKind::Text(Box::new(text))), + ]); + assert!(d.swatch("Missing").is_none()); + // The fills, strokes and character fills plate `plate` draws. + let drawn = |postscript: bool, plate: usize| { + let opts = PrintOptions { settings: settings(json!({"output": {"mode": "separations"}})), postscript, ..Default::default() }; + let p = plan(&d, &opts).unwrap(); + let (mut fills, mut strokes, mut chars) = (0, 0, 0); + p.plates[plate].walk(|n| { + fills += usize::from(n.appearance.fill().is_some_and(|f| !f.paint.is_none())); + strokes += usize::from(n.appearance.stroke().is_some_and(|s| !s.paint.is_none())); + if let NodeKind::Text(t) = &n.kind { + chars += t.runs.iter().filter(|r| !r.style.fill.is_none()).count(); + } + }); + (fills, strokes, chars) + }; + assert_eq!(drawn(true, 0), (2, 0, 0), "PostScript cyan plate: the cyan and the faint fill"); + assert_eq!(drawn(false, 0), (4, 1, 1), "PDF cyan plate: the cyan, the fill, the gradient, the faint fill, the stroke and the type"); + assert_eq!(drawn(true, 3), (3, 1, 1), "PostScript Black plate: every black, not the faint fill"); +} + #[test] fn an_overprinting_fill_keeps_its_faint_ink_on_pdf_plates() { // 0.4% cyan beside 100% K, set to overprint: a PDF plate draws it with Darken, a PostScript diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index e9fc9a6820..9c0996b834 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2066,7 +2066,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Separations Preview shows placed and embedded raster images on the visible plates, as it shows vector art (#4153): an RGB image's pixels are separated into process inks with the proof setup's intent, a CMYK image shows its own inks, a hidden plate's ink leaves the image, and with one plate visible the image shows that plate's ink as a grey. Raster images carry no spot ink, so a spot plate shown alone shows them as paper; a colorized image shows its color's plates. Emoji and other bitmap glyphs follow the same rule. The plate-filtered pixels and their reduced-size copies are kept apart from the image's own pixels, for each set of visible plates, proof setup and color settings, and with the preview off nothing changes. Evidence: `tests::colorize::separations_preview_shows_an_rgb_images_process_inks`, `separations_preview_shows_a_cmyk_images_own_inks`, `separations_preview_keeps_an_images_pixels_per_plate_set`. Print preview fidelity remains the open gap, so scores and hours are unchanged. - Desktop print transport uses `craft-print` for CUPS and modern Windows. Sheet composition, copies, separations and colour management remain in VectorCraft. The Print dialog's Media list also carries the Japanese papers — JIS B4 257 × 364 mm, JIS B5 182 × 257 mm and JIS B6 128 × 182 mm beside the ISO B4/B5 (250 × 353 and 176 × 250 mm, kept so settings and presets saved before them keep their paper), and はがき 100 × 148 mm, 往復はがき 148 × 200 mm, 封筒 長形3号 120 × 235 mm, 長形4号 90 × 225 mm, 角形2号 240 × 332 mm, 角形3号 216 × 277 mm and 四六判 127 × 188 mm; the JSON id or the dialog label names a paper, any case and spacing (`B5 (JIS)` or `b5jis`) (`crates/pdf/src/print/settings.rs`, `crates/pdf/src/tests/print.rs`). The print-preview and physical-device fidelity gaps remain, so print scores and hours are unchanged. - The Print dialog's Document Ink Options list shows an icon before each spot ink's name, and a click on it prints that one ink as process inks (on the Cyan, Magenta, Yellow and Black plates, with no plate of its own) or as a spot ink again, as [the help page](https://helpx.adobe.com/illustrator/using/printing-color-separations.html) describes for single spot colors. Other spot inks keep their plates, and spot gradient stops and DCS images' spot plates follow each ink's choice (`print.setup {settings: {output: {inks: [{name, convertToProcess: true}]}}}`, kept with the document and in print presets; `print.preview` lists every ink as `documentInks`). These are VectorCraft's own rules: Convert All Spot Colors to Process converts every spot ink and dims the icons while keeping each ink's own choice, a converted ink's Print, Frequency and Angle are dimmed and kept, and process inks and Registration have no icon. Evidence: `print::one_spot_ink_converts_to_process_and_the_others_keep_their_plates`, `print::converting_every_spot_ink_overrides_and_keeps_each_inks_own_choice`, `print::a_spot_gradient_stop_prints_its_process_plates`, `cmykimages::a_dcs_image_converts_only_the_spot_ink_chosen`, `tests::print::a_spot_ink_converted_to_process_is_saved_and_listed_without_a_plate`, `dialogs::tests_print::a_spot_inks_icon_converts_it_to_process_and_back`. Print scores and hours are unchanged. - - The Print dialog's Output section has Overprint Black under Convert All Spot Colors to Process, off by default and available with Separations ([Print color separations](https://helpx.adobe.com/illustrator/using/printing-color-separations.html) lists it among the separation options): black art then leaves the inks under it on the other plates (`print.setup {settings: {output: {overprintBlack: true}}}`, kept with the document and in print presets). Solid 100% K or 100% gray fills, strokes and characters (to within half a percent, as Edit › Edit Colors › Overprint Black counts them), and gradients whose every stop (every color point of a freeform gradient) is, overprint; rich, RGB, Lab, spot-linked and lighter blacks are not marked, paints already set to overprint keep that setting, and only the printed copy is marked. These limits are VectorCraft's own rules. Characters set to overprint now also leave the inks below them on printed PDF plates, a type object's own fill in a PDF is drawn with its blending mode, and Edit › Edit Colors › Overprint Black counts a gradient with a stop linked to a spot swatch as a spot black, as it counts a solid one, and a freeform gradient by the color points it draws from. On a plate, an overprinting paint that puts none of that plate's ink down is drawn as nothing; on PostScript plates so is up to half a percent of another ink in a color that counts as black, and any other faint ink stays on the plate. Evidence: `print::overprint_black_keeps_the_inks_under_solid_black_on_separations`, `print::overprint_black_keeps_the_cyan_under_near_and_freeform_blacks_on_postscript_plates`, `print::overprinting_paints_keep_their_faint_ink_on_postscript_plates`, `print::overprinting_type_leaves_the_inks_below_on_separations`, `print::a_type_objects_own_black_fill_overprints_on_separations`, `tests::print::overprint_black_is_saved_with_the_setup_and_in_presets`, `overprint::tests::a_gradient_with_a_spot_linked_stop_is_black_only_with_spot`, `overprint::tests::a_freeform_gradient_is_black_when_every_point_is`. Print scores and hours are unchanged. + - The Print dialog's Output section has Overprint Black under Convert All Spot Colors to Process, off by default and available with Separations ([Print color separations](https://helpx.adobe.com/illustrator/using/printing-color-separations.html) lists it among the separation options): black art then leaves the inks under it on the other plates (`print.setup {settings: {output: {overprintBlack: true}}}`, kept with the document and in print presets). Solid 100% K or 100% gray fills, strokes and characters (to within half a percent, as Edit › Edit Colors › Overprint Black counts them), and gradients whose every stop (every color point of a freeform gradient) is, overprint; rich, RGB, Lab, spot-linked and lighter blacks are not marked, paints already set to overprint keep that setting, and only the printed copy is marked. These limits are VectorCraft's own rules. Characters set to overprint now also leave the inks below them on printed PDF plates, a type object's own fill in a PDF is drawn with its blending mode, and Edit › Edit Colors › Overprint Black counts a gradient with a stop linked to a spot swatch as a spot black, as it counts a solid one, and a freeform gradient by the color points it draws from. On a plate, an overprinting paint that puts none of that plate's ink down is drawn as nothing; on PostScript plates so is up to half a percent of another ink in a color that counts as black, and any other faint ink stays on the plate. A black linked to a swatch the document lacks separates from its own values, so on PostScript plates it counts as an unlinked black (VectorCraft's own rule). Evidence: `print::overprint_black_keeps_the_inks_under_solid_black_on_separations`, `print::overprint_black_keeps_the_cyan_under_near_and_freeform_blacks_on_postscript_plates`, `print::overprint_black_keeps_the_cyan_under_a_near_black_linked_to_a_missing_swatch_on_postscript_plates`, `print::overprinting_near_blacks_linked_to_a_missing_swatch_keep_the_cyan_on_postscript_plates`, `print::overprinting_paints_keep_their_faint_ink_on_postscript_plates`, `print::overprinting_type_leaves_the_inks_below_on_separations`, `print::a_type_objects_own_black_fill_overprints_on_separations`, `tests::print::overprint_black_is_saved_with_the_setup_and_in_presets`, `overprint::tests::a_gradient_with_a_spot_linked_stop_is_black_only_with_spot`, `overprint::tests::a_freeform_gradient_is_black_when_every_point_is`. Print scores and hours are unchanged. - The Print dialog's General section (and the print preset editor) has a link button after Scale W and H, as the Custom scale has one on [the help page](https://helpx.adobe.com/illustrator/desktop/save-and-export/export-files-to-different-formats/print-documents-in-illustrator.html), where turning it off scales the width and height apart. While it is on, typing either percentage sets the other, and turning it on sets H to W. It is on for new settings, dimmed with the fields unless Scaling is Custom or a tiling choice, toggled with a click, Space or Enter, and named with its on or off state for screen readers. W and H take 1–1000% in the fields. The link is kept with the document's print settings and in print presets (`print.setup {settings: {scale: {linked}}}`); settings saved without it read it as off, so they print as before. Its default, the tiling choices and the agent rules are VectorCraft's own. Evidence: `print::the_scale_link_is_on_for_new_settings_and_off_for_a_saved_scale_without_it`, `tests::print::the_scale_link_keeps_width_and_height_equal`, `tests::print::a_scale_saved_without_the_link_keeps_its_width_and_height`, `dialogs::tests_print::the_scale_link_keeps_scale_width_and_height_equal`, `dialogs::tests_print::a_print_preset_keeps_the_scale_link`. Print scores and hours are unchanged. - A PDF, PDF-compatible `.ai` or `.ait` opened from its pages or its editing copy opens with the File Info that its XMP packet and its document information dictionary give: the title (`dc:title`, its `x-default` item first, else Info `Title`), the author, description, keywords, copyright status, notice and URL, and the created and modified dates, the XMP packet's value where both give one (`crates/pdf/src/tests/file_info.rs`, `crates/engine/src/tests/fileinfo.rs`). An SVG opens with the title of its root `<title>`. The title is File Info's alone (`DocMetadata::title`): the document's name stays the file's name with its extension, a file that gives no title leaves File Info with that name, and exports (PDF, SVG, PNG, EPS, `.ai`) and native saves carry it; changing the title in File Info sets the document's name as before (#3626). - PDF export and PDF-compatible `.ai` and `.ait` saves write the document's File Info created date as the file's creation date, or the time of writing when the document has none, and the time of writing as its modification date; the page information mark still prints the time of writing (`crates/engine/src/tests/fileinfo.rs`, `crates/pdf/src/tests.rs`, `crates/pdf/src/tests/marks.rs`). From a09bcb3ecd6a2d38e5ab7167bb1f3d9861842dfb Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 17 Nov 2026 09:48:16 -0800 Subject: [PATCH 103/176] Free Transform: a shear drag shows its angle next to the pointer With Smart Guides' Transform Tools on, a Cmd/Ctrl side-handle shear with the Free Transform tool now shows its angle next to the pointer, with the same sign and one decimal place as the Shear tool's label. Before, a shear showed no value, and a scale drag turned into a shear kept showing the scale's size. Transform Tools off still hides the label. Docs: docs/mcp.md (transformToolsGuides), docs/target-app-parity.md. --- crates/tools/src/xform/free.rs | 69 +++++++++++++++++++++++++++++++++- docs/mcp.md | 4 +- docs/target-app-parity.md | 1 + 3 files changed, 71 insertions(+), 3 deletions(-) diff --git a/crates/tools/src/xform/free.rs b/crates/tools/src/xform/free.rs index 1583584940..e22e17d2e2 100644 --- a/crates/tools/src/xform/free.rs +++ b/crates/tools/src/xform/free.rs @@ -237,7 +237,15 @@ impl FreeTransformTool { self.measure = cx.transform_tools_guides.then(|| (p, cx.size_label(nr.width(), nr.height()))); bx.conjugate(a) } - Op::Shear(h) => bx.conjugate(shear_for_side(bx.rect, h, local, m.alt)), + Op::Shear(h) => { + let a = shear_for_side(bx.rect, h, local, m.alt); + // The shear's slope, read from the matrix the preview applies, labeled with the + // angle the Shear tool shows for the same slant. + let [_, vertical, horizontal, ..] = a.as_coeffs(); + let k = if matches!(h, Handle::Top | Handle::Bottom) { horizontal } else { vertical }; + self.measure = cx.transform_tools_guides.then(|| (p, format!("{:.1}°", 0.0 - k.atan().to_degrees()))); + bx.conjugate(a) + } Op::Rotate => { let (a, deg) = rotate_for_drag(bx.center(), d.start, p, shift); self.measure = cx.transform_tools_guides.then(|| (p, format!("{:.1}°", -deg))); @@ -723,4 +731,63 @@ mod tests { t.pointer(&cx(false), &ev(PointerKind::Drag, 220.0, 230.0)); assert!(t.overlays(&cx(false)).iter().all(|o| !matches!(o, Overlay::Measure { .. }))); } + + /// The label a drag shows next to the pointer, and where. + fn shown_measure(t: &FreeTransformTool, cx: &ToolContext) -> Option<(Point, String)> { + t.overlays(cx).into_iter().find_map(|o| if let Overlay::Measure { p, text } = o { Some((p, text)) } else { None }) + } + + /// With Smart Guides' Transform Tools on, a Cmd side-handle shear shows its angle next to the + /// pointer, with the Shear tool's sign: the top side moved right and the right side moved down + /// by 20 pt on the 100 pt square slant 11.3° either way. Alt shears about the center. + #[test] + fn shear_drag_shows_its_angle_with_transform_tools_guides() { + let (d, id) = doc_with_rect(); + let mut s = Selection::default(); + s.add(id); + let p = paint(); + let cx = |on: bool| ToolContext { transform_tools_guides: on, ..cx(&d, &s, &p) }; + let cmd = Mods { cmd: true, ..Default::default() }; + let shear = |c: &ToolContext, from: (f64, f64), to: (f64, f64), m: Mods| { + let mut t = FreeTransformTool::default(); + t.pointer(c, &ev(PointerKind::Down, from.0, from.1).with_mods(m)); + let a = t.pointer(c, &ev(PointerKind::Drag, to.0, to.1).with_mods(m)); + assert_eq!(a[0], Action::Begin("Shear".into())); + let shown = shown_measure(&t, c); + assert_eq!(t.pointer(c, &ev(PointerKind::Up, to.0, to.1).with_mods(m)), vec![Action::Commit]); + assert_eq!(shown_measure(&t, c), None, "the label goes with the drag"); + shown + }; + let on = cx(true); + let off = Vec2::new(on.tol(12.0), on.tol(12.0)); + assert_eq!(shear(&on, (150.0, 100.0), (170.0, 100.0), cmd), Some((Point::new(170.0, 100.0) + off, "11.3°".into()))); + assert_eq!(shear(&on, (200.0, 150.0), (200.0, 170.0), cmd), Some((Point::new(200.0, 170.0) + off, "-11.3°".into()))); + // About the center the lever is half as long: atan(20 / 50). + let alt = Mods { alt: true, ..cmd }; + assert_eq!(shear(&on, (150.0, 100.0), (170.0, 100.0), alt).map(|m| m.1), Some("21.8°".into())); + // A drag straight away from the side, at right angles to it, shears nothing. + assert_eq!(shear(&on, (150.0, 100.0), (150.0, 90.0), cmd).map(|m| m.1), Some("0.0°".into())); + assert_eq!(shear(&cx(false), (150.0, 100.0), (170.0, 100.0), cmd), None); + } + + /// A handle drag that turns into a shear, and back into a scale, labels only what it does now. + #[test] + fn a_handle_drag_that_changes_operation_relabels_it() { + let (d, id) = doc_with_rect(); + let mut s = Selection::default(); + s.add(id); + let p = paint(); + let cx = ToolContext { transform_tools_guides: true, ..cx(&d, &s, &p) }; + let cmd = Mods { cmd: true, ..Default::default() }; + let mut t = FreeTransformTool::default(); + t.pointer(&cx, &ev(PointerKind::Down, 150.0, 100.0)); + t.pointer(&cx, &ev(PointerKind::Drag, 150.0, 90.0)); + let size = cx.size_label(100.0, 110.0); + assert_eq!(shown_measure(&t, &cx).map(|m| m.1), Some(size.clone())); + let a = t.pointer(&cx, &ev(PointerKind::Drag, 170.0, 100.0).with_mods(cmd)); + assert_eq!(a[..2], [Action::Cancel, Action::Begin("Shear".into())]); + assert_eq!(shown_measure(&t, &cx).map(|m| m.1), Some("11.3°".into())); + t.pointer(&cx, &ev(PointerKind::Drag, 150.0, 90.0)); + assert_eq!(shown_measure(&t, &cx).map(|m| m.1), Some(size)); + } } diff --git a/docs/mcp.md b/docs/mcp.md index 092faabc4c..428e5e21f6 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7031,8 +7031,8 @@ Guides change where a snapped point lands: - `anchorPathLabels` (on by default): off, no "anchor", "center", "path" or "align" label. - `measurementLabels` (on by default): off, no size or offset readout while drawing, moving (Free Transform's move too), dragging a ruler guide, drawing and resizing an artboard, or moving and resizing a slice. -- `transformToolsGuides` (on by default): off, no readout while scaling or rotating with the Selection tool, the - Free Transform tool or the Rotate, Scale, Shear and Reflect tools. +- `transformToolsGuides` (on by default): off, no readout while scaling, rotating or shearing with the Selection + tool, the Free Transform tool or the Rotate, Scale, Shear and Reflect tools. - `objectHighlighting` (on by default; desktop app): off, the Selection tools no longer outline the object under the pointer. The outline also needs View › Smart Guides on. - `snappingTolerance` (0–40 px, 4 by default): how near an anchor, edge, centre or artboard edge pulls a drawn point, diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index e9fc9a6820..c7035950c0 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1050,6 +1050,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - After a rotation the Scale and Reflect tools, the Scale and Reflect dialogs, `object.scale`, `object.reflect` with a named axis and the Transform and Properties panels' flips act along the selection's turned bounding box until Reset Bounding Box: the horizontal and vertical scale stretch along its own width and height, and the vertical and horizontal reflection axes are its own. The Reflect tool's default axis and its Shift steps start from the box's axes, and an axis drawn with the tool is the line drawn on the page. `basis: "page"` keeps the page's axes (VectorCraft's own rules; `bboxrotate::scale_and_reflect_follow_the_turned_box`, tools `xform::transform::tests::scale_and_reflect_drags_follow_a_turned_bounding_box`). - Perspective Distort and Free Distort (`object.distort`) turn each warped object's bounding box as the warp turns the object at its own center, the objects inside groups, compound paths and clip groups and the art of linked opacity masks included, so the next Selection or Free Transform drag uses the tilted box; Object › Transform › Reset Bounding Box squares it again, and corners left where they are add no undo step (VectorCraft's own rule; `bboxrotate::distort_turns_an_upright_box_with_the_warp_at_its_center`, `distort_turns_each_member_and_linked_mask_by_its_own_warp`, `mirrored_and_collapsing_distorts_keep_valid_angles`, `distort_angles_undo_redo_and_reopen_together`, `xform::unchanged_distort_records_no_history`). - The Free Transform widget's Constrain works in Free Distort as well as in Free Transform ([the help page](https://helpx.adobe.com/illustrator/using/tool-techniques/free-transform-tool.html)). With Constrain on, or Shift held, a corner dragged in Free Distort moves only along the line through the opposite corner, in the box's own proportions, and the other three corners stay in place; on a turned box the line runs through the box's own corners. The line is VectorCraft's own rule. Cmd/Ctrl+Alt+Shift on a corner still drags in Perspective Distort, where Constrain stays unavailable (tools `xform::free::tests::free_distort_corner_keeps_to_its_diagonal_with_shift_or_constrain`, `shift_pressed_during_a_free_distort_drag_constrains_it`, `a_turned_box_is_constrained_along_its_own_diagonal`, `along_diagonal_of_a_degenerate_box`; engine `xform::free_transform_constrained_distort_keeps_the_corner_on_its_diagonal`; ui-egui `free_transform::tests::the_widget_sets_the_mode_and_a_corner_drag_then_distorts`). + - With Smart Guides › Transform Tools on, a Free Transform shear (Cmd/Ctrl on a side handle) shows its angle next to the pointer, as the Shear tool does, and a handle drag that turns from a scale into a shear and back shows only the current operation's value ([the help page](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/smart-guides-options.html)). The angle's sign and its one decimal place are VectorCraft's own rule, the same as the Shear tool's label (tools `xform::free::tests::shear_drag_shows_its_angle_with_transform_tools_guides`, `a_handle_drag_that_changes_operation_relabels_it`). - Native macOS menu bar, vector tool cursors, a command palette (Help › Search Commands…), middle-button panning with any tool. Native menus explicitly end tracking on command selection, outside window presses and Escape; menu updates wait until tracking ends, and a dismissing press never starts a canvas gesture (M14.8). - Help › Search Commands… is the first item of the Help menu in the window, with its shortcut and a separator after it; in the native macOS menu bar it is the first item below the system's search field. This is VectorCraft's own order and does not raise a score (`menus::tests::help_starts_with_search_commands`, `tests::nativemenu::the_mac_help_menu_starts_with_search_commands`). - A Recent Commands button beside the Help › Search Commands field lists the last five commands, tools, panels and effects picked from the palette, most recent first, with a command picked again moved to the top. Choosing a row closes the palette and runs it as a pick of the same result does; with no picks yet the list shows a dimmed No recent commands row, and a command that is not available now, such as a filter of a plug-in that is not loaded, is left out until it comes back. The ids are saved with the UI state. While the list is open, Up and Down move through its rows, wrapping at the ends, and Escape closes the list before the palette. This is VectorCraft's own addition and does not raise a score (#6376; `palette` tests `recent_commands_*`, `a_recent_command_runs_what_its_pick_runs`, `the_keys_wrap_within_recent_commands`, `escape_closes_recent_commands_before_the_palette`). From c7c14be61b2485678f363ebf69e1936edd94130e Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 17 Nov 2026 09:56:43 -0800 Subject: [PATCH 104/176] Save PDF: the PDF/X note covers a loaded Don't Include Profiles Params or a preset can open the dialog with PDF/X-3 or PDF/X-4 and Profile inclusion set to none, without the standard being chosen. The dialog keeps that value, and with a CMYK output intent every CMYK color is then written as DeviceCMYK unless it is converted to a CMYK destination of another profile. The Output section now says so under the PDF/X note, in every catalog. --- crates/ui-egui/src/dialogs/save_pdf.rs | 9 +++++++++ crates/ui-egui/src/dialogs/save_pdf/tests.rs | 18 ++++++++++++++++++ crates/ui-egui/src/i18n/bg.tsv | 1 + crates/ui-egui/src/i18n/bs.tsv | 1 + crates/ui-egui/src/i18n/ca.tsv | 1 + crates/ui-egui/src/i18n/cs.tsv | 1 + crates/ui-egui/src/i18n/da.tsv | 1 + crates/ui-egui/src/i18n/de.tsv | 1 + crates/ui-egui/src/i18n/el.tsv | 1 + crates/ui-egui/src/i18n/es.tsv | 1 + crates/ui-egui/src/i18n/fi.tsv | 1 + crates/ui-egui/src/i18n/fr.tsv | 1 + crates/ui-egui/src/i18n/gu.tsv | 1 + crates/ui-egui/src/i18n/hi.tsv | 1 + crates/ui-egui/src/i18n/hu.tsv | 1 + crates/ui-egui/src/i18n/id.tsv | 1 + crates/ui-egui/src/i18n/it.tsv | 1 + crates/ui-egui/src/i18n/ja.tsv | 1 + crates/ui-egui/src/i18n/ka.tsv | 1 + crates/ui-egui/src/i18n/ko.tsv | 1 + crates/ui-egui/src/i18n/nl.tsv | 1 + crates/ui-egui/src/i18n/pl.tsv | 1 + crates/ui-egui/src/i18n/pt-br.tsv | 1 + crates/ui-egui/src/i18n/ru.tsv | 1 + crates/ui-egui/src/i18n/sv.tsv | 1 + crates/ui-egui/src/i18n/tr.tsv | 1 + crates/ui-egui/src/i18n/uk.tsv | 1 + crates/ui-egui/src/i18n/vi.tsv | 1 + crates/ui-egui/src/i18n/zh-hans.tsv | 1 + crates/ui-egui/src/i18n/zh-hant.tsv | 1 + 30 files changed, 55 insertions(+) diff --git a/crates/ui-egui/src/dialogs/save_pdf.rs b/crates/ui-egui/src/dialogs/save_pdf.rs index 048861d799..8c779fd229 100644 --- a/crates/ui-egui/src/dialogs/save_pdf.rs +++ b/crates/ui-egui/src/dialogs/save_pdf.rs @@ -722,6 +722,15 @@ fn output(ui: &mut egui::Ui, d: &mut Dialog) { "Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK." ), ); + // A preset or the dialog's params can bring `none` with the standard; the picker can't change it. + if choice::<ProfileInclusion>(d, "output.profiles") == Some(ProfileInclusion::None) { + note( + ui, + tl!( + "With Don't include profiles and a CMYK output intent, every CMYK color is written as DeviceCMYK unless it is converted to a CMYK destination of another profile." + ), + ); + } } else if standard != Standard::None { note(ui, tl!("Files of this standard tag their colours with ICC profiles.")); } diff --git a/crates/ui-egui/src/dialogs/save_pdf/tests.rs b/crates/ui-egui/src/dialogs/save_pdf/tests.rs index 8967e13977..87a00a897a 100644 --- a/crates/ui-egui/src/dialogs/save_pdf/tests.rs +++ b/crates/ui-egui/src/dialogs/save_pdf/tests.rs @@ -552,6 +552,24 @@ fn choosing_pdfx3_or_pdfx4_unsets_profile_inclusion() { } } +/// Opened with PDF/X-3 or PDF/X-4 and `none` (params or a preset, without choosing the standard), +/// the dialog keeps `none` and its Output note says every CMYK color is written as DeviceCMYK. +#[test] +fn a_loaded_pdfx_standard_with_no_profiles_says_cmyk_is_device_cmyk() { + const NOTE: &str = "every CMYK color is written as DeviceCMYK"; + let (mut app, _, _) = app(); + for (standard, profiles, shown) in + [(Standard::PdfX4, "none", true), (Standard::PdfX3, "none", true), (Standard::PdfX4, "all", false), (Standard::PdfX1a, "none", false)] + { + let params = json!({"path": "/tmp/x.pdf", "standard": standard.id(), "output": {"profiles": profiles}}); + app.run("ui.savePdfDialog", params).unwrap(); + set_field(&mut app, "__section", json!("Output")); + assert_eq!(get(app.ui.dialog.as_ref().unwrap(), "output.profiles"), &json!(profiles)); + let text = crate::tests_labels::painted_text(&mut app, |app, ui| super::super::show(app, ui.ctx())); + assert_eq!(text.contains(NOTE), shown, "{} {profiles}: {text}", standard.id()); + } +} + /// "Write pages longer than 200 in at full size in points" is enabled only without a standard, at /// PDF 1.5 and later: PDF/X files and PDF 1.3 and 1.4 files write long pages in points anyway, and /// PDF/A files keep the `UserUnit`. diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index 86ea88e6c4..49b2b602b0 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -1209,6 +1209,7 @@ font-technology Variable Променливи Files of a PDF standard can't be password-protected. Файлове от PDF стандарт не могат да бъдат защитени с парола. Files of this standard tag their colours with ICC profiles. Файловете от този стандарт етикетират цветовете си с ICC профили. Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. Файловете от този стандарт етикетират цветовете си с ICC профили, с изключение на CMYK цветовете в профила на предназначението на изхода, които се записват като DeviceCMYK. + With Don't include profiles and a CMYK output intent, every CMYK color is written as DeviceCMYK unless it is converted to a CMYK destination of another profile. С „Без включване на профили“ и CMYK предназначение на изхода всеки CMYK цвят се записва като DeviceCMYK, освен ако не се преобразува към CMYK местоназначение с друг профил. Fill Запълване Fill & Stroke Запълване и щрих Fill (X), double-click for the Color Picker Запълване (X), щракнете двукратно за избор на цвят diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index d93d523c4a..687d76fbdd 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -3088,6 +3088,7 @@ antiAlias Sharp Oštro Files of a PDF standard can't be password-protected. Datoteke PDF standarda ne mogu se zaštititi lozinkom. Files of this standard tag their colours with ICC profiles. Datoteke ovog standarda označavaju svoje boje ICC profilima. Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. Datoteke ovog standarda označavaju svoje boje ICC profilima, osim CMYK boja u profilu izlazne namjene, koje se zapisuju kao DeviceCMYK. + With Don't include profiles and a CMYK output intent, every CMYK color is written as DeviceCMYK unless it is converted to a CMYK destination of another profile. Uz „Ne uključuj profile“ i CMYK izlaznu namjenu, svaka CMYK boja zapisuje se kao DeviceCMYK, osim ako se ne pretvori u CMYK odredište s drugim profilom. Flattener preset: Predložak spljoštavanja: General › Thumbnails Općenito › Sličice Grayscale images Slike u nijansama sive diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index 41b03b7fe0..80ea559aeb 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -1707,6 +1707,7 @@ digits Malayalam Malaiàlam Files of a PDF standard can't be password-protected. Els fitxers d’un estàndard PDF no es poden protegir amb contrasenya. Files of this standard tag their colours with ICC profiles. Els fitxers d’aquest estàndard etiqueten els colors amb perfils ICC. Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. Els fitxers d’aquest estàndard etiqueten els colors amb perfils ICC, excepte els colors CMYK del perfil d’intenció de sortida, que s’escriuen com a DeviceCMYK. + With Don't include profiles and a CMYK output intent, every CMYK color is written as DeviceCMYK unless it is converted to a CMYK destination of another profile. Amb «No incloguis els perfils» i una intenció de sortida CMYK, cada color CMYK s’escriu com a DeviceCMYK, tret que es converteixi a una destinació CMYK d’un altre perfil. Fill Farciment Fill & Stroke Farciment i traç Fill (X), double-click for the Color Picker Farciment (X), fes doble clic per al selector de color diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 77f7ea934a..09931fd898 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -3172,6 +3172,7 @@ antiAlias Sharp Ostré Files of a PDF standard can't be password-protected. Soubory podle standardu PDF nelze chránit heslem. Files of this standard tag their colours with ICC profiles. Soubory tohoto standardu označují své barvy profily ICC. Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. Soubory tohoto standardu označují své barvy profily ICC, kromě barev CMYK v profilu výstupního záměru, které se zapisují jako DeviceCMYK. + With Don't include profiles and a CMYK output intent, every CMYK color is written as DeviceCMYK unless it is converted to a CMYK destination of another profile. S volbou „Nezahrnovat profily“ a výstupním záměrem CMYK se každá barva CMYK zapíše jako DeviceCMYK, pokud se nepřevede do cíle CMYK s jiným profilem. Flattener preset: Přednastavení sloučení: General › Thumbnails Obecné › Miniatury Grayscale images Obrazy ve stupních šedi diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 8f71585fd3..4845cb65d3 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -5645,6 +5645,7 @@ antiAlias Sharp Skarp Files of a PDF standard can't be password-protected. Filer med en PDF-standard kan ikke beskyttes med adgangskode. Files of this standard tag their colours with ICC profiles. Filer med denne standard mærker deres farver med ICC-profiler. Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. Filer med denne standard mærker deres farver med ICC-profiler, undtagen CMYK-farver i outputintentens profil, som skrives som DeviceCMYK. + With Don't include profiles and a CMYK output intent, every CMYK color is written as DeviceCMYK unless it is converted to a CMYK destination of another profile. Med »Medtag ikke profiler« og en CMYK-outputintent skrives alle CMYK-farver som DeviceCMYK, medmindre de konverteres til en CMYK-destination med en anden profil. Flattener preset: Forudindstilling til fladgøring: General › Thumbnails Generelt › Miniaturer Grayscale images Gråtonebilleder diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 3c198e8dce..c50e6e55b6 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -1232,6 +1232,7 @@ font-technology Variable Variabel Files of a PDF standard can't be password-protected. Dateien eines PDF-Standards können nicht mit einem Kennwort geschützt werden. Files of this standard tag their colours with ICC profiles. Dateien dieses Standards kennzeichnen ihre Farben mit ICC-Profilen. Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. Dateien dieses Standards kennzeichnen ihre Farben mit ICC-Profilen, außer CMYK-Farben im Profil der Ausgabemethode, die als DeviceCMYK geschrieben werden. + With Don't include profiles and a CMYK output intent, every CMYK color is written as DeviceCMYK unless it is converted to a CMYK destination of another profile. Mit „Profile nicht einschließen“ und einer CMYK-Ausgabemethode wird jede CMYK-Farbe als DeviceCMYK geschrieben, sofern sie nicht in ein CMYK-Ziel mit einem anderen Profil konvertiert wird. Fill Fläche Fill & Stroke Fläche und Kontur Fill (X), double-click for the Color Picker Fläche (X), Doppelklick öffnet den Farbwähler diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 4741b40dd5..cee0990f7f 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -1194,6 +1194,7 @@ font-technology Variable Μεταβλητές Files of a PDF standard can't be password-protected. Τα αρχεία αυτού του προτύπου PDF δεν μπορούν να προστατεύονται με κωδικό. Files of this standard tag their colours with ICC profiles. Τα αρχεία αυτού του προτύπου χαρακτηρίζουν τα χρώματά τους με προφίλ ICC. Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. Τα αρχεία αυτού του προτύπου χαρακτηρίζουν τα χρώματά τους με προφίλ ICC, εκτός από τα χρώματα CMYK στο προφίλ προορισμού εξόδου, τα οποία γράφονται ως DeviceCMYK. + With Don't include profiles and a CMYK output intent, every CMYK color is written as DeviceCMYK unless it is converted to a CMYK destination of another profile. Με «Να μη συμπεριληφθούν προφίλ» και προορισμό εξόδου CMYK, κάθε χρώμα CMYK γράφεται ως DeviceCMYK, εκτός αν μετατραπεί σε προορισμό CMYK άλλου προφίλ. Fill Γέμισμα Fill & Stroke Γέμισμα και περίγραμμα Fill (X), double-click for the Color Picker Γέμισμα (X), διπλό κλικ για τον επιλογέα χρώματος diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 6530cb8c73..e82b6ef610 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -1257,6 +1257,7 @@ font-technology Variable Variables Files of a PDF standard can't be password-protected. Los archivos de un estándar PDF no se pueden proteger con contraseña. Files of this standard tag their colours with ICC profiles. Los archivos de este estándar etiquetan sus colores con perfiles ICC. Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. Los archivos de este estándar etiquetan sus colores con perfiles ICC, excepto los colores CMYK en el perfil de propósito de salida, que se escriben como DeviceCMYK. + With Don't include profiles and a CMYK output intent, every CMYK color is written as DeviceCMYK unless it is converted to a CMYK destination of another profile. Con «No incluir perfiles» y un propósito de salida CMYK, cada color CMYK se escribe como DeviceCMYK, salvo que se convierta a un destino CMYK de otro perfil. Fill Relleno Fill & Stroke Relleno y trazo Fill (X), double-click for the Color Picker Relleno (X), doble clic para el selector de color diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index dadad98564..1b6f9fe69a 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -3116,6 +3116,7 @@ antiAlias Sharp Terävä Files of a PDF standard can't be password-protected. PDF-standardin mukaisia tiedostoja ei voi suojata salasanalla. Files of this standard tag their colours with ICC profiles. Tämän standardin tiedostot merkitsevät värinsä ICC-profiileilla. Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. Tämän standardin tiedostot merkitsevät värinsä ICC-profiileilla, paitsi tulostustavoitteen profiilin CMYK-värit, jotka kirjoitetaan DeviceCMYK-muodossa. + With Don't include profiles and a CMYK output intent, every CMYK color is written as DeviceCMYK unless it is converted to a CMYK destination of another profile. Kun valintana on ”Älä sisällytä profiileja” ja tulostustavoite on CMYK, jokainen CMYK-väri kirjoitetaan DeviceCMYK-muodossa, ellei sitä muunneta toisen profiilin CMYK-kohteeseen. Flattener preset: Litistyksen esiasetus: General › Thumbnails Yleiset › Pikkukuvat Grayscale images Harmaasävykuvat diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 4559058a49..8a72ca8677 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -1248,6 +1248,7 @@ font-technology Variable Variables Files of a PDF standard can't be password-protected. Les fichiers conformes à une norme PDF ne peuvent pas être protégés par mot de passe. Files of this standard tag their colours with ICC profiles. Les fichiers conformes à cette norme balisent leurs couleurs avec des profils ICC. Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. Les fichiers conformes à cette norme balisent leurs couleurs avec des profils ICC, sauf les couleurs CMJN du profil du mode de sortie, qui sont écrites en DeviceCMYK. + With Don't include profiles and a CMYK output intent, every CMYK color is written as DeviceCMYK unless it is converted to a CMYK destination of another profile. Avec l’option Ne pas inclure les profils et un mode de sortie CMJN, chaque couleur CMJN est écrite en DeviceCMYK, sauf si elle est convertie vers une destination CMJN d’un autre profil. Fill Fond Fill & Stroke Fond et contour Fill (X), double-click for the Color Picker Fond (X), double-cliquez pour ouvrir le Sélecteur de couleurs diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index e0b3e97b9f..94a91700de 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -1379,6 +1379,7 @@ Files of a PDF standard can't be password-protected. PDF સ્ટાન્ડર્ડની ફાઇલો પાસવર્ડ-સુરક્ષિત કરી શકાતી નથી. Files of this standard tag their colours with ICC profiles. આ સ્ટાન્ડર્ડની ફાઇલો તેમના રંગોને ICC પ્રોફાઇલ્સ સાથે ટૅગ કરે છે. Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. આ સ્ટાન્ડર્ડની ફાઇલો તેમના રંગોને ICC પ્રોફાઇલ્સ સાથે ટૅગ કરે છે, આઉટપુટ ઇન્ટેન્ટ પ્રોફાઇલમાંના CMYK રંગો સિવાય, જે DeviceCMYK તરીકે લખાય છે. + With Don't include profiles and a CMYK output intent, every CMYK color is written as DeviceCMYK unless it is converted to a CMYK destination of another profile. “પ્રોફાઇલ્સ શામેલ કરશો નહીં” અને CMYK આઉટપુટ ઇન્ટેન્ટ સાથે, દરેક CMYK રંગ DeviceCMYK તરીકે લખાય છે, સિવાય કે તેને બીજી પ્રોફાઇલના CMYK ગંતવ્યમાં રૂપાંતરિત કરવામાં આવે. Fill ભરો Fill & Stroke ભરો અને સ્ટ્રોક Fill (X), double-click for the Color Picker ભરો (X), કલર પીકર માટે ડબલ-ક્લિક કરો diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index d8a6d9a124..719fb0ed4c 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -1899,6 +1899,7 @@ antiAlias Sharp शार्प Files of a PDF standard can't be password-protected. एक PDF मानक की फ़ाइलें पासवर्ड की रक्षा नहीं की जा सकती है। Files of this standard tag their colours with ICC profiles. इस मानक की फ़ाइलें ICC प्रोफ़ाइल के साथ उनके रंगों को टैग करती हैं। Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. इस मानक की फ़ाइलें ICC प्रोफ़ाइल के साथ उनके रंगों को टैग करती हैं, आउटपुट इंटेंट प्रोफ़ाइल के CMYK रंगों को छोड़कर, जो DeviceCMYK के रूप में लिखे जाते हैं। + With Don't include profiles and a CMYK output intent, every CMYK color is written as DeviceCMYK unless it is converted to a CMYK destination of another profile. “प्रोफ़ाइल शामिल नहीं है” और CMYK आउटपुट इंटेंट के साथ, हर CMYK रंग DeviceCMYK के रूप में लिखा जाता है, जब तक कि उसे किसी अन्य प्रोफ़ाइल के CMYK गंतव्य में रूपांतरित न किया जाए। Fill फ़िल Fill (X), double-click for the Color Picker फ़िल (X), कलर पिकर के लिए डबल-क्लिक करें Fill & Stroke भरें और स्ट्रोक करें diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 1e9e020a8c..415dfcdc16 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -1566,6 +1566,7 @@ digits Malayalam Malajálam Files of a PDF standard can't be password-protected. A PDF-szabványnak megfelelő fájlok nem védhetők jelszóval. Files of this standard tag their colours with ICC profiles. Ennek a szabványnak a fájljai ICC-profillal jelölik a színeiket. Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. Ennek a szabványnak a fájljai ICC-profillal jelölik a színeiket, kivéve a kimeneti cél profiljában lévő CMYK-színeket, amelyek DeviceCMYK-ként íródnak. + With Don't include profiles and a CMYK output intent, every CMYK color is written as DeviceCMYK unless it is converted to a CMYK destination of another profile. „Profilok nélkül” beállítással és CMYK kimeneti céllal minden CMYK-szín DeviceCMYK-ként íródik, kivéve, ha egy másik profil CMYK-céljába konvertálódik. Fill Kitöltés Fill & Stroke Kitöltés és körvonal Fill (X), double-click for the Color Picker Kitöltés (X), dupla kattintás: Színválasztó diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 4bf67e692b..4fbd700a34 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -2897,6 +2897,7 @@ antiAlias Sharp Tajam Files of a PDF standard can't be password-protected. File standar PDF tidak dapat dilindungi kata sandi. Files of this standard tag their colours with ICC profiles. File standar ini menandai warnanya dengan profil ICC. Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. File standar ini menandai warnanya dengan profil ICC, kecuali warna CMYK dalam profil output intent, yang ditulis sebagai DeviceCMYK. + With Don't include profiles and a CMYK output intent, every CMYK color is written as DeviceCMYK unless it is converted to a CMYK destination of another profile. Dengan “Jangan sertakan profil” dan output intent CMYK, setiap warna CMYK ditulis sebagai DeviceCMYK, kecuali dikonversi ke tujuan CMYK dengan profil lain. Flattener preset: Preset flattener: General › Thumbnails Umum › Miniatur Grayscale images Gambar skala abu-abu diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 989eaa9b87..4d47b142e1 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -1266,6 +1266,7 @@ font-technology Variable Variabili Files of a PDF standard can't be password-protected. I file conformi a uno standard PDF non possono essere protetti da password. Files of this standard tag their colours with ICC profiles. I file conformi a questo standard contrassegnano i colori con profili ICC. Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. I file conformi a questo standard contrassegnano i colori con profili ICC, tranne i colori CMYK nel profilo dell'intento di output, che vengono scritti come DeviceCMYK. + With Don't include profiles and a CMYK output intent, every CMYK color is written as DeviceCMYK unless it is converted to a CMYK destination of another profile. Con «Non includere i profili» e un intento di output CMYK, ogni colore CMYK viene scritto come DeviceCMYK, a meno che non venga convertito in una destinazione CMYK di un altro profilo. Fill Riempimento Fill & Stroke Riempimento e traccia Fill (X), double-click for the Color Picker Riempimento (X), fai doppio clic per il selettore colore diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 04cfbc90b2..7a91891409 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -1830,6 +1830,7 @@ antiAlias Sharp シャープ Files of a PDF standard can't be password-protected. PDF 規格のファイルにはパスワードを設定できません。 Files of this standard tag their colours with ICC profiles. この規格のファイルでは、カラーに ICC プロファイルが付けられます。 Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. この規格のファイルでは、カラーに ICC プロファイルが付けられます。ただし、出力インテントのプロファイルの CMYK カラーは DeviceCMYK として書き出されます。 + With Don't include profiles and a CMYK output intent, every CMYK color is written as DeviceCMYK unless it is converted to a CMYK destination of another profile. 「プロファイルを含めない」と CMYK の出力インテントでは、別のプロファイルの CMYK 変換先に変換されない限り、すべての CMYK カラーが DeviceCMYK として書き出されます。 Fill 塗り Fill New Type Objects With Placeholder Text 新規テキストオブジェクトをダミーテキストで埋める Start Lists From Typed Markers 入力した記号からリストを開始 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index b00a69a5df..c7a5bb772c 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -5041,6 +5041,7 @@ antiAlias Sharp მკვეთრი Files of a PDF standard can't be password-protected. PDF სტანდარტის ფაილების პაროლით დაცვა შეუძლებელია. Files of this standard tag their colours with ICC profiles. ამ სტანდარტის ფაილები ფერებს ICC პროფილებით აღნიშნავს. Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. ამ სტანდარტის ფაილები ფერებს ICC პროფილებით აღნიშნავს, გარდა გამოტანის მიზნის პროფილის CMYK ფერებისა, რომლებიც DeviceCMYK-ად იწერება. + With Don't include profiles and a CMYK output intent, every CMYK color is written as DeviceCMYK unless it is converted to a CMYK destination of another profile. „პროფილების გარეშე“ და CMYK გამოტანის მიზნით ყველა CMYK ფერი DeviceCMYK-ად იწერება, თუ ის სხვა პროფილის CMYK დანიშნულებაში არ გარდაიქმნება. Flattener preset: გაბრტყელების პრესეტი: General › Thumbnails ზოგადი › ესკიზები Grayscale images ნაცრისფერი გამოსახულებები diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 1db7ed4951..d670ce52d7 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -1820,6 +1820,7 @@ antiAlias Sharp 날카롭게 Files of a PDF standard can't be password-protected. PDF 표준 파일은 암호로 보호할 수 없습니다. Files of this standard tag their colours with ICC profiles. 이 표준의 파일은 ICC 프로파일로 색상을 태그합니다. Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. 이 표준의 파일은 ICC 프로파일로 색상을 태그합니다. 단, 출력 의도 프로파일의 CMYK 색상은 DeviceCMYK로 기록됩니다. + With Don't include profiles and a CMYK output intent, every CMYK color is written as DeviceCMYK unless it is converted to a CMYK destination of another profile. '프로파일 포함 안 함'과 CMYK 출력 의도를 사용하면, 다른 프로파일의 CMYK 대상으로 변환되지 않는 한 모든 CMYK 색상이 DeviceCMYK로 기록됩니다. Fill 칠 Fill New Type Objects With Placeholder Text 새 문자 개체를 대체 텍스트로 채우기 Start Lists From Typed Markers 입력한 기호로 목록 시작 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 800e46c54a..e12067efa4 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -3519,6 +3519,7 @@ antiAlias Sharp Scherp Files of a PDF standard can't be password-protected. Bestanden volgens een PDF-standaard kunnen niet met een wachtwoord worden beveiligd. Files of this standard tag their colours with ICC profiles. Bestanden volgens deze standaard voorzien hun kleuren van ICC-profielen. Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. Bestanden volgens deze standaard voorzien hun kleuren van ICC-profielen, behalve CMYK-kleuren in het profiel voor uitvoerintentie, die als DeviceCMYK worden geschreven. + With Don't include profiles and a CMYK output intent, every CMYK color is written as DeviceCMYK unless it is converted to a CMYK destination of another profile. Met ‘Geen profielen opnemen’ en een CMYK-uitvoerintentie wordt elke CMYK-kleur als DeviceCMYK geschreven, tenzij deze wordt omgezet naar een CMYK-bestemming met een ander profiel. Flattener preset: Voorinstelling voor afvlakking: General › Thumbnails Algemeen › Miniaturen Grayscale images Grijswaardenafbeeldingen diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 8a03719e5c..f5396f6e5c 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -3062,6 +3062,7 @@ antiAlias Sharp Ostre Files of a PDF standard can't be password-protected. Plików standardu PDF nie można chronić hasłem. Files of this standard tag their colours with ICC profiles. Pliki tego standardu oznaczają kolory profilami ICC. Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. Pliki tego standardu oznaczają kolory profilami ICC, z wyjątkiem kolorów CMYK w profilu docelowych warunków wyjściowych, które są zapisywane jako DeviceCMYK. + With Don't include profiles and a CMYK output intent, every CMYK color is written as DeviceCMYK unless it is converted to a CMYK destination of another profile. Przy opcji „Nie dołączaj profili” i docelowych warunkach wyjściowych CMYK każdy kolor CMYK jest zapisywany jako DeviceCMYK, chyba że zostanie przekonwertowany do miejsca docelowego CMYK z innym profilem. Flattener preset: Ustawienie spłaszczania: General › Thumbnails Ogólne › Miniatury Grayscale images Obrazy w skali szarości diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index cc88a2bae4..147acf4e58 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -1142,6 +1142,7 @@ antiAlias Sharp Nítido Files of a PDF standard can't be password-protected. Arquivos de um padrão PDF não podem ser protegidos por senha. Files of this standard tag their colours with ICC profiles. Os arquivos deste padrão etiquetam suas cores com perfis ICC. Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. Os arquivos deste padrão etiquetam suas cores com perfis ICC, exceto as cores CMYK no perfil de intenção de saída, que são gravadas como DeviceCMYK. + With Don't include profiles and a CMYK output intent, every CMYK color is written as DeviceCMYK unless it is converted to a CMYK destination of another profile. Com “Não incluir perfis” e uma intenção de saída CMYK, cada cor CMYK é gravada como DeviceCMYK, a menos que seja convertida para um destino CMYK de outro perfil. Fill Preenchimento Fill & Stroke Preenchimento e Traçado Fill Color Cor de Preenchimento diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index aa78f6335c..9a023cafed 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -1255,6 +1255,7 @@ font-technology Variable Вариативные Files of a PDF standard can't be password-protected. Файлы стандарта PDF не могут быть защищены паролем. Files of this standard tag their colours with ICC profiles. Файлы этого стандарта помечают свои цвета профилями ICC. Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. Файлы этого стандарта помечают свои цвета профилями ICC, кроме цветов CMYK в профиле назначения вывода, которые записываются как DeviceCMYK. + With Don't include profiles and a CMYK output intent, every CMYK color is written as DeviceCMYK unless it is converted to a CMYK destination of another profile. При «Не включать профили» и назначении вывода CMYK каждый цвет CMYK записывается как DeviceCMYK, если он не преобразуется в назначение CMYK с другим профилем. Fill Заливка Fill & Stroke Заливка и обводка Fill (X), double-click for the Color Picker Заливка (X), дважды щёлкните для палитры цветов diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 8600a0b479..d1df41ab74 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -1227,6 +1227,7 @@ font-technology Variable Variabla Files of a PDF standard can't be password-protected. Filer enligt en PDF-standard kan inte lösenordsskyddas. Files of this standard tag their colours with ICC profiles. Filer enligt den här standarden märker sina färger med ICC-profiler. Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. Filer enligt den här standarden märker sina färger med ICC-profiler, utom CMYK-färger i profilen för utgångsavsikt, som skrivs som DeviceCMYK. + With Don't include profiles and a CMYK output intent, every CMYK color is written as DeviceCMYK unless it is converted to a CMYK destination of another profile. Med ”Inkludera inte profiler” och en CMYK-utgångsavsikt skrivs varje CMYK-färg som DeviceCMYK, om den inte konverteras till ett CMYK-mål med en annan profil. Fill Fyllning Fill & Stroke Fyllning och kontur Fill (X), double-click for the Color Picker Fyllning (X), dubbelklicka för färgväljaren diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 154683b0d1..5e88528886 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -1218,6 +1218,7 @@ font-technology Variable Değişken Files of a PDF standard can't be password-protected. PDF standardının dosyaları parola korumalı olamaz. Files of this standard tag their colours with ICC profiles. Bu standardın dosyaları renklerini ICC profilleriyle etiketler. Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. Bu standardın dosyaları renklerini ICC profilleriyle etiketler, ancak çıkış amacı profilindeki CMYK renkleri DeviceCMYK olarak yazılır. + With Don't include profiles and a CMYK output intent, every CMYK color is written as DeviceCMYK unless it is converted to a CMYK destination of another profile. “Profilleri ekleme” ve bir CMYK çıkış amacıyla, başka bir profilin CMYK hedefine dönüştürülmedikçe her CMYK rengi DeviceCMYK olarak yazılır. Fill Dolgu Fill & Stroke Doldur ve Konturla Fill (X), double-click for the Color Picker Doldur (X), Renk Seçici için çift tıklayın diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 6f1fbfb0cf..064498d960 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -1260,6 +1260,7 @@ font-technology Variable Варіативні Files of a PDF standard can't be password-protected. Файли стандарту PDF не можуть бути захищені паролем. Files of this standard tag their colours with ICC profiles. Файли цього стандарту позначають свої кольори профілями ICC. Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. Файли цього стандарту позначають свої кольори профілями ICC, крім кольорів CMYK у профілі призначення виведення, які записуються як DeviceCMYK. + With Don't include profiles and a CMYK output intent, every CMYK color is written as DeviceCMYK unless it is converted to a CMYK destination of another profile. З «Не включати профілі» та призначенням виведення CMYK кожен колір CMYK записується як DeviceCMYK, якщо його не перетворено в призначення CMYK з іншим профілем. Fill Заливка Fill & Stroke Заливка та обведення Fill (X), double-click for the Color Picker Заливка (X), двічі клацніть на палітрі кольорів diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index e1811b090b..158dc02592 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -1452,6 +1452,7 @@ digits Malayalam Malayalam Files of a PDF standard can't be password-protected. Tệp theo tiêu chuẩn PDF không thể bảo vệ bằng mật khẩu. Files of this standard tag their colours with ICC profiles. Tệp theo tiêu chuẩn này gắn thẻ màu bằng hồ sơ ICC. Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. Tệp theo tiêu chuẩn này gắn thẻ màu bằng hồ sơ ICC, trừ các màu CMYK trong hồ sơ mục đích đầu ra, được ghi dưới dạng DeviceCMYK. + With Don't include profiles and a CMYK output intent, every CMYK color is written as DeviceCMYK unless it is converted to a CMYK destination of another profile. Với “Không bao gồm hồ sơ” và mục đích đầu ra CMYK, mọi màu CMYK được ghi dưới dạng DeviceCMYK, trừ khi được chuyển đổi sang đích CMYK của hồ sơ khác. Fill Tô Fill & Stroke Tô & Nét Fill (X), double-click for the Color Picker Tô (X), bấm đúp để mở Bộ chọn màu diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index 4c3814bcea..4a9a48d18f 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -1196,6 +1196,7 @@ antiAlias Sharp 锐利 Files of a PDF standard can't be password-protected. PDF 标准的文件无法设置密码保护。 Files of this standard tag their colours with ICC profiles. 此标准的文件会以 ICC 配置文件标记颜色。 Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. 此标准的文件会以 ICC 配置文件标记颜色,但输出意图配置文件中的 CMYK 颜色会写为 DeviceCMYK。 + With Don't include profiles and a CMYK output intent, every CMYK color is written as DeviceCMYK unless it is converted to a CMYK destination of another profile. 选择“不包含配置文件”且输出意图为 CMYK 时,除非转换为其他配置文件的 CMYK 目标,否则每种 CMYK 颜色都会写为 DeviceCMYK。 Fill 填色 Fill & Stroke 填色和描边 Fill (X), double-click for the Color Picker 填色 (X),双击打开拾色器 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 1c5db20e0a..1bf4beb616 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -1230,6 +1230,7 @@ font-technology Variable 可變 Files of a PDF standard can't be password-protected. PDF 標準的檔案無法設定密碼保護。 Files of this standard tag their colours with ICC profiles. 此標準的檔案會以 ICC 描述檔標記顏色。 Files of this standard tag their colors with ICC profiles, except CMYK colors in the output intent's profile, which are written as DeviceCMYK. 此標準的檔案會以 ICC 描述檔標記顏色,但輸出目的描述檔中的 CMYK 顏色會寫為 DeviceCMYK。 + With Don't include profiles and a CMYK output intent, every CMYK color is written as DeviceCMYK unless it is converted to a CMYK destination of another profile. 選擇「不包含描述檔」且輸出目的為 CMYK 時,除非轉換為其他描述檔的 CMYK 目的地,否則每種 CMYK 顏色都會寫為 DeviceCMYK。 Fill 填色 Fill & Stroke 填色與筆畫 Fill (X), double-click for the Color Picker 填色 (X),按兩下開啟檢色器 From cd4e9e95060946502957f0427a3d91d083ac6c1d Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 17 Nov 2026 09:57:07 -0800 Subject: [PATCH 105/176] Transform: a live line shows Line Properties with Line Length and Line Angle A line drawn with the Line Segment tool now shows Line Properties in the Transform panel and the Properties panel's Transform section, with the two properties the help page lists for a line: https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/live-shape-properties.html - object.setLiveShape takes lineLength (pt, above 0) and lineAngle (degrees, brought into 0 to 360). Every selected line changes in one undo step; a value that changes nothing records none. - VectorCraft's own rules: the angle runs counterclockwise from 3 o'clock, as the Rotate field does; a new length keeps the first end in place and a new angle turns the line about its midpoint; a line whose ends meet reads 0 degrees; the section shows only while every selected object is a live line; a line that would reach past the coordinate limit is an error that changes no line. Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/doc/src/node/live_shape.rs | 42 +++++++++ crates/engine/src/cmd/object/commands.rs | 2 +- crates/engine/src/cmd/object/shape.rs | 55 +++++++++++- crates/engine/src/tests/livecorners.rs | 95 ++++++++++++++++++++ crates/engine/src/tests/params.rs | 1 + crates/engine/tests/command_sweep.rs | 30 +++++++ crates/ui-egui/src/i18n/bg.tsv | 3 + crates/ui-egui/src/i18n/bs.tsv | 3 + crates/ui-egui/src/i18n/ca.tsv | 3 + crates/ui-egui/src/i18n/cs.tsv | 3 + crates/ui-egui/src/i18n/da.tsv | 3 + crates/ui-egui/src/i18n/de.tsv | 3 + crates/ui-egui/src/i18n/el.tsv | 3 + crates/ui-egui/src/i18n/es.tsv | 3 + crates/ui-egui/src/i18n/fi.tsv | 3 + crates/ui-egui/src/i18n/fr.tsv | 3 + crates/ui-egui/src/i18n/gu.tsv | 3 + crates/ui-egui/src/i18n/hi.tsv | 3 + crates/ui-egui/src/i18n/hu.tsv | 3 + crates/ui-egui/src/i18n/id.tsv | 3 + crates/ui-egui/src/i18n/it.tsv | 3 + crates/ui-egui/src/i18n/ja.tsv | 3 + crates/ui-egui/src/i18n/ka.tsv | 3 + crates/ui-egui/src/i18n/ko.tsv | 3 + crates/ui-egui/src/i18n/nl.tsv | 3 + crates/ui-egui/src/i18n/pl.tsv | 3 + crates/ui-egui/src/i18n/pt-br.tsv | 3 + crates/ui-egui/src/i18n/ru.tsv | 3 + crates/ui-egui/src/i18n/sv.tsv | 3 + crates/ui-egui/src/i18n/tr.tsv | 3 + crates/ui-egui/src/i18n/uk.tsv | 3 + crates/ui-egui/src/i18n/vi.tsv | 3 + crates/ui-egui/src/i18n/zh-hans.tsv | 3 + crates/ui-egui/src/i18n/zh-hant.tsv | 3 + crates/ui-egui/src/panels/transform.rs | 49 +++++++++- crates/ui-egui/src/panels/transform/tests.rs | 46 ++++++++++ docs/mcp.md | 8 +- docs/target-app-parity.md | 1 + 38 files changed, 406 insertions(+), 7 deletions(-) diff --git a/crates/doc/src/node/live_shape.rs b/crates/doc/src/node/live_shape.rs index 9ddc4e1bb6..a384836442 100644 --- a/crates/doc/src/node/live_shape.rs +++ b/crates/doc/src/node/live_shape.rs @@ -179,6 +179,48 @@ impl LiveShape { *xf = Affine::rotate_about((now - angle).to_radians(), centre) * *xf; } } + /// A line's length in the document, from its first end to its second. None for other shapes. + pub fn line_length(&self) -> Option<f64> { + let LiveShape::Line { a, b } = self else { return None }; + Some((*b - *a).hypot()) + } + /// A line's angle: the counterclockwise degrees in [0, 360) from the page's horizontal to the + /// direction from its first end to its second (the Rotate field's sense). 0 for a line whose + /// ends meet. None for other shapes. + pub fn line_angle(&self) -> Option<f64> { + let LiveShape::Line { a, b } = self else { return None }; + if a == b { + return Some(0.0); + } + // No −0° or 360° from rounding: a line drawn left to right reads 0°. + let a = (-self.angle_deg()).rem_euclid(360.0); + Some(if a > 360.0 - 1e-9 { 0.0 } else { a + 0.0 }) + } + /// Make a line `len` long (0 or more), keeping its first end in place and its direction, or + /// pointing it to the right when its ends meet. + pub fn set_line_length(&mut self, len: f64) { + let LiveShape::Line { a, b } = self else { return }; + if !len.is_finite() || len < 0.0 { + return; + } + let now = (*b - *a).hypot(); + *b = if now > 0.0 { *a + (*b - *a) * (len / now) } else { Point::new(a.x + len, a.y) }; + } + /// Turn a line about its midpoint to `angle` (degrees, as [`LiveShape::line_angle`]). A line + /// whose ends meet stays as it is. + pub fn set_line_angle(&mut self, angle: f64) { + let LiveShape::Line { a, b } = self else { return }; + let half = (*b - *a).hypot() / 2.0; + if !angle.is_finite() || half <= 0.0 { + return; + } + let mid = a.midpoint(*b); + let t = angle.to_radians(); + // The page's y axis points down, so a counterclockwise angle goes up the page. + let (dx, dy) = (half * t.cos(), -half * t.sin()); + *a = Point::new(mid.x - dx, mid.y - dy); + *b = Point::new(mid.x + dx, mid.y + dy); + } /// Make a polygon's sides equal (Make Sides Equal): drop the uneven scale and the shear from /// `xf`, keeping its centre, angle, reflection and [`LiveShape::polygon_radius`]. pub fn make_sides_equal(&mut self) { diff --git a/crates/engine/src/cmd/object/commands.rs b/crates/engine/src/cmd/object/commands.rs index d9c0b22d4b..3e9d5dbdad 100644 --- a/crates/engine/src/cmd/object/commands.rs +++ b/crates/engine/src/cmd/object/commands.rs @@ -297,7 +297,7 @@ pub fn specs() -> Vec<CommandSpec> { "Live Shape Properties", [], None, - "{id?, ids?, radius?: pt (or % of each corner's maximum when `relativeRadii` is true), kind?: \"round\"|\"invertedRound\"|\"chamfer\", relativeRadii?: bool (Relative rounding, as in the reference app: store radii as fractions of each corner's maximum so they scale with the shape), corners?: [i…], items?: [{id, corners?: [i…]}] (several objects, each with its own corners, in place of ids and corners: the canvas's corner widgets across a selection), sides?: n, polygonAngle?: degrees (counter-clockwise from its first vertex straight up), polygonRadius?: pt (centre to vertex), sideLength?: pt (sets the radius), makeSidesEqual?: true (a polygon scaled unevenly: drops the uneven scale and shear, keeping its centre, angle and mean radius), pieStart?, pieEnd?: degrees (an ellipse's pie, counter-clockwise from 3 o'clock; 0 to 360 is the whole ellipse), invertPie?: true (swaps them: the other part of the ellipse)} (Live Corners on any path: radius and kind set its corners (anchors that aren't smooth, where two sides, straight or curved (#1144), meet at an angle): `corners` (anchor indices of the path with its corners uncut, counting every subpath's anchors in order: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; a polygon's from the first vertex clockwise), else the corners with a Direct-Selected anchor, else every corner; each radius is drawn no larger than half the corner's shorter side allows; a path that isn't a live shape keeps its uncut outline so its corners stay editable, and is plain again once none is cut; sides: a polygon's, which keep the radius they shared; the polygon params apply in that order: sides, makeSidesEqual, polygonAngle, then sideLength or else polygonRadius)", + "{id?, ids?, radius?: pt (or % of each corner's maximum when `relativeRadii` is true), kind?: \"round\"|\"invertedRound\"|\"chamfer\", relativeRadii?: bool (Relative rounding, as in the reference app: store radii as fractions of each corner's maximum so they scale with the shape), corners?: [i…], items?: [{id, corners?: [i…]}] (several objects, each with its own corners, in place of ids and corners: the canvas's corner widgets across a selection), sides?: n, polygonAngle?: degrees (counter-clockwise from its first vertex straight up), polygonRadius?: pt (centre to vertex), sideLength?: pt (sets the radius), makeSidesEqual?: true (a polygon scaled unevenly: drops the uneven scale and shear, keeping its centre, angle and mean radius), pieStart?, pieEnd?: degrees (an ellipse's pie, counter-clockwise from 3 o'clock; 0 to 360 is the whole ellipse), invertPie?: true (swaps them: the other part of the ellipse), lineLength?: pt (a live line's length, above 0; its first end stays), lineAngle?: degrees (a live line's angle, counter-clockwise from 3 o'clock, from its first end to its second; it turns about its midpoint)} (Live Corners on any path: radius and kind set its corners (anchors that aren't smooth, where two sides, straight or curved (#1144), meet at an angle): `corners` (anchor indices of the path with its corners uncut, counting every subpath's anchors in order: a rectangle's 0 top-left, 1 top-right, 2 bottom-right, 3 bottom-left; a polygon's from the first vertex clockwise), else the corners with a Direct-Selected anchor, else every corner; each radius is drawn no larger than half the corner's shorter side allows; a path that isn't a live shape keeps its uncut outline so its corners stay editable, and is plain again once none is cut; sides: a polygon's, which keep the radius they shared; the polygon params apply in that order: sides, makeSidesEqual, polygonAngle, then sideLength or else polygonRadius; a line's lineLength applies before its lineAngle)", has_selection, set_live_shape ), diff --git a/crates/engine/src/cmd/object/shape.rs b/crates/engine/src/cmd/object/shape.rs index b30959de99..0c5a16b00c 100644 --- a/crates/engine/src/cmd/object/shape.rs +++ b/crates/engine/src/cmd/object/shape.rs @@ -6,6 +6,7 @@ use super::{ BTreeSet, CornerKind, EngineError, LiveCorners, LiveShape, NodeId, NodeKind, Result, Session, Value, bad, check_numbers, check_switches, convert_radii_relative, ok, selected_roots, set_corners, targets, }; +use crate::MAX_COORD; /// The largest scale of 0 or more at which `spans`, with the margins that scale grown by `k`, /// reach across `size` together. Returns 1 when their geometric boxes reach 1e-9 or less across @@ -98,6 +99,30 @@ fn corners_param(p: &Value) -> Result<Option<BTreeSet<usize>>> { list.iter().map(|k| k.as_u64().and_then(|k| usize::try_from(k).ok()).ok_or_else(err)).collect::<Result<_>>().map(Some) } +/// Live line `l` with Line Length `len` (its first end stays) and then Line Angle `angle` (about +/// its midpoint; a line whose ends meet has none to turn), or None when neither changes it. +fn line_edit(l: &LiveShape, len: Option<f64>, angle: Option<f64>) -> Option<LiveShape> { + let now = l.line_length()?; + let mut new = l.clone(); + let mut changed = false; + if let Some(len) = len + && (len - now).abs() > 1e-9 * len.max(now) + { + new.set_line_length(len); + changed = true; + } + if let Some(a) = angle + && new.line_length().is_some_and(|n| n > 0.0) + && let Some(turn) = new.line_angle().map(|now| (a - now).rem_euclid(360.0)) + && turn > 1e-9 + && turn < 360.0 - 1e-9 + { + new.set_line_angle(a); + changed = true; + } + changed.then_some(new) +} + pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result<Value> { check_switches(p, &["invertPie", "makeSidesEqual", "relativeRadii"], "object.setLiveShape")?; check_numbers(p, &["radius", "sides"], "object.setLiveShape")?; @@ -148,7 +173,7 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result<Value> { } }; let angle = |k: &str| Ok::<_, EngineError>(number(k, |_| true, "an angle in degrees")?.map(|a| a.rem_euclid(360.0))); - let length = |k: &str| number(k, |x| x > 0.0 && x <= crate::MAX_COORD, "a length in points above 0"); + let length = |k: &str| number(k, |x| x > 0.0 && x <= MAX_COORD, "a length in points above 0"); // Saved steps ([`Session::replay`]) can hold values a direct call refuses, recorded before these // checks: a negative radius is 0, a whole side count of 0 or more is brought into 3 to 1000, and // a fractional or negative one is ignored. A whole number written as 5.0 counts as 5, as in a @@ -171,6 +196,10 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result<Value> { // A polygon's Polygon Properties: its angle, radius or side length, Make Sides Equal. let (polygon_angle, polygon_radius, side) = (angle("polygonAngle")?, length("polygonRadius")?, length("sideLength")?); let equal = p.get("makeSidesEqual").and_then(Value::as_bool) == Some(true); + // A line's Line Properties: its length (its first end stays) and its angle (about its midpoint). + // A line's length can reach across the whole canvas, past `MAX_COORD`: its ends are checked below. + let line_length = number("lineLength", |x| x > 0.0, "a length in points above 0")?; + let line_angle = angle("lineAngle")?; // An ellipse's pie becomes `pie_of(pie)`. An end of 0 is a full turn (Illustrator shows a whole // ellipse as 0° to 360°). let end_of = |a: f64| if a == 0.0 { 360.0 } else { a }; @@ -181,8 +210,26 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result<Value> { // When every value given is the current one, the document and its undo history stay as they // are. let st = s.doc()?; + // The lines that Line Length or Line Angle changes, as they become. A line that would reach + // past the document's coordinate limit is an error before anything changes. + let mut lines = std::collections::BTreeMap::new(); + if line_length.is_some() || line_angle.is_some() { + for id in &ids { + let Some(NodeKind::Path { live: Some(l), .. }) = st.doc.node(*id).map(|n| &n.kind) else { continue }; + if let Some(new) = line_edit(l, line_length, line_angle) { + let LiveShape::Line { a, b } = &new else { continue }; + if ![a.x, a.y, b.x, b.y].iter().all(|c| c.abs() <= MAX_COORD) { + return Err(bad("object.setLiveShape", format!("coordinate out of range (limit ±{MAX_COORD} pt)"))); + } + lines.insert(*id, new); + } + } + } let has_values = |id: &NodeId| { let Some(NodeKind::Path { path, live, .. }) = st.doc.node(*id).map(|n| &n.kind) else { return true }; + if lines.contains_key(id) { + return false; + } match live.as_deref() { Some(l @ LiveShape::Polygon { sides: now, .. }) if !(sides.is_none_or(|n| n.clamp(3, 1000) == u64::from(*now)) @@ -244,6 +291,12 @@ pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result<Value> { } *path = l.to_path(); } + if let Some(new) = lines.get(id) + && let Some(l) = live.as_deref_mut() + { + *l = new.clone(); + *path = l.to_path(); + } if let Some(on) = relative_radii && let Some(l) = live.as_deref_mut() { diff --git a/crates/engine/src/tests/livecorners.rs b/crates/engine/src/tests/livecorners.rs index b9e3793913..f32d0c8257 100644 --- a/crates/engine/src/tests/livecorners.rs +++ b/crates/engine/src/tests/livecorners.rs @@ -524,6 +524,101 @@ fn a_polygon_takes_its_angle_radius_side_length_and_equal_sides() { } } +/// A live line's Line Properties: Line Length keeps its first end in place, Line Angle (degrees +/// counterclockwise, any finite value brought into 0 to 360) turns it about its midpoint, the +/// length applies before the angle, every selected line takes them in one undo step, and a value +/// that changes nothing records none. +#[test] +fn a_line_takes_its_length_and_angle() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + let line = |s: &mut Session, a: (f64, f64), b: (f64, f64)| { + NodeId(s.execute("shape.line", &json!({"x1": a.0, "y1": a.1, "x2": b.0, "y2": b.1})).unwrap()["id"].as_u64().unwrap()) + }; + let id = line(&mut s, (100.0, 100.0), (200.0, 100.0)); + let ends = |s: &Session, id: NodeId| match &s.doc().unwrap().doc.node(id).unwrap().kind { + NodeKind::Path { live: Some(l), path, .. } => { + let LiveShape::Line { a, b } = **l else { panic!("{l:?}") }; + assert_eq!(*path, l.to_path(), "the path follows the line"); + (a.x, a.y, b.x, b.y) + } + k => panic!("{k:?}"), + }; + let near = |got: (f64, f64, f64, f64), want: (f64, f64, f64, f64)| { + assert!([got.0 - want.0, got.1 - want.1, got.2 - want.2, got.3 - want.3].iter().all(|d| d.abs() < 1e-9), "{got:?} ≠ {want:?}") + }; + let steps = |s: &Session| s.doc().unwrap().history.undo.len(); + run(&mut s, json!({"lineLength": 50})); + near(ends(&s, id), (100.0, 100.0, 150.0, 100.0)); + // 90° points up the page. + run(&mut s, json!({"lineAngle": 90})); + near(ends(&s, id), (125.0, 125.0, 125.0, 75.0)); + let n = steps(&s); + for same in [json!({"lineAngle": 450}), json!({"lineAngle": -270}), json!({"lineLength": 50}), json!({"lineLength": 50, "lineAngle": 90})] { + run(&mut s, same.clone()); + assert_eq!(steps(&s), n, "{same} records no undo step"); + } + near(ends(&s, id), (125.0, 125.0, 125.0, 75.0)); + run(&mut s, json!({"lineLength": 20, "lineAngle": 0})); + near(ends(&s, id), (115.0, 115.0, 135.0, 115.0)); + assert_eq!(steps(&s), n + 1, "both in one step"); + run(&mut s, json!({"lineAngle": 180})); + near(ends(&s, id), (135.0, 115.0, 115.0, 115.0)); + run(&mut s, json!({"lineAngle": -90})); + near(ends(&s, id), (125.0, 105.0, 125.0, 125.0)); + let LiveShape::Line { .. } = s.doc().unwrap().doc.node(id).unwrap().live_shape().unwrap() else { panic!("still live") }; + assert_eq!(s.doc().unwrap().doc.node(id).unwrap().live_shape().unwrap().line_angle(), Some(270.0)); + // Several lines: each keeps its own first end, in one undo step. + let other = line(&mut s, (0.0, 0.0), (0.0, 40.0)); + let n = steps(&s); + run(&mut s, json!({"ids": [id.0, other.0], "lineLength": 10})); + near(ends(&s, id), (125.0, 105.0, 125.0, 115.0)); + near(ends(&s, other), (0.0, 0.0, 0.0, 10.0)); + assert_eq!(steps(&s), n + 1); + s.execute("edit.undo", &json!({})).unwrap(); + near(ends(&s, id), (125.0, 105.0, 125.0, 125.0)); + near(ends(&s, other), (0.0, 0.0, 0.0, 40.0)); + // Bad values, and a line that would reach past the coordinate limit, change neither line. + let far = line(&mut s, (3_900_000.0, 0.0), (3_900_100.0, 0.0)); + let n = steps(&s); + for bad in [ + json!({"ids": [id.0], "lineLength": 0}), + json!({"ids": [id.0], "lineLength": -3}), + json!({"ids": [id.0], "lineLength": "long"}), + json!({"ids": [id.0], "lineAngle": "up"}), + json!({"ids": [id.0], "lineLength": 1e300}), + json!({"ids": [id.0, far.0], "lineLength": 200_000}), + ] { + assert!(s.execute("object.setLiveShape", &bad).is_err(), "{bad}"); + assert_eq!(steps(&s), n, "{bad}"); + } + near(ends(&s, id), (125.0, 105.0, 125.0, 125.0)); + near(ends(&s, far), (3_900_000.0, 0.0, 3_900_100.0, 0.0)); + // A length past the coordinate limit is fine while both ends stay inside it. + let wide = line(&mut s, (-3_500_000.0, 0.0), (3_500_000.0, 0.0)); + run(&mut s, json!({"ids": [wide.0], "lineLength": 6_000_000})); + near(ends(&s, wide), (-3_500_000.0, 0.0, 2_500_000.0, 0.0)); + // A line whose ends meet reads 0°: an angle leaves it as it is, and a length points it right. + let dot = line(&mut s, (10.0, 10.0), (10.0, 10.0)); + assert_eq!(s.doc().unwrap().doc.node(dot).unwrap().live_shape().unwrap().line_angle(), Some(0.0)); + let n = steps(&s); + run(&mut s, json!({"lineAngle": 45})); + assert_eq!(steps(&s), n); + run(&mut s, json!({"lineLength": 30})); + near(ends(&s, dot), (10.0, 10.0, 40.0, 10.0)); + // A very short length is applied. + let speck = line(&mut s, (20.0, 20.0), (20.0, 20.0)); + let n = steps(&s); + run(&mut s, json!({"ids": [speck.0], "lineLength": 1e-12})); + assert_eq!(steps(&s), n + 1, "a length of 1e-12 pt is a change"); + assert!(ends(&s, speck).2 > 20.0, "{:?}", ends(&s, speck)); + // Other live shapes ignore the line params. + let rect = NodeId(s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap()); + let n = steps(&s); + run(&mut s, json!({"ids": [rect.0], "lineLength": 30, "lineAngle": 45})); + assert_eq!(steps(&s), n); +} + #[test] fn relative_corner_rounding_keeps_fraction_on_resize() { let (mut s, id) = session(); diff --git a/crates/engine/src/tests/params.rs b/crates/engine/src/tests/params.rs index 708b602d1f..059dd041a3 100644 --- a/crates/engine/src/tests/params.rs +++ b/crates/engine/src/tests/params.rs @@ -430,6 +430,7 @@ fn set_live_shape_refuses_an_unknown_key() { json!({"id": 3, "radius": 5}), json!({"ids": [3], "sides": 6, "polygonAngle": 15, "polygonRadius": 20, "sideLength": null, "makeSidesEqual": true}), json!({"pieStart": 30, "pieEnd": 90, "invertPie": true}), + json!({"ids": [3], "lineLength": 72, "lineAngle": 90}), json!({"items": null}), ] { assert!(check_params(ID, &ok).is_ok(), "{ok}"); diff --git a/crates/engine/tests/command_sweep.rs b/crates/engine/tests/command_sweep.rs index fd1edc9b77..d4e6129da4 100644 --- a/crates/engine/tests/command_sweep.rs +++ b/crates/engine/tests/command_sweep.rs @@ -1256,6 +1256,36 @@ fn polygon_properties_junk() { assert!(failures.is_empty(), "{} failures:\n{}", failures.len(), failures.join("\n")); } +/// A live line's Line Properties with junk values (the fixtures have no line), on a line, a line +/// whose ends meet and one at the coordinate limit: never a panic, and the document stays sound. +#[test] +fn line_properties_junk() { + let mut cases: Vec<Value> = vec![json!({"lineLength": 4.0e6, "lineAngle": 45})]; + for key in ["lineLength", "lineAngle"] { + for v in junk_values() { + cases.push(json!({ key: v })); + } + } + let mut failures = vec![]; + for (a, b) in [((10.0, 20.0), (110.0, 70.0)), ((50.0, 50.0), (50.0, 50.0)), ((-4.0e6, 4.0e6), (4.0e6, -4.0e6))] { + for p in &cases { + let mut s = Fixture::Multi.session(); + let Ok(_) = no_panic(s.execute("shape.line", &json!({"x1": a.0, "y1": a.1, "x2": b.0, "y2": b.1}))) else { + continue; + }; + match catch_quiet(|| no_panic(s.execute("object.setLiveShape", p))) { + Err(m) => failures.push(format!("PANIC object.setLiveShape {p} [{a:?} {b:?}]: {m}")), + Ok(_) => { + if let Err(e) = catch_quiet(|| check_all(&mut s)).unwrap_or_else(|m| Err(format!("panic in checks: {m}"))) { + failures.push(format!("object.setLiveShape {p} [{a:?} {b:?}]: {e}")); + } + } + } + } + } + assert!(failures.is_empty(), "{} failures:\n{}", failures.len(), failures.join("\n")); +} + /// The params `fuzzed_calls_keep_documents_serializable` sends `c`: each key with each of the /// first junk values, a string under a file or folder key replaced by a location inside `path`'s /// folder. diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index bb039bb08e..cebf101e77 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -2599,6 +2599,9 @@ font-technology Variable Променливи Polar Grid Tool Инструмент „Полярна мрежа“ Polygon Многоъгълник Polygon Properties: Свойства на многоъгълника: + Line Properties: Свойства на линията: + Line Length: Дължина на линията: + Line Angle: Ъгъл на линията: Polygon Tool Инструмент „Многоъгълник“ Portrait Портретна Power Saving (integrated) Пестене на енергия (интегрирано) diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 99f23d313c..164c433cfa 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -2346,6 +2346,9 @@ digits Malayalam Malajalam Flip Horizontal Preokreni vodoravno Flip Vertical Preokreni okomito Polygon Properties: Svojstva mnogougla: + Line Properties: Svojstva linije: + Line Length: Dužina linije: + Line Angle: Ugao linije: Rectangle Properties: Svojstva pravougaonika: Shape Properties: Svojstva oblika: Shape Properties Svojstva oblika diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index c54311799d..439b284d46 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -3365,6 +3365,9 @@ digits Malayalam Malaiàlam Polar Grid Tool Options Opcions de l’eina de quadrícula polar Polygon Polígon Polygon Properties: Propietats del polígon: + Line Properties: Propietats de la línia: + Line Length: Longitud de la línia: + Line Angle: Angle de la línia: Polygon Tool Eina de polígon Portrait Vertical Portrait (flipped) Vertical (invertit) diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index a5d7bb948a..b2b9eaeea5 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -2419,6 +2419,9 @@ digits Malayalam Malajálamské Flip Horizontal Překlopit vodorovně Flip Vertical Překlopit svisle Polygon Properties: Vlastnosti mnohoúhelníku: + Line Properties: Vlastnosti čáry: + Line Length: Délka čáry: + Line Angle: Úhel čáry: Rectangle Properties: Vlastnosti obdélníku: Shape Properties: Vlastnosti tvaru: Shape Properties Vlastnosti tvaru diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 08100f593f..db29199900 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -4910,6 +4910,9 @@ digits Malayalam Malayalam Flip Horizontal Spejl vandret Flip Vertical Spejl lodret Polygon Properties: Polygonegenskaber: + Line Properties: Linjeegenskaber: + Line Length: Linjelængde: + Line Angle: Linjevinkel: Rectangle Properties: Rektangelegenskaber: Shape Properties: Figuregenskaber: Shape Properties Figuregenskaber diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 10147b2d45..4aad9da8f0 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -2647,6 +2647,9 @@ diagnostics ui Oberfläche Polar Grid Tool Radiales-Raster-Werkzeug Polygon Polygon Polygon Properties: Polygoneigenschaften: + Line Properties: Linieneigenschaften: + Line Length: Linienlänge: + Line Angle: Linienwinkel: Polygon Tool Polygon-Werkzeug Portrait Hochformat Power Saving (integrated) Energiesparen (integriert) diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 1ebf6e5684..f771513ed4 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -3555,6 +3555,9 @@ theme Appearance Εμφάνιση Polar Grid Tool Πολικό πλέγμα (Polar Grid Tool) Polygon Πολύγωνο Polygon Properties: Ιδιότητες πολυγώνου: + Line Properties: Ιδιότητες γραμμής: + Line Length: Μήκος γραμμής: + Line Angle: Γωνία γραμμής: Power Saving (integrated) Εξοικονόμηση ενέργειας (ενσωματωμένη GPU) Portuguese Πορτογαλικά PostScript: PostScript: diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index a456910a16..8e8a49630e 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -2688,6 +2688,9 @@ font-technology Variable Variables Polar Grid Tool Herramienta Cuadrícula polar Polygon Polígono Polygon Properties: Propiedades del polígono: + Line Properties: Propiedades de la línea: + Line Length: Longitud de la línea: + Line Angle: Ángulo de la línea: Polygon Tool Herramienta Polígono Portrait Vertical Power Saving (integrated) Ahorro de energía (integrada) diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index bff46fc0d7..e6f4333bf1 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -2380,6 +2380,9 @@ digits Malayalam Malajalam Flip Horizontal Käännä vaakasuunnassa Flip Vertical Käännä pystysuunnassa Polygon Properties: Monikulmion ominaisuudet: + Line Properties: Viivan ominaisuudet: + Line Length: Viivan pituus: + Line Angle: Viivan kulma: Rectangle Properties: Suorakulmion ominaisuudet: Shape Properties: Muodon ominaisuudet: Shape Properties Muodon ominaisuudet diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 3be3497f97..c99245fbbf 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -2676,6 +2676,9 @@ font-technology Variable Variables Polar Grid Tool Outil Grille à coordonnées polaires Polygon Polygone Polygon Properties: Propriétés du polygone : + Line Properties: Propriétés de la ligne : + Line Length: Longueur de la ligne : + Line Angle: Angle de la ligne : Polygon Tool Outil Polygone Portrait Portrait Power Saving (integrated) Économie d’énergie (intégrée) diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index c427fc527c..ed9f3b9ae6 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -2757,6 +2757,9 @@ Polish પોલિશ Polygon બહુકોણ Polygon Properties: બહુકોણના ગુણધર્મો: + Line Properties: રેખાના ગુણધર્મો: + Line Length: રેખાની લંબાઈ: + Line Angle: રેખાનો કોણ: Polygon Tool બહુકોણ ટૂલ Polygonal Lasso બહુકોણીય લાસો Polygonal Lasso Tool બહુકોણીય લાસો ટૂલ diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index cbfb4f51d1..a53390ce50 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -3697,6 +3697,9 @@ antiAlias Sharp शार्प Polish पोलिश Polygon बहुभुज Polygon Properties: बहुभुज प्रॉपर्टीज़: + Line Properties: रेखा प्रॉपर्टीज़: + Line Length: रेखा की लंबाई: + Line Angle: रेखा का कोण: Polygon Tool पॉलीगोन टूल Polygonal Lasso बहुभुज लैस्सो Polygonal Lasso Tool बहुभुज लैस्सो टूल diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 0f81a72036..1accf9422c 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -3239,6 +3239,9 @@ diagnostics ui felület Polar Grid Tool Polárrács Polygon Sokszög Polygon Properties: Sokszög tulajdonságai: + Line Properties: Vonal tulajdonságai: + Line Length: Vonal hossza: + Line Angle: Vonal szöge: Polygon Tool Sokszög Portrait Álló Portrait (flipped) Álló (megfordítva) diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 28ea2b5ab3..912ad02885 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -2169,6 +2169,9 @@ digits Malayalam Malayalam Flip Horizontal Balik horizontal Flip Vertical Balik vertikal Polygon Properties: Properti poligon: + Line Properties: Properti garis: + Line Length: Panjang garis: + Line Angle: Sudut garis: Rectangle Properties: Properti persegi panjang: Shape Properties: Properti bentuk: Shape Properties Properti bentuk diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 8f2ed3216c..7955e16401 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -2728,6 +2728,9 @@ diagnostics ui interfaccia Polar Grid Tool Strumento Griglia polare Polygon Poligono Polygon Properties: Proprietà poligono: + Line Properties: Proprietà linea: + Line Length: Lunghezza linea: + Line Angle: Angolo linea: Polygon Tool Strumento Poligono Portrait Verticale Power Saving (integrated) Risparmio energetico (integrata) diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index c429f204a1..e7f59d5380 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -2812,6 +2812,9 @@ diagnostics ui UI Polar Grid Tool 同心円グリッドツール Polygon 多角形 Polygon Properties: 多角形のプロパティ: + Line Properties: 線のプロパティ: + Line Length: 線の長さ: + Line Angle: 線の角度: Polygon Tool 多角形ツール Portrait 縦置き Portuguese ポルトガル語 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 414f45171c..595b8176a8 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -4337,6 +4337,9 @@ digits Malayalam მალაიალამური Flip Horizontal ჰორიზონტალურად არეკვლა Flip Vertical ვერტიკალურად არეკვლა Polygon Properties: მრავალკუთხედის თვისებები: + Line Properties: ხაზის თვისებები: + Line Length: ხაზის სიგრძე: + Line Angle: ხაზის კუთხე: Rectangle Properties: მართკუთხედის თვისებები: Shape Properties: ფიგურის თვისებები: Shape Properties ფიგურის თვისებები diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index dbda53243f..dda811e472 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -2802,6 +2802,9 @@ diagnostics ui UI Polar Grid Tool 극좌표 격자 도구 Polygon 다각형 Polygon Properties: 다각형 속성: + Line Properties: 선 속성: + Line Length: 선 길이: + Line Angle: 선 각도: Polygon Tool 다각형 도구 Portrait 세로 Portuguese Português diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 69aef91cfc..eaa00b9095 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -2784,6 +2784,9 @@ digits Malayalam Malayalam Flip Horizontal Horizontaal spiegelen Flip Vertical Verticaal spiegelen Polygon Properties: Veelhoekeigenschappen: + Line Properties: Lijneigenschappen: + Line Length: Lijnlengte: + Line Angle: Lijnhoek: Rectangle Properties: Rechthoekeigenschappen: Shape Properties: Vormeigenschappen: Shape Properties Vormeigenschappen diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 0147515ffe..c6bfa4eb43 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -2338,6 +2338,9 @@ digits Malayalam Malajalam Flip Horizontal Odbij w poziomie Flip Vertical Odbij w pionie Polygon Properties: Właściwości wielokąta: + Line Properties: Właściwości linii: + Line Length: Długość linii: + Line Angle: Kąt linii: Rectangle Properties: Właściwości prostokąta: Shape Properties: Właściwości kształtu: Shape Properties Właściwości kształtu diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 8201db7ab6..2ab59241bc 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -2222,6 +2222,9 @@ antiAlias Sharp Nítido Polar Grid Tool Ferramenta Grade Polar Polygon Polígono Polygon Properties: Propriedades do Polígono: + Line Properties: Propriedades da Linha: + Line Length: Comprimento da Linha: + Line Angle: Ângulo da Linha: Polygon Tool Ferramenta Polígono Portrait Retrato Portuguese Português diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index d1593508d3..1257d5005a 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -2715,6 +2715,9 @@ diagnostics ui интерфейс Polar Grid Tool Инструмент «Полярная сетка» Polygon Многоугольник Polygon Properties: Свойства многоугольника: + Line Properties: Свойства линии: + Line Length: Длина линии: + Line Angle: Угол линии: Polygon Tool Инструмент «Многоугольник» Portrait Книжная Power Saving (integrated) Энергосбережение (встроенная) diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 5c0420fcd3..2f7e492645 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -2619,6 +2619,9 @@ font-technology Variable Variabla Polar Grid Tool Verktyg för polärt rutnät Polygon Polygon Polygon Properties: Polygonegenskaper: + Line Properties: Linjeegenskaper: + Line Length: Linjelängd: + Line Angle: Linjevinkel: Polygon Tool Polygonverktyg Portrait Stående Power Saving (integrated) Energisparläge (integrerad) diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 910a7fc5b1..eabb4d5e1b 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -2460,6 +2460,9 @@ shape Open Açık Polar Grid Tool Yuvarlak Izgara Aracı Polygon Çokgen Polygon Properties: Poligon Özellikleri: + Line Properties: Çizgi Özellikleri: + Line Length: Çizgi Uzunluğu: + Line Angle: Çizgi Açısı: Polygon Tool Çokgen Aracı Portrait Portre Power Saving (integrated) Güç Tasarrufu (entegre) diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index dbd6d2609e..50513ba8cc 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -2720,6 +2720,9 @@ diagnostics ui інтерфейс Polar Grid Tool Інструмент «Полярна сітка» Polygon Багатокутник Polygon Properties: Властивості багатокутника: + Line Properties: Властивості лінії: + Line Length: Довжина лінії: + Line Angle: Кут лінії: Polygon Tool Інструмент «Багатокутник» Portrait Книжкова Power Saving (integrated) Енергозбереження (вбудована) diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 519c5d8f0d..50fd75dcb5 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -3039,6 +3039,9 @@ diagnostics ui giao diện Polar Grid Tool Công cụ Lưới cực Polygon Đa giác Polygon Properties: Thuộc tính đa giác: + Line Properties: Thuộc tính đường thẳng: + Line Length: Độ dài đường thẳng: + Line Angle: Góc đường thẳng: Polygon Tool Công cụ Đa giác Portrait Đứng Portuguese Tiếng Bồ Đào Nha diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index c6696a9ec6..552524fbfc 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -2581,6 +2581,9 @@ diagnostics ui 界面 Polar Grid Tool 极坐标网格工具 Polygon 多边形 Polygon Properties: 多边形属性: + Line Properties: 直线属性: + Line Length: 直线长度: + Line Angle: 直线角度: Polygon Tool 多边形工具 Portrait 纵向 Portuguese 葡萄牙语 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 1480422931..648a781543 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -3860,6 +3860,9 @@ diagnostics ui 介面 Polar Grid Tool 極座標格點工具 Polygon 多邊形 Polygon Properties: 多邊形內容: + Line Properties: 直線內容: + Line Length: 直線長度: + Line Angle: 直線角度: Polygon Tool 多邊形工具 Portrait 直向 Power Saving (integrated) 節能 (內建顯示晶片) diff --git a/crates/ui-egui/src/panels/transform.rs b/crates/ui-egui/src/panels/transform.rs index 1bce03c53d..6145d34de3 100644 --- a/crates/ui-egui/src/panels/transform.rs +++ b/crates/ui-egui/src/panels/transform.rs @@ -416,10 +416,11 @@ fn pixel_aligned_ids(app: &VectorcraftApp) -> Vec<u64> { app.session.active().map(|st| st.selection.objects.iter().filter(|id| st.doc.node(**id).is_some()).map(|id| id.0).collect()).unwrap_or_default() } -/// A live rectangle's, polygon's or ellipse's properties (Transform and Properties panels, and the -/// Contextual Task Bar), their widget ids under `id`. `headed` adds the Rectangle and Polygon -/// Properties headings; an ellipse's heading always shows. Returns false, drawing nothing, for -/// other live shapes. +/// A live rectangle's, polygon's, ellipse's or line's properties (Transform and Properties panels, +/// and for the first three the Contextual Task Bar), their widget ids under `id`. `headed` adds +/// the Rectangle and Polygon Properties headings; an ellipse's and a line's heading always show. +/// Returns false, drawing nothing, for other live shapes, and for a line unless every selected +/// object is one. pub(crate) fn live_shape_rows(app: &mut VectorcraftApp, ui: &mut Ui, n: &Node, live: &LiveShape, id: &str, headed: bool) -> bool { match live { LiveShape::Rectangle { .. } => { @@ -438,11 +439,51 @@ pub(crate) fn live_shape_rows(app: &mut VectorcraftApp, ui: &mut Ui, n: &Node, l widgets::subheader(ui, tl!("Ellipse Properties:")); pie_rows(app, ui, *pie, &format!("{id}-pie")); } + LiveShape::Line { .. } => return line_rows(app, ui, live, &format!("{id}-line")), _ => return false, } true } +/// Whether every selected object is a live line (and one is selected). +fn only_lines_selected(app: &VectorcraftApp) -> bool { + let Some(st) = app.session.active() else { return false }; + let line = |n: &Node| matches!(&n.kind, NodeKind::Path { live: Some(l), .. } if matches!(**l, LiveShape::Line { .. })); + !st.selection.objects.is_empty() && st.selection.objects.iter().all(|o| st.doc.node(*o).is_some_and(line)) +} + +/// A live line's Line Properties (Transform and Properties panels), under its heading: its length, +/// end to end, and its angle (counterclockwise from 3 o'clock, from its first end to its second). A new length keeps each selected line's first end in place, and a +/// new angle turns each one about its midpoint. Returns false, drawing nothing, unless every +/// selected object is a live line. +pub(crate) fn line_rows(app: &mut VectorcraftApp, ui: &mut Ui, live: &LiveShape, id: &str) -> bool { + if !only_lines_selected(app) { + return false; + } + let (units, fw) = (app.session.general_unit(), super::field_width(ui)); + widgets::subheader(ui, tl!("Line Properties:")); + // The `object.setLiveShape` param an edited field sets. + let mut set = None; + egui::Grid::new((id, "grid")).num_columns(2).spacing([6.0, 6.0]).show(ui, |ui| { + widgets::dim_label(ui, tl!("Line Length:")); + if let Some(l) = widgets::num_field_named(ui, (id, "length"), Some(tl!("Line Length:")), live.line_length(), units, fw) { + set = Some(("lineLength", json!(l))); + } + ui.end_row(); + widgets::dim_label(ui, tl!("Line Angle:")); + if let Some(a) = widgets::plain_field_named(ui, (id, "angle"), Some(tl!("Line Angle:")), live.line_angle().unwrap_or(0.0), "°", 1, fw) { + set = Some(("lineAngle", json!(a))); + } + ui.end_row(); + }); + if let Some((key, v)) = set + && let Err(e) = app.run("object.setLiveShape", json!({ key: v })) + { + app.status(e); + } + true +} + /// An ellipse's Pie Start and End Angle (degrees, counterclockwise from 3 o'clock; 0 to 360 is the /// whole ellipse) and Invert Pie, which shows the other part of it (Transform and Properties panels). pub(crate) fn pie_rows(app: &mut VectorcraftApp, ui: &mut Ui, pie: (f64, f64), id: &str) { diff --git a/crates/ui-egui/src/panels/transform/tests.rs b/crates/ui-egui/src/panels/transform/tests.rs index 3dff8e6a4b..24f471b479 100644 --- a/crates/ui-egui/src/panels/transform/tests.rs +++ b/crates/ui-egui/src/panels/transform/tests.rs @@ -125,6 +125,52 @@ fn an_ellipse_shows_its_pie_properties() { assert!(shown.iter().any(|s| s == "30°") && shown.iter().any(|s| s == "120°"), "{shown:?}"); } +/// A live line shows its Line Properties in the Transform panel and the Properties panel's +/// Transform section: a typed length keeps its first end in place and a typed angle turns it +/// about its midpoint, each one undo step. A line with other objects selected, and a line after +/// Expand Shape, show none. +#[test] +fn a_line_shows_and_takes_its_line_properties() { + let ends = |app: &VectorcraftApp| match &first_selected(app).unwrap().kind { + NodeKind::Path { live: Some(l), .. } => match **l { + LiveShape::Line { a, b } => (a, b), + ref k => panic!("{k:?}"), + }, + k => panic!("{k:?}"), + }; + let near = |p: Point, x: f64, y: f64| (p.x - x).abs() < 1e-6 && (p.y - y).abs() < 1e-6; + for draw in [show as fn(&mut VectorcraftApp, &mut Ui), crate::panels::properties::transform_section] { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); + // 100 pt long, going down the page to the right: 53.13° clockwise, 306.87° counterclockwise. + let id = app.run("shape.line", json!({"x1": 50, "y1": 50, "x2": 110, "y2": 130})).unwrap()["id"].as_u64().unwrap(); + let shown = texts(&mut app, draw); + for t in ["Line Properties:", "Line Length:", "100 pt", "Line Angle:", "306.9°"] { + assert!(shown.iter().any(|s| s == t), "{t} in {shown:?}"); + } + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + type_into(&ctx, &mut app, draw, "100 pt", "50"); + let (a, b) = ends(&app); + assert!(near(a, 50.0, 50.0) && near(b, 80.0, 90.0), "{a:?} {b:?}"); + type_into(&ctx, &mut app, draw, "306.9°", "90"); + let (a, b) = ends(&app); + assert!(near(a, 65.0, 95.0) && near(b, 65.0, 45.0), "{a:?} {b:?}"); + assert!(texts(&mut app, draw).iter().any(|s| s == "90°")); + app.run("edit.undo", json!({})).unwrap(); + let (a, b) = ends(&app); + assert!(near(a, 50.0, 50.0) && near(b, 80.0, 90.0), "one undo step: {a:?} {b:?}"); + // With a rectangle selected too, the fields would set the line alone: they don't show. + let rect = app.run("shape.rectangle", json!({"x": 200, "y": 200, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [id, rect]})).unwrap(); + assert!(!texts(&mut app, draw).iter().any(|s| s == "Line Properties:" || s == "Line Length:")); + app.run("select.set", json!({"ids": [id]})).unwrap(); + assert!(texts(&mut app, draw).iter().any(|s| s == "Line Properties:")); + app.run("object.expandShape", json!({})).unwrap(); + assert!(!texts(&mut app, draw).iter().any(|s| s == "Line Properties:" || s == "Line Length:")); + } +} + #[test] fn the_artboard_tool_shows_the_active_artboard() { let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); diff --git a/docs/mcp.md b/docs/mcp.md index 092faabc4c..d78ae1c856 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -6467,7 +6467,12 @@ polygon (Polygon Properties): `sides` (3–1000), `polygonAngle` (degrees counte at 0), `polygonRadius` (pt, centre to vertex), `sideLength` (pt, which sets the radius) and `makeSidesEqual: true`, which drops an uneven scale or shear (its sides then differ) and keeps its centre, angle and mean radius; a radius or length that isn't a number above 0 is an error. An ellipse (Ellipse Properties): `pieStart` and `pieEnd` (degrees -counterclockwise from 3 o'clock; 0 to 360 is the whole ellipse) and `invertPie: true`, which swaps them. Each call is +counterclockwise from 3 o'clock; 0 to 360 is the whole ellipse) and `invertPie: true`, which swaps them. A line drawn +with the Line Segment tool (Line Properties): `lineLength` (pt, above 0; the line's first end stays in place) and +`lineAngle` (degrees counterclockwise from 3 o'clock, from the first end to the second; the line turns about its +midpoint; any finite value is brought into 0 to 360). With both, the length applies first. A line whose ends meet reads +0° and keeps its place under `lineAngle`; `lineLength` points it to the right. A length that isn't a number above 0, +and a line that would reach past the coordinate limit (±4,000,000 pt), are errors that change no line. Each call is one undo step. `object.setLiveShape` returns a parameter error, and leaves the document and its undo history as they were, for a key @@ -6480,6 +6485,7 @@ below 3 or above 1000 counts as 3 or 1000, and a fractional or negative `sides` ```json {"name":"run_command","arguments":{"command":"object.setLiveShape","params":{"sides":8,"polygonAngle":22.5,"sideLength":40}}} {"name":"run_command","arguments":{"command":"object.setLiveShape","params":{"makeSidesEqual":true}}} +{"name":"run_command","arguments":{"command":"object.setLiveShape","params":{"lineLength":72,"lineAngle":90}}} ``` ## Align to Artboard diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index e9fc9a6820..83842e33ef 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1250,6 +1250,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Shapes:** all shape tools (including Flare) and the line, arc, spiral and grid tools. Space held while dragging out a shape, line, arc, spiral or grid moves it at its current size. The Flare tool's center drag turns the rays by 0.1 radian at each drag update in which the pointer's document y grows, and back by as much at each one in which it falls, Shift held keeps their turn, and Space held during either of its drags moves the flare. While a grid is dragged out, Up/Down change its rows (concentric dividers) and Left/Right its columns (radial dividers). A click with a grid tool asks for the size, the divider counts and the grid options (#1377, in part): a skew for each set of dividers, Use Outside Rectangle As Frame or Create Compound Path From Ellipses, and Fill Grid; they are parameters of `shape.rectangularGrid` and `shape.polarGrid`, stay as the tool's options and apply to drags too. The curve a skew percentage follows and the direction of the radial skew are our own (the public documentation gives neither), and the dialogs have no reference point locator. An ellipse's Pie Start and End Angle and Invert Pie (Transform and Properties panels' Ellipse Properties, `object.setLiveShape {pieStart, pieEnd, invertPie}`) cut it as a pie (#812). With the bounding box showing, the Selection tool shows a selected ellipse's two pie widgets just outside it; dragging one sets its angle in one undo step and double-clicking one makes the ellipse whole again. A live polygon's Polygon Properties there: side count, angle, corner type and radius, radius, side length and Make Sides Equal once an uneven scale has made its sides differ (`object.setLiveShape {sides, polygonAngle, polygonRadius, sideLength, makeSidesEqual}`, part of #812); a star is a plain path, as in Illustrator. The Flare Tool Options last as the tool's options: the next flare dragged out uses them, a click's dialog shows them and double-clicking the tool opens them (part of #812). - **Shapes:** all shape tools (including Flare) and the line, arc, spiral and grid tools. Space held while dragging out a shape, line, arc, spiral or grid moves it at its current size. The Flare tool's center drag turns the rays with the pointer, Shift keeps them in their original orientation (unturned, or turned by a nonzero General › Constrain Angle), and Space held during either of its drags moves the flare. While a grid is dragged out, Up/Down change its rows (concentric dividers) and Left/Right its columns (radial dividers). A click with a grid tool asks for the size, the divider counts and the grid options (#1377, in part): a skew for each set of dividers, Use Outside Rectangle As Frame or Create Compound Path From Ellipses, and Fill Grid; they are parameters of `shape.rectangularGrid` and `shape.polarGrid`, stay as the tool's options and apply to drags too. The curve a skew percentage follows and the direction of the radial skew are our own (the public documentation gives neither), and the dialogs have no reference point locator. An ellipse's Pie Start and End Angle and Invert Pie (Transform and Properties panels' Ellipse Properties, `object.setLiveShape {pieStart, pieEnd, invertPie}`) cut it as a pie (#812). With the bounding box showing, the Selection tool shows a selected ellipse's two pie widgets just outside it; dragging one sets its angle in one undo step and double-clicking one makes the ellipse whole again. A live polygon's Polygon Properties there: side count, angle, corner type and radius, radius, side length and Make Sides Equal once an uneven scale has made its sides differ (`object.setLiveShape {sides, polygonAngle, polygonRadius, sideLength, makeSidesEqual}`, part of #812); a star is a plain path, as in Illustrator. The Flare Tool Options last as the tool's options: the next flare dragged out uses them, a click's dialog shows them and double-clicking the tool opens them (part of #812). - **Shapes:** all shape tools (including Flare) and the line, arc, spiral and grid tools. Space held while dragging out a shape, line, arc, spiral or grid moves it at its current size. The Flare tool's center drag turns the rays with the pointer, Shift keeps them in their original orientation, and Space held during either of its drags moves the flare. While a grid is dragged out, Up/Down change its rows (concentric dividers) and Left/Right its columns (radial dividers). A click with a grid tool asks for the size, the divider counts and the grid options (#1377, in part): a skew for each set of dividers, Use Outside Rectangle As Frame or Create Compound Path From Ellipses, and Fill Grid; they are parameters of `shape.rectangularGrid` and `shape.polarGrid`, stay as the tool's options and apply to drags too. The curve a skew percentage follows and the direction of the radial skew are our own (the public documentation gives neither), and the dialogs have no reference point locator. An ellipse's Pie Start and End Angle and Invert Pie (Transform and Properties panels' Ellipse Properties, `object.setLiveShape {pieStart, pieEnd, invertPie}`) cut it as a pie (#812). With the bounding box showing, the Selection tool shows a selected ellipse's two pie widgets just outside it; dragging one sets its angle in one undo step and double-clicking one makes the ellipse whole again. A live polygon's Polygon Properties there: side count, angle, corner type and radius, radius, side length and Make Sides Equal once an uneven scale has made its sides differ (`object.setLiveShape {sides, polygonAngle, polygonRadius, sideLength, makeSidesEqual}`, part of #812); a star is a plain path, as in Illustrator. The Flare Tool Options last as the tool's options: the next flare dragged out uses them, a click's dialog shows them and double-clicking the tool opens them (part of #812). + A live line drawn with the Line Segment tool shows Line Properties in the Transform panel and the Properties panel's Transform section: Line Length (a length above 0, in the document's units) and Line Angle (0° horizontal, 90° vertical, any value brought into 0° to 360°), the two properties that [the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/live-shape-properties.html) lists for a line (`object.setLiveShape {lineLength, lineAngle}`). Typing one sets every selected line in one undo step. These rules are VectorCraft's own: the angle runs counterclockwise from 3 o'clock, as the Rotate field does; a new length keeps the line's first end in place and a new angle turns it about its midpoint; a line whose ends meet reads 0°; the section shows only while every selected object is a live line; and a line that would reach past the document's coordinate limit is an error that changes nothing. Expand Shape makes the line a plain path without these properties (tests `a_line_shows_and_takes_its_line_properties` and, through the engine, `a_line_takes_its_length_and_angle`). Backtick (`` ` ``) held while a rectangle, rounded rectangle, ellipse, polygon, star or line is dragged out leaves copies of the shape being drawn along the drag, each its own object: the continuous duplicate that the Keys for drawing table of [the help page](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=469) lists. Each copy is the shape as the drag showed it then, with its modifiers and Up/Down counts; the release keeps the copies and the last shape as one undo step, and Escape takes them all back. The spacing (a copy each time the pointer has moved 8 screen points with the key down, none for the key alone) and the limit of 128 copies a drag are VectorCraft's own values, and a shape with no width, height or length leaves no copy. The arc, spiral, grid and Flare tools do not leave copies (tests `backtick_drag_leaves_copies_of_the_rectangle_being_drawn` and, through the engine, `a_backtick_drag_leaves_copies_of_the_shape_as_one_undo_step`). Escape while a polygon, star or rounded rectangle is dragged out cancels it and puts back the side count, point count, corner radius or star ratio its Up/Down and Ctrl/Cmd changed, so the next drag, the tool's options and General › Corner Radius start from the values before the canceled drag; a drag that is let go keeps them, and an option set with `tool.setOption` during the drag stays. This is VectorCraft's own rule. A click with the Rounded Rectangle tool opens the size dialog with its radius at General › Corner Radius, and OK makes the radius typed there that preference, so later rounded rectangles and the dialog's next opening start from it while rounded rectangles already drawn keep their corners, as [the help page](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=64) describes. A radius outside the preference's range of 0 to 1296 pt, which is VectorCraft's own, or one that is not a length is refused with an error: the dialog stays open, nothing is drawn and the preference keeps its value. Evidence: `dialogs::shapes::tests::{rounded_rectangle_click_dialog_opens_on_and_sets_the_corner_radius, rounded_rectangle_click_dialog_refuses_a_radius_out_of_range}`. From 57601ec0a4b8f816b4c673d8322eebcde9a6a1d0 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 17 Nov 2026 09:57:58 -0800 Subject: [PATCH 106/176] .ai import: pattern fills in brush art turn over with the art A Scatter or Art brush's art is read turned over, and the tiles of its pattern fills now turn over with it, so they keep their place on the art. The version 7 pattern test reads a Scatter brush's tile moves in the file's own space (y up), as the art now is. --- crates/eps/src/import/ai/brush.rs | 9 ++++--- crates/eps/src/import/ai/tests.rs | 44 ++++++++++++++++++++++++++++--- 2 files changed, 45 insertions(+), 8 deletions(-) diff --git a/crates/eps/src/import/ai/brush.rs b/crates/eps/src/import/ai/brush.rs index 23982759a0..4d6d00deea 100644 --- a/crates/eps/src/import/ai/brush.rs +++ b/crates/eps/src/import/ai/brush.rs @@ -63,7 +63,7 @@ use std::sync::Arc; use kurbo::Affine; use vectorcraft_brush::{ArtBrush, ArtScale, Bristle, Brush, BrushKind, Calligraphic, Colorization, Scatter, Variation}; use vectorcraft_color::Paint; -use vectorcraft_doc::{AppearanceItem, Node, NodeKind}; +use vectorcraft_doc::{AppearanceItem, Node, NodeKind, Scaling}; use super::lex::{Lexer, Tok}; use super::obj::Names; @@ -475,10 +475,11 @@ pub(super) fn parse_tool_object(kind: Tool, name: &str, params: &str) -> Result< Ok(BrushDraft { name: name.to_string(), kind }) } -/// Turn `art` over (y for -y) with the art of all its opacity masks, those that don't move with -/// their objects too: the art changes the space it is in, and no object moves over its mask. +/// Turn `art` over (y for -y) with its pattern fills' tiles and the art of all its opacity masks, +/// those that don't move with their objects too: the art changes the space it is in, and no object +/// moves over its tiles or its mask. pub(crate) fn turn_over(art: &mut Node) { - art.transform(Affine::scale_non_uniform(1.0, -1.0), false); + art.transform(Affine::scale_non_uniform(1.0, -1.0), Scaling { patterns: true, ..Scaling::default() }); turn_unlinked_masks(art); } diff --git a/crates/eps/src/import/ai/tests.rs b/crates/eps/src/import/ai/tests.rs index 9fb3153d8b..d4ba306c98 100644 --- a/crates/eps/src/import/ai/tests.rs +++ b/crates/eps/src/import/ai/tests.rs @@ -10397,11 +10397,11 @@ fn a_brushs_art_places_a_version_7_patterns_tiles_with_its_operands() { }; let plain = placed("0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0]"); // The operands and the move they make from the plain placement (a b c d e f): those of - // `a_pattern_fill_applies_its_offset_scale_rotation_reflection_and_shear` with y down, as the - // art's space has it. + // `a_pattern_fill_applies_its_offset_scale_rotation_reflection_and_shear` in the file's own + // space (y up), since a Scatter brush's art is turned over with its tiles. let cases = [ - ("10 15 1 1 0 0 0 0 0 [1 0 0 1 0 0]", [1.0, 0.0, 0.0, 1.0, 10.0, -15.0]), - ("-5 7 2 .5 -45 0 0 -15 45 [1 0 0 1 0 0]", [1.793151, 0.353553, -1.035276, 0.353553, -5.0, -7.0]), + ("10 15 1 1 0 0 0 0 0 [1 0 0 1 0 0]", [1.0, 0.0, 0.0, 1.0, 10.0, 15.0]), + ("-5 7 2 .5 -45 0 0 -15 45 [1 0 0 1 0 0]", [1.793151, -0.353553, 1.035276, 0.353553, -5.0, 7.0]), ]; for (ops, want) in cases { let got = (placed(ops) * plain.inverse()).as_coeffs(); @@ -11300,6 +11300,42 @@ fn a_scatter_brushs_copies_are_its_art_turned_over() { assert!(filled(&up, 2.0, 55.0) && !filled(&up, 2.0, 25.0), "the narrow block is right of it, at the copy's bottom"); } +/// A pattern fill in a Scatter or Art brush's art is turned over with the art: the tiles keep their +/// place on the art. The section fills a 40 by 8 rectangle with an 8-point tile placed with the +/// identity, so the tile's top left is at the rectangle's top left in the section (y up). +#[test] +fn a_pattern_fill_in_brush_art_turns_over_with_the_art() { + let still = "2 /Tiled art/ 5 1 0 0 / 0 1 1 0 1 1 0 0 0 0 0 0 0 0 0"; + let ribbon = "2 / Tiled art/ / / / / 0 0/ 5 0 0 0 / 1 1 1 0 1 0 0 0 1 1 0 0 0 0 1"; + let section = format!( + "%AI8_BeginBrushPattern\n(Tiled art)\n0 A\n(Dots) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p\n{}f\n%AI8_EndBrushPattern\n", + rect_path(0.0, 0.0, 40.0, 8.0) + ); + let def = format!("{DOTS}{section}{}{}", plugin_object(SCATTER, "Spray", still), plugin_object(ART_BRUSH, "Ribbon", ribbon)); + let r = read_ok(&format!("{def}{}", layer(&(rect_path(0.0, 0.0, 10.0, 10.0) + "f\n")))); + let lib = vectorcraft_brush::library(&r.doc); + for name in ["Spray", "Ribbon"] { + let b = lib.iter().find(|b| b.name == name).unwrap_or_else(|| panic!("{name}: {lib:?}")); + let art = match &b.kind { + vectorcraft_brush::BrushKind::Scatter(s) => &s.art, + vectorcraft_brush::BrushKind::Art(a) => &a.art, + k => panic!("{name}: {k:?}"), + }; + let mut found = None; + art.walk(&mut |n| { + if let (Some(_), Paint::Pattern { xf, .. }) = (n.path_data(), fill(n)) { + found = Some((n.geometric_bounds(), xf)); + } + }); + let Some((Some(bounds), xf)) = found else { panic!("{name}: {art:#?}") }; + // The art is turned over (y up again): the tile's top left (0, 0) and its dot (4, 4), in + // the tile's space with y down, are at the rectangle's top left and 4 below it. + assert_eq!(bounds, Rect::new(0.0, 0.0, 40.0, 8.0), "{name}"); + assert!((xf * Point::ZERO - Point::new(0.0, bounds.y1)).hypot() < 1e-9, "{name}: {xf:?}"); + assert!((xf * Point::new(4.0, 4.0) - Point::new(4.0, bounds.y1 - 4.0)).hypot() < 1e-9, "{name}: {xf:?}"); + } +} + use read::{GRAPH_PLAIN, GRAPH_UNENDED}; use vectorcraft_doc::{GraphKind, TickLength}; From f9e639919561b85bb4d886eb8f41460038df543e Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 17 Nov 2026 09:58:54 -0800 Subject: [PATCH 107/176] Layers: with Show Layers Only on, Locate Object becomes Locate Layer With Panel Options > Show Layers Only on, the panel lists no object rows, so Locate Object highlighted a row that was not there. The panel menu, the bottom bar's button and a row's menu now read Locate Layer in that mode and send layer.locate with layersOnly: true, which highlights the innermost layer or sublayer holding the object (a layer locates itself) and returns {id, objectId, ancestry}. The panel opens the layers around it and scrolls to it. With the option off nothing changes. Help page: https://helpx.adobe.com/illustrator/desktop/manage-layers/create-and-organize-layers/locate-objects-in-the-layers-panel.html Adds Locate Layer rows to the 28 catalogs that translate Locate Object. --- crates/engine/src/cmd/layerpanel.rs | 16 +++++-- crates/engine/src/tests/layers.rs | 25 +++++++++++ crates/ui-egui/src/i18n/bg.tsv | 1 + crates/ui-egui/src/i18n/bs.tsv | 1 + crates/ui-egui/src/i18n/ca.tsv | 1 + crates/ui-egui/src/i18n/cs.tsv | 1 + crates/ui-egui/src/i18n/da.tsv | 1 + crates/ui-egui/src/i18n/de.tsv | 1 + crates/ui-egui/src/i18n/el.tsv | 1 + crates/ui-egui/src/i18n/es.tsv | 1 + crates/ui-egui/src/i18n/fi.tsv | 1 + crates/ui-egui/src/i18n/fr.tsv | 1 + crates/ui-egui/src/i18n/gu.tsv | 1 + crates/ui-egui/src/i18n/hi.tsv | 1 + crates/ui-egui/src/i18n/hu.tsv | 1 + crates/ui-egui/src/i18n/id.tsv | 1 + crates/ui-egui/src/i18n/it.tsv | 1 + crates/ui-egui/src/i18n/ja.tsv | 1 + crates/ui-egui/src/i18n/ka.tsv | 1 + crates/ui-egui/src/i18n/ko.tsv | 1 + crates/ui-egui/src/i18n/nl.tsv | 1 + crates/ui-egui/src/i18n/pl.tsv | 1 + crates/ui-egui/src/i18n/pt-br.tsv | 1 + crates/ui-egui/src/i18n/ru.tsv | 1 + crates/ui-egui/src/i18n/sv.tsv | 1 + crates/ui-egui/src/i18n/tr.tsv | 1 + crates/ui-egui/src/i18n/uk.tsv | 1 + crates/ui-egui/src/i18n/vi.tsv | 1 + crates/ui-egui/src/i18n/zh-hans.tsv | 1 + crates/ui-egui/src/i18n/zh-hant.tsv | 1 + crates/ui-egui/src/panels/layers/controls.rs | 14 +++++-- crates/ui-egui/src/panels/layers/rows.rs | 7 ++-- crates/ui-egui/src/panels/layers/tests.rs | 44 ++++++++++++++++++++ docs/mcp.md | 4 +- docs/target-app-parity.md | 1 + 35 files changed, 128 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/cmd/layerpanel.rs b/crates/engine/src/cmd/layerpanel.rs index 95c152e959..4710966004 100644 --- a/crates/engine/src/cmd/layerpanel.rs +++ b/crates/engine/src/cmd/layerpanel.rs @@ -132,7 +132,7 @@ pub fn specs() -> Vec<CommandSpec> { "Locate Object", ["Window", "Layers"], None, - "{id?} (default: the last selected object) highlight the object's row; the Layers panel opens the layers around it and scrolls to it → {id, ancestry: [layer…, id]}", + "{id?, layersOnly?} (default: the last selected object) highlight the object's row; the Layers panel opens the layers around it and scrolls to it → {id, ancestry: [layer…, id]}. layersOnly (default false; the panel sends true while Show Layers Only is on, as Locate Layer) highlights the innermost layer or sublayer holding the object instead, or a layer id itself → {id: layer, objectId, ancestry: [layer…]}", has_doc, locate ), @@ -435,10 +435,18 @@ fn reverse(s: &mut Session, p: &Value) -> Result<Value> { fn locate(s: &mut Session, p: &Value) -> Result<Value> { let id = object_param(p, "id", "layer.locate")?; + let layers_only = switch_or(p, "layersOnly", false, "layer.locate")?; let st = s.doc_mut()?; let id = id.or_else(|| st.selection.objects.last().copied()).ok_or_else(|| bad("layer.locate", "nothing selected"))?; - let ancestry = st.doc.ancestry(id).ok_or(EngineError::NoNode(id))?; - st.layer_rows = vec![id]; + let mut ancestry = st.doc.ancestry(id).ok_or(EngineError::NoNode(id))?; + if layers_only { + // Locate Layer: the innermost layer or sublayer holding the object (a layer locates itself). + let at = ancestry.iter().rposition(|a| st.doc.node(*a).is_some_and(Node::is_layer)).ok_or(EngineError::NoNode(id))?; + ancestry.truncate(at + 1); + } + let row = ancestry.last().copied().ok_or(EngineError::NoNode(id))?; + st.layer_rows = vec![row]; st.revision += 1; - Ok(json!({ "id": id.0, "ancestry": ancestry.iter().map(|i| i.0).collect::<Vec<_>>() })) + let ancestry: Vec<u64> = ancestry.iter().map(|i| i.0).collect(); + Ok(if layers_only { json!({ "id": row.0, "objectId": id.0, "ancestry": ancestry }) } else { json!({ "id": id.0, "ancestry": ancestry }) }) } diff --git a/crates/engine/src/tests/layers.rs b/crates/engine/src/tests/layers.rs index f6b35716f6..186c5de6c1 100644 --- a/crates/engine/src/tests/layers.rs +++ b/crates/engine/src/tests/layers.rs @@ -904,6 +904,31 @@ fn locate_object_highlights_its_row() { assert!(s.execute("layer.locate", &json!({})).is_err()); } +/// Locate Layer (`layersOnly`, sent while Show Layers Only is on) highlights the innermost layer +/// or sublayer holding the object, through any groups; a layer locates itself. +#[test] +fn locate_layer_highlights_the_layer_holding_the_object() { + let mut s = session(); + let (layer, sub, _, g, b, c) = tree(&mut s); + run(&mut s, "select.set", json!({"ids": [b.0]})); + let r = run(&mut s, "layer.locate", json!({"layersOnly": true})); + assert_eq!(r, json!({"id": sub.0, "objectId": b.0, "ancestry": [layer.0, sub.0]}), "the group's sublayer"); + assert_eq!(s.doc().unwrap().highlighted_rows(), vec![sub]); + assert_eq!(run(&mut s, "layer.locate", json!({"id": c.0, "layersOnly": true}))["id"], layer.0, "art directly in a layer"); + assert_eq!(s.doc().unwrap().highlighted_rows(), vec![layer]); + let r = run(&mut s, "layer.locate", json!({"id": sub.0, "layersOnly": true})); + assert_eq!((r["id"].clone(), r["objectId"].clone()), (json!(sub.0), json!(sub.0)), "a sublayer locates itself"); + // Off, the object's own row is highlighted, as before. + assert_eq!(run(&mut s, "layer.locate", json!({"id": g.0, "layersOnly": false})), json!({"id": g.0, "ancestry": [layer.0, sub.0, g.0]})); + // Bad input changes nothing. + for p in [json!({"id": b.0, "layersOnly": "yes"}), json!({"id": 999_999, "layersOnly": true})] { + assert!(s.execute("layer.locate", &p).is_err(), "{p}"); + assert_eq!(s.doc().unwrap().highlighted_rows(), vec![g], "{p}"); + } + run(&mut s, "select.none", json!({})); + assert!(s.execute("layer.locate", &json!({"layersOnly": true})).is_err(), "nothing selected"); +} + #[test] fn the_clipping_mask_button_acts_on_the_highlighted_group() { let mut s = session(); diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index bb039bb08e..e625b302c6 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -1949,6 +1949,7 @@ font-technology Variable Променливи Load SVG into Clipboard Зареждане на SVG в клипборда Load Text into Clipboard Зареждане на текст в клипборда Local Libraries Локални библиотеки + Locate Layer Намиране на слой Locate Object Намиране на обект Locate Selected Objects Намиране на избраните обекти Location Местоположение diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 99f23d313c..32f7271ed5 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -3711,6 +3711,7 @@ theme Appearance Izgled Select Art Odaberi crtež Set Current Layer Postavi trenutni sloj Flatten Artwork Spljošti crtež + Locate Layer Pronađi sloj Locate Object Pronađi objekat Lock Others Zaključaj ostale Merge Selected Spoji odabrano diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index c54311799d..5f03892a52 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -2543,6 +2543,7 @@ digits Malayalam Malaiàlam Loads native code Carrega codi natiu Local Libraries Biblioteques locals Locate Library… Localitza la biblioteca… + Locate Layer Localitza la capa Locate Object Localitza l’objecte Locate Selected Objects Localitza els objectes seleccionats Location Ubicació diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index a5d7bb948a..b629145983 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -3813,6 +3813,7 @@ theme Appearance Motiv Select Art Vybrat kresbu Set Current Layer Nastavit aktuální vrstvu Flatten Artwork Sloučit kresbu + Locate Layer Najít vrstvu Locate Object Najít objekt Lock Others Zamknout ostatní Merge Selected Sloučit vybrané diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 08100f593f..255ae36f88 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -6235,6 +6235,7 @@ theme Appearance Udseende Select Art Markér grafik Set Current Layer Angiv aktuelt lag Flatten Artwork Fladgør grafik + Locate Layer Lokalisér lag Locate Object Lokalisér objekt Lock Others Lås andre Merge Selected Flet valgte diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 10147b2d45..ed50c44208 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -2031,6 +2031,7 @@ file-filter Templates Vorlagen Load SVG into Clipboard SVG in die Zwischenablage laden Load Text into Clipboard Text in die Zwischenablage laden Local Libraries Lokale Bibliotheken + Locate Layer Ebene ausfindig machen Locate Object Objekt ausfindig machen Locate Selected Objects Ausgewählte Objekte ausfindig machen Location Speicherort diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 1ebf6e5684..b7d86dfb18 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -3110,6 +3110,7 @@ theme Appearance Εμφάνιση Load SVG into Clipboard Φόρτωση SVG στο πρόχειρο Load Text into Clipboard Φόρτωση κειμένου στο πρόχειρο Local Libraries Τοπικές βιβλιοθήκες + Locate Layer Εντοπισμός επιπέδου Locate Object Εντοπισμός αντικειμένου Locate Selected Objects Εντοπισμός επιλεγμένων αντικειμένων Lock (⌘2) Κλείδωμα (⌘2) diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index a456910a16..3aba4e61ed 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -2030,6 +2030,7 @@ font-technology Variable Variables Load SVG into Clipboard Cargar SVG en el portapapeles Load Text into Clipboard Cargar texto en el portapapeles Local Libraries Bibliotecas locales + Locate Layer Localizar capa Locate Object Localizar objeto Locate Selected Objects Localizar objetos seleccionados Location Ubicación diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index bff46fc0d7..5149789c78 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -3751,6 +3751,7 @@ theme Appearance Ulkoasu Select Art Valitse kuvitus Set Current Layer Aseta nykyinen taso Flatten Artwork Litistä kuvitus + Locate Layer Paikanna taso Locate Object Paikanna objekti Lock Others Lukitse muut Merge Selected Yhdistä valitut diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 3be3497f97..f42072dadb 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -2020,6 +2020,7 @@ font-technology Variable Variables Load SVG into Clipboard Charger un SVG dans le presse-papiers Load Text into Clipboard Charger du texte dans le presse-papiers Local Libraries Bibliothèques locales + Locate Layer Localiser le calque Locate Object Localiser l’objet Locate Selected Objects Localiser les objets sélectionnés Location Emplacement diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index c427fc527c..a69a49f9ac 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -2093,6 +2093,7 @@ Loads native code નેટિવ કોડ લોડ કરે છે Local Libraries સ્થાનિક લાઇબ્રેરીઓ Locate Library… લાઇબ્રેરી શોધો… + Locate Layer લેયર શોધો Locate Object ઑબ્જેક્ટ શોધો Locate Selected Objects પસંદ કરેલા ઑબ્જેક્ટ શોધો Location સ્થાન diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index cbfb4f51d1..ffb48ddfc6 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -2787,6 +2787,7 @@ antiAlias Sharp शार्प Loads native code मूल कोड लोड करता है Local Libraries स्थानीय लाइब्रेरी Locate Library… लाइब्रेरी… + Locate Layer लेयर का पता लगाएं Locate Object ऑब्जेक्ट का पता लगाएं Locate Selected Objects सिलेक्टेड ऑब्जेक्ट्स का पता लगाएँ Location स्थान diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 0f81a72036..37712b280d 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -2531,6 +2531,7 @@ file-filter Templates Sablonok Load Texture… Textúra betöltése… Loaded Texture Betöltött textúra Local Libraries Helyi könyvtárak + Locate Layer Réteg megkeresése Locate Object Objektum megkeresése Locate Selected Objects Kijelölt objektumok megkeresése Location Hely diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 28ea2b5ab3..ed76ff00c3 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -3487,6 +3487,7 @@ theme Appearance Tampilan Select Art Pilih karya seni Set Current Layer Tetapkan lapisan saat ini Flatten Artwork Ratakan karya seni + Locate Layer Temukan lapisan Locate Object Temukan objek Lock Others Kunci lainnya Merge Selected Gabungkan terpilih diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 8f2ed3216c..d72b30e4a4 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -2068,6 +2068,7 @@ file-filter Templates Modelli Load SVG into Clipboard Carica SVG negli appunti Load Text into Clipboard Carica testo negli appunti Local Libraries Librerie locali + Locate Layer Individua livello Locate Object Individua oggetto Locate Selected Objects Individua oggetti selezionati Location Posizione diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index c429f204a1..d6f9f834d2 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -2333,6 +2333,7 @@ antiAlias Sharp シャープ Load SVG into Clipboard SVG をクリップボードに読み込む Load Text into Clipboard テキストをクリップボードに読み込む Local Libraries ローカルライブラリ + Locate Layer レイヤーを検索 Locate Object オブジェクトを検索 Locate Selected Objects 選択したオブジェクトを検索 Location 場所 diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 414f45171c..e45e8adadf 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -5580,6 +5580,7 @@ theme Appearance იერსახე Select Art ნახატის მონიშვნა Set Current Layer მიმდინარე შრედ დაყენება Flatten Artwork ნახატის გაბრტყელება + Locate Layer შრის მოძებნა Locate Object ობიექტის მოძებნა Lock Others დანარჩენების ჩაკეტვა Merge Selected მონიშნულების შერწყმა diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index dbda53243f..e13b9b726e 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -2323,6 +2323,7 @@ antiAlias Sharp 날카롭게 Load SVG into Clipboard SVG를 클립보드로 불러오기 Load Text into Clipboard 텍스트를 클립보드로 불러오기 Local Libraries 로컬 라이브러리 + Locate Layer 레이어 찾기 Locate Object 개체 찾기 Locate Selected Objects 선택한 개체 찾기 Location 위치 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 69aef91cfc..0b7f641859 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -4109,6 +4109,7 @@ theme Appearance Vormgeving Select Art Kunst selecteren Set Current Layer Huidige laag instellen Flatten Artwork Kunst afvlakken + Locate Layer Laag lokaliseren Locate Object Object lokaliseren Lock Others Overigen vergrendelen Merge Selected Selectie samenvoegen diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 0147515ffe..54c413c65f 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -3692,6 +3692,7 @@ theme Appearance Wygląd Select Art Zaznacz kompozycję Set Current Layer Ustaw bieżącą warstwę Flatten Artwork Spłaszcz kompozycję + Locate Layer Znajdź warstwę Locate Object Znajdź obiekt Lock Others Zablokuj pozostałe Merge Selected Scal zaznaczone diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 8201db7ab6..c273252eee 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -1712,6 +1712,7 @@ antiAlias Sharp Nítido Load SVG into Clipboard Carregar SVG na Área de Transferência Load Text into Clipboard Carregar Texto na Área de Transferência Local Libraries Bibliotecas Locais + Locate Layer Localizar Camada Locate Object Localizar Objeto Location Local Location: Local: diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index d1593508d3..4217fe2238 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -2057,6 +2057,7 @@ file-filter Templates Шаблоны Load SVG into Clipboard Загрузить SVG в буфер обмена Load Text into Clipboard Загрузить текст в буфер обмена Local Libraries Локальные библиотеки + Locate Layer Найти слой Locate Object Найти объект Locate Selected Objects Находить выделенные объекты Location Расположение diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 5c0420fcd3..d1f062dd3b 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -1965,6 +1965,7 @@ font-technology Variable Variabla Load SVG into Clipboard Läs in SVG till urklipp Load Text into Clipboard Läs in text till urklipp Local Libraries Lokala bibliotek + Locate Layer Hitta lager Locate Object Hitta objekt Locate Selected Objects Hitta markerade objekt Location Plats diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 910a7fc5b1..dddab221b3 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -1851,6 +1851,7 @@ font-technology Variable Değişken Load SVG into Clipboard SVG'yi Panoya yükleyin Load Text into Clipboard Metni Panoya Yükle Local Libraries Yerel Kütüphaneler + Locate Layer Katmanı Bul Locate Object Nesneyi Bul Location Konum Location: Konum: diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index dbd6d2609e..8a65ccabda 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -2062,6 +2062,7 @@ file-filter Templates Шаблони Load SVG into Clipboard Завантажити SVG у буфер обміну Load Text into Clipboard Завантажити текст у буфер обміну Local Libraries Локальні бібліотеки + Locate Layer Знайти шар Locate Object Знайти об’єкт Locate Selected Objects Знаходити виділені об’єкти Location Розташування diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 519c5d8f0d..0d166b4a70 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -2367,6 +2367,7 @@ digits Hindi Hindi Load Texture… Tải kết cấu… Loaded Texture Kết cấu đã tải Local Libraries Thư viện cục bộ + Locate Layer Xác định vị trí lớp Locate Object Xác định vị trí đối tượng Locate Selected Objects Xác định vị trí đối tượng đã chọn Location Vị trí diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index c6696a9ec6..fe93812961 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -1939,6 +1939,7 @@ file-filter Templates 模板 Load SVG into Clipboard 将 SVG 载入剪贴板 Load Text into Clipboard 将文本载入剪贴板 Local Libraries 本地库 + Locate Layer 查找图层 Locate Object 查找对象 Locate Selected Objects 查找所选对象 Location 位置 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 1480422931..c720cff2ad 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -3184,6 +3184,7 @@ liquify-list-end {0}, {1} {0}和{1} Load SVG into Clipboard 將 SVG 載入剪貼簿 Load Text into Clipboard 將文字載入剪貼簿 Local Libraries 本機資料庫 + Locate Layer 尋找圖層 Locate Object 尋找物件 Locate Selected Objects 尋找選取的物件 Location 位置 diff --git a/crates/ui-egui/src/panels/layers/controls.rs b/crates/ui-egui/src/panels/layers/controls.rs index 4cea41db75..1cde07b2c9 100644 --- a/crates/ui-egui/src/panels/layers/controls.rs +++ b/crates/ui-egui/src/panels/layers/controls.rs @@ -116,8 +116,11 @@ pub(super) fn bottom_bar(app: &mut VectorcraftApp, ui: &mut Ui, view: &View, doc if widgets::icon_button(&mut child, "frame", tl!("Make/Release Clipping Mask"), false, 24.0).clicked() { actions.push(("layer.clippingMask.toggle".into(), json!({}))); } - if widgets::icon_button(&mut child, "search", tl!("Locate Object"), false, 24.0).clicked() { - actions.push(("layer.locate".into(), json!({}))); + // With Show Layers Only on, Locate Object becomes Locate Layer: it highlights the layer row. + let layers_only = view.opts.layers_only; + let locate = if layers_only { tl!("Locate Layer") } else { tl!("Locate Object") }; + if widgets::icon_button(&mut child, "search", locate, false, 24.0).clicked() { + actions.push(("layer.locate".into(), json!({ "layersOnly": layers_only }))); } } @@ -132,6 +135,7 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { let current = st.current_layer(); let has_sel = !st.selection.is_empty(); let isolated = st.isolation.is_some(); + let layers_only = app.ui.layers_panel.layers_only; let targets: Vec<NodeId> = if rows.is_empty() { current.into_iter().collect() } else { rows.clone() }; let one_container = match targets.as_slice() { [id] => doc.node(*id).is_some_and(|n| matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. })), @@ -166,7 +170,11 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { }); items.extend([ None, - Some(("Locate Object", "layer.locate", json!({}), has_sel, false)), + Some(if layers_only { + ("Locate Layer", "layer.locate", json!({"layersOnly": true}), has_sel, false) + } else { + ("Locate Object", "layer.locate", json!({}), has_sel, false) + }), // Sentinel: rendered as the Save Selection submenu (the Select menu's saved-selection items). Some(("Save Selection", "", json!({}), true, false)), None, diff --git a/crates/ui-egui/src/panels/layers/rows.rs b/crates/ui-egui/src/panels/layers/rows.rs index 62e32f1097..36cae8e9b8 100644 --- a/crates/ui-egui/src/panels/layers/rows.rs +++ b/crates/ui-egui/src/panels/layers/rows.rs @@ -510,9 +510,10 @@ fn row_context_menu(ui: &mut Ui, view: &View, n: &Node, collect_ids: &[u64], out } } ui.separator(); - // Locate Object - if widgets::menu_item(ui, "Locate Object", true, false) { - out.actions.push(("layer.locate".into(), json!({ "id": n.id.0 }))); + // Locate Object, or Locate Layer with Show Layers Only on + let layers_only = view.opts.layers_only; + if widgets::menu_item(ui, if layers_only { "Locate Layer" } else { "Locate Object" }, true, false) { + out.actions.push(("layer.locate".into(), json!({ "id": n.id.0, "layersOnly": layers_only }))); ui.close(); } ui.separator(); diff --git a/crates/ui-egui/src/panels/layers/tests.rs b/crates/ui-egui/src/panels/layers/tests.rs index 2570e77df7..11d0d70842 100644 --- a/crates/ui-egui/src/panels/layers/tests.rs +++ b/crates/ui-egui/src/panels/layers/tests.rs @@ -2133,6 +2133,50 @@ fn the_panel_menu_lists_every_operation() { } } +/// With Show Layers Only on, Locate Object becomes Locate Layer in the panel menu and a row's +/// menu, and the bottom bar's Locate button highlights the sublayer holding the selected art, +/// opening the layer around it. Off, the button highlights the art's own row. +#[test] +fn with_show_layers_only_locate_object_becomes_locate_layer() { + let (mut app, [layer, sub, _, b, _, _]) = nested(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let shown = |app: &mut VectorcraftApp, events: Vec<egui::Event>, f: fn(&mut VectorcraftApp, &mut egui::Ui)| { + super::super::tests_appearance::frame_events(&ctx, app, events, f).into_iter().map(|(t, _)| t.trim().to_string()).collect::<Vec<_>>() + }; + let has = |texts: &[String], s: &str| texts.iter().any(|t| t == s); + app.session.execute("select.set", &json!({"ids": [b.0]})).unwrap(); + let off = shown(&mut app, vec![], menu); + assert!(has(&off, "Locate Object") && !has(&off, "Locate Layer"), "{off:?}"); + let locate = |app: &mut VectorcraftApp| { + let at = bar_buttons(app, &ctx)[4]; + click_with(app, &ctx, at, egui::Modifiers::NONE); + }; + locate(&mut app); + assert_eq!(rows_of(&app), vec![b], "off: the art's own row"); + + app.ui.layers_panel.layers_only = true; + let on = shown(&mut app, vec![], menu); + assert!(has(&on, "Locate Layer") && !has(&on, "Locate Object"), "{on:?}"); + app.session.active_mut().unwrap().layers_open.set(layer, false); + shown(&mut app, vec![], show); + locate(&mut app); + assert_eq!(rows_of(&app), vec![sub], "on: the sublayer holding the art"); + shown(&mut app, vec![], show); + assert!(app.session.active().unwrap().layers_open.contains(layer), "the layer around the sublayer opens"); + assert!(has(&shown(&mut app, vec![], show), "Sub"), "the sublayer's row shows"); + + // A row's menu says Locate Layer too. + let c = frame(&mut app, &ctx, vec![], false).0; + let at = egui::pos2(150.0, c[0].y); + let right = egui::PointerButton::Secondary; + for e in [egui::Event::PointerMoved(at), button_by(at, true, right), button_by(at, false, right)] { + frame(&mut app, &ctx, vec![e], false); + } + let row_menu = shown(&mut app, vec![], show); + assert!(has(&row_menu, "Locate Layer") && !has(&row_menu, "Locate Object"), "{row_menu:?}"); +} + /// ≡ › Save Selection lists the saved selections: choosing one recalls it, Update Selection /// makes it hold the selected objects, and Save Selection… opens the name dialog. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 092faabc4c..b719d3352e 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5413,7 +5413,9 @@ and `layerRows`, the rows highlighted in the panel. locked or nested art included, dialog `confirm` asks "Delete this layer and its artwork?" for one layer, else "Delete the selected items and their artwork?"; OK deletes the rows it asked about in that document, one undo step, and Cancel keeps them; an empty layer, a layer with only guides, and groups or objects alone are deleted at once), - `layer.locate {id?}` (highlights the selected object's row; the panel opens the rows around it) + `layer.locate {id?, layersOnly?}` (highlights the selected object's row; the panel opens the rows around it; + `layersOnly: true`, which the panel sends while Show Layers Only is on, as Locate Layer, highlights the innermost + layer or sublayer holding the object instead, or a layer `id` itself, and returns `{id, objectId, ancestry}`) and `layer.clippingMask.toggle`. - **Panel menu**: `layer.duplicate {ids?}`, `layer.merge {ids?}` (into the layer highlighted last, keeping the stacking order), `layer.flatten {id?}` (every other visible layer's art into one layer; hidden layers are deleted, diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index e9fc9a6820..6bae94488f 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1386,6 +1386,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Layer Options for several highlighted rows shows the first row's settings, and OK changes only the settings set in the dialog: each row keeps its own color, Template, Lock, Show, Print, Preview and Dim Images otherwise (`crates/ui-egui/src/dialogs/layer_options.rs` tests). As VectorCraft's own rule, a layer color (`layer.setProps`, `layer.new`, `layer.newSublayer`) or a Live Paint Gap Preview Color (`livePaint.gapOptions`) given as a hex color with an alpha part (`#rrggbbaa` or `#rgba`) is an error and changes nothing, instead of being set without its alpha. Regression tests: `a_layer_color_with_an_alpha_part_is_refused` in `crates/engine/src/tests/layers.rs` and `a_gap_color_with_an_alpha_part_is_refused` in `crates/engine/src/tests/build.rs`. Panel Options › Locate Selected Objects (beyond Illustrator, off by default): when the last selected object changes on the canvas or by a command, the panel opens the layers and groups around it and scrolls to its row, as Locate Object does, without highlighting the row; when Show Layers Only, a search or the filter leaves the object without a row, the panel opens no rows for it and scrolls as with the option off. + With Panel Options › Show Layers Only on, Locate Object is named Locate Layer and highlights the layer that holds the selected object instead of the object's own row, which that mode does not list (help page: https://helpx.adobe.com/illustrator/desktop/manage-layers/create-and-organize-layers/locate-objects-in-the-layers-panel.html). As VectorCraft's own rules, the bottom bar's button and a row's menu are renamed too, the innermost sublayer holding the object is the one highlighted, a layer row locates itself, and the panel opens the layers around it (`locate_layer_highlights_the_layer_holding_the_object` in `crates/engine/src/tests/layers.rs`, `with_show_layers_only_locate_object_becomes_locate_layer` in `crates/ui-egui/src/panels/layers/tests.rs`). - **Drawing aids:** Smart Guides and snapping (moving, with the Selection, Group Selection or Direct Selection tool, and resizing by the bounding-box handles with the Selection or Free Transform tool, Shift and Alt too: the dragged corner or side lands on the other objects' anchors and centres ("anchor", "center") or lines up with their edges and centres (a line and "align"); with Smart Guides › Spacing Guides, a moved selection that lines up with nothing along an axis lands as far from its neighbour as two other objects of its row or column are apart, or halfway between its two neighbours, the equal gaps marked; with View › Snap to Grid on, a moved selection lands on the grid instead, by whichever of its edges is nearest a gridline on each axis (the center does not snap), #740, #1816; the Rotate, Scale, Shear and Reflect tools drag from the anchor they grab and snap the pointer the same way, so a corner dragged onto another object's anchor scales exactly onto it, #482; anchors dragged with Direct Selection: the one pressed on lands on other anchors, its own path's that stay put among them, on path segments or in line with them, the others following, Shift keeps 45° steps, and with Smart Guides off Snap to Point pulls it onto anchors; the Artboard tool snaps artboards, and their bleed, to other artboards, bleeds and art, the grid or whole pixels while moving, copying and resizing them, and the Transform panel shows and edits the active artboard's X/Y/W/H; drawn points, #506: hovering shows where the press goes, the point lands on the other objects' anchors, centres and paths ("anchor", "center", "path") or lines up with their anchors, edges and centres ("align"), the Pen's on the path being drawn too, near a construction guide through the anchor before it on that guide (Preferences › Smart Guides › Construction Guides and Angles), and with Shift kept to its 45° step or a square's diagonal it slides along that way into line; the targets are gathered once per document state, from the art in the window, and the anchors, centres and lines near the pointer are found by bisection, so hovering never rescans the document), guides dragged out of the rulers (#451: they snap as moved guides do, Shift to the ruler's ticks; with the Artboard tool they are artboard guides, which run across their artboard only and move, copy and delete with it, `guide.add {artboard}`) that the Selection, Direct Selection and Group Selection tools then pick and drag (#414: the selected guides highlight and move together, Alt copies them, Shift snaps the dragged one to the ticks, otherwise it snaps to pixels, the grid or the edges, centres (so the sides' midpoints) and anchors of the art and the artboards, or with Smart Guides off Snap to Point pulls it onto anchors; Shift-clicked they join the selected art, and Shift-added art keeps them, so guides and art are selected together in either order, Delete then deleting both in one step; the arrow keys nudge them, Delete deletes them, dragging one back onto its ruler deletes it, Lock Guides and Hide Guides leave them alone; `guide.list`, `guide.select`, `guide.move` and `guide.remove` reach agents), a right-click on either ruler or the origin box to pick the document's units (the current one checked; `document.setUnits`, one undo step, #528), and Draw Normal / Behind / Inside modes. Smart Guides: a point drawn with the Pen or a shape tool, and an anchor dragged with Direct Selection, snaps to where paths and ruler guides cross, labelled "intersect" (#1658, part of #1602; a moved selection's own anchors don't, except the anchor the Selection tool grabbed it by). A selection the Selection tool grabs by one of its anchors snaps that anchor onto the other objects' paths ("path"), and where a path crosses another path or a ruler guide ("intersect"), in the order Direct Selection uses for a dragged anchor; when the anchor lands on a path, the selection's bounds do not also line up with other objects (#7411). The archived 2007 [user guide](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=55) (page 49) says Smart Guides align the pointer of a moved object to existing paths. Snapping onto paths only when the selection was grabbed by an anchor is VectorCraft's own rule; a selection grabbed anywhere else still lines its bounds up. Tests: `select::tests::a_move_grabbed_by_an_anchor_lands_it_on_another_path`, `a_move_grabbed_by_an_anchor_lands_it_where_paths_cross` and `a_move_grabbed_by_an_anchor_lands_it_where_a_path_crosses_a_ruler_guide`. With Smart Guides › Measurement Labels on, the Line Segment tool labels the segment being drawn with its distance, angle and X and Y offsets (`D`, `Angle`, `dX`, `dY`), and the Pen, Curvature and Smart Pen tools label their rubber band the same way when Enable Rubber Band is on (#2983). A move that Shift keeps level, upright or diagonal stays on that line when it snaps, with the Selection, Group Selection or Direct Selection tool. It slides along the line until the selection lands on the grid or on whole pixels, lines up with the other objects or is spaced evenly with them, or until the line passes an anchor or crosses a ruler guide near the point the selection was grabbed by. A level or upright move snaps along its own axis only. Snap to Last Location: with Smart Guides on and Preferences › Smart Guides › Snap to Last Location on (off by default, VectorCraft's own choice), a selection moved by dragging with the Selection, Group Selection or Direct Selection tool, Shift too, goes back to where the move began while it is within Snapping Tolerance of it, labeled "last location"; an Alt copy is not pulled back onto its original, and with View › Snap to Grid or Snap to Pixel on the move snaps to the grid or to whole pixels instead (`prefs.set` key `snapToLastLocation`). The public [Smart Guides options](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/smart-guides-options.html) page lists the option as snapping objects back to their previous position; the distance, the label, the copy rule and the grid and pixel rule are VectorCraft's own. Tests: `select::tests::snap_to_last_location_puts_a_move_back_where_it_began`, `select::tests::snap_to_pixel_wins_over_snap_to_last_location`, `direct::tests::snap_to_last_location_puts_a_path_moved_by_its_anchor_back`, `direct::tests::snap_to_pixel_wins_over_snap_to_last_location_for_a_path_moved_by_its_anchor`, `tests_prefs::snap_to_last_location_puts_a_dragged_square_back`. From 24e0208d314622564e56729e253b8b848f5115ef Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 17 Nov 2026 10:08:24 -0800 Subject: [PATCH 108/176] Type: inline graphics are checked again only in the layer trees an edit changed After an edit of a document with symbols, the refresh of inline graphics walked every node of every layer. It now keeps the document the last refresh left resolved, with the symbol bounds it measured, and checks only the layer trees that are not the same nodes as that document's, as long as the symbols, graph designs, pattern tiles and foreign data (which holds the symbols' natural sizes and 9-slice guides) are the same and each measured symbol still measures the same. Otherwise the full pass runs, as before. Visit order is unchanged, so the document and the ids of the texts laid out again equal the full pass's. --- crates/doc/src/inline.rs | 228 ++++++++++++++++++++++++++-- crates/doc/src/lib.rs | 2 +- crates/engine/src/cmd/inline.rs | 31 +++- crates/engine/src/doc_state.rs | 5 + crates/engine/src/session/edit.rs | 9 +- crates/engine/src/tests/inline.rs | 239 ++++++++++++++++++++++++++++++ docs/target-app-parity.md | 1 + 7 files changed, 497 insertions(+), 18 deletions(-) diff --git a/crates/doc/src/inline.rs b/crates/doc/src/inline.rs index 86c26e14f4..b22f6cbfc7 100644 --- a/crates/doc/src/inline.rs +++ b/crates/doc/src/inline.rs @@ -117,6 +117,29 @@ impl Document { /// symbol that shows itself inline ([`Self::inline_art_bounds`]) is shown as an empty slot. /// Returns the ids of the texts in the layers that changed. pub fn resolve_inline_art_with(&mut self, layout: &mut dyn FnMut(&mut TextObject)) -> Vec<NodeId> { + self.resolve_inline_art_since(None, layout).changed + } + + /// [`Self::resolve_inline_art_with`], given `last`: a document an earlier pass left resolved, + /// with the bounds that pass measured ([`InlinePass::measured`]). When this document has the + /// same symbols, graph designs, pattern tiles and foreign data (`unknown`, which holds the + /// symbols' natural sizes and 9-slice guides) as `last`, and each symbol name measured then + /// still measures the same, the type in the layer trees that are the same nodes as `last`'s + /// already has these bounds: only the other layer trees are checked, in the same order, and + /// the document and the ids returned are those of the full pass. Otherwise, or without `last`, + /// the full pass runs. + pub fn resolve_inline_art_since(&mut self, last: Option<(&Document, &InlineMeasured)>, layout: &mut dyn FnMut(&mut TextObject)) -> InlinePass { + if let Some((last, kept)) = last + && self.same_inline_inputs(last, kept) + { + let measured = Measured(RefCell::new(kept.0.clone())); + let mut changed = vec![]; + let layers = resolve_kids(Some(&last.layers), &self.layers, &|n| measured.get(n, || self.inline_art_bounds(n)), layout, &mut changed); + for (i, layer) in layers { + self.layers[i] = layer; + } + return InlinePass { changed, measured: InlineMeasured(measured.0.into_inner()), partial: true }; + } let mut out = vec![]; let mut unused = vec![]; let graph = InlineGraph::of(self); @@ -147,10 +170,44 @@ impl Document { } } } - out + InlinePass { changed: out, measured: InlineMeasured(measured.0.into_inner()), partial: false } + } + + /// Whether the type in this document's layer trees that are the same nodes as `last`'s already + /// has the bounds a full pass would give it (see [`Self::resolve_inline_art_since`]). + fn same_inline_inputs(&self, last: &Document, kept: &InlineMeasured) -> bool { + self.symbols.len() == last.symbols.len() + && self.symbols.iter().zip(&last.symbols).all(|(a, b)| a.name == b.name && Arc::ptr_eq(&a.art, &b.art)) + && self.graph_designs.len() == last.graph_designs.len() + && self.graph_designs.iter().zip(&last.graph_designs).all(|(a, b)| a.name == b.name && Arc::ptr_eq(&a.art, &b.art)) + && self.patterns.len() == last.patterns.len() + && self + .patterns + .iter() + .zip(&last.patterns) + .all(|(a, b)| a.name == b.name && a.art.len() == b.art.len() && a.art.iter().zip(&b.art).all(|(x, y)| Arc::ptr_eq(x, y))) + && crate::Shared::ptr_eq(&self.unknown, &last.unknown) + && kept.0.iter().all(|(name, b)| self.inline_art_bounds(name) == *b) } } +/// What a pass of [`Document::resolve_inline_art_since`] did. +#[derive(Debug)] +pub struct InlinePass { + /// The ids of the texts in the layers that changed, in the order the full pass finds them. + pub changed: Vec<NodeId>, + /// The bounds the pass gave the inline graphics of each symbol name, for the next pass. + pub measured: InlineMeasured, + /// Whether only the layer trees that differ from the last resolved document's were checked. + pub partial: bool, +} + +/// The art bounds a pass of [`Document::resolve_inline_art_since`] gave the inline graphics of each +/// symbol name it was asked for. A pass that checks only some layer trees keeps the names the +/// pass before it measured, so the names of all the type in the document stay listed. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct InlineMeasured(HashMap<String, Option<Rect>>); + /// Whether `t` has inline graphics whose bounds differ from what `bounds` gives their symbols. fn stale_by(t: &TextObject, bounds: &dyn Fn(&str) -> Option<Rect>) -> bool { t.runs.iter().filter_map(|r| r.inline.as_ref()).any(|a| a.bounds != bounds(&a.symbol)) @@ -185,6 +242,22 @@ fn resolve_tree( layout: &mut dyn FnMut(&mut TextObject), changed: &mut Vec<NodeId>, ) -> bool { + resolve_since(None, n, bounds, layout, changed) +} + +/// [`resolve_tree`], given `old`: the node `n` was before an edit, in a document whose type was +/// resolved with the same `bounds`. The opacity mask art and children of `n` that are the same +/// nodes as `old`'s are skipped: their type already has these bounds. Without `old`, every node +/// of the tree is visited. +fn resolve_since( + old: Option<&Node>, + n: &mut Arc<Node>, + bounds: &dyn Fn(&str) -> Option<Rect>, + layout: &mut dyn FnMut(&mut TextObject), + changed: &mut Vec<NodeId>, +) -> bool { + #[cfg(test)] + tests::VISITS.with(|v| v.set(v.get() + 1)); let mut copied = false; if matches!(&n.kind, NodeKind::Text(t) if stale_by(t, bounds)) { let node = Arc::make_mut(n); @@ -196,17 +269,17 @@ fn resolve_tree( } copied = true; } + let old_mask = old.and_then(|o| o.extras().mask.as_deref()).map(|m| &m.art); let mask = n.extras().mask.as_deref().and_then(|m| { - let mut art = m.art.clone(); - resolve_tree(&mut art, bounds, layout, changed).then_some(art) - }); - let mut kids = vec![]; - for (i, c) in n.children().into_iter().flatten().enumerate() { - let mut c = c.clone(); - if resolve_tree(&mut c, bounds, layout, changed) { - kids.push((i, c)); + if old_mask.is_some_and(|o| Arc::ptr_eq(o, &m.art)) { + return None; } - } + let mut art = m.art.clone(); + let old_art = old_mask.filter(|o| o.id == art.id).map(|o| &**o); + resolve_since(old_art, &mut art, bounds, layout, changed).then_some(art) + }); + let old_kids = old.map(|o| o.children().map_or(&[][..], Vec::as_slice)); + let kids = resolve_kids(old_kids, n.children().map_or(&[][..], Vec::as_slice), bounds, layout, changed); if mask.is_none() && kids.is_empty() { return copied; } @@ -224,6 +297,35 @@ fn resolve_tree( true } +/// Resolves the trees `kids` as [`resolve_since`] does, each with the node of `old` (the same list +/// before an edit) that has its id, found at the same position or else by id, and skips those that +/// are the same nodes as theirs. Without `old`, every tree is visited. Returns the position and new +/// node of each tree that changed. +fn resolve_kids( + old: Option<&[Arc<Node>]>, + kids: &[Arc<Node>], + bounds: &dyn Fn(&str) -> Option<Rect>, + layout: &mut dyn FnMut(&mut TextObject), + changed: &mut Vec<NodeId>, +) -> Vec<(usize, Arc<Node>)> { + let mut by_id: Option<HashMap<NodeId, &Arc<Node>>> = None; + let mut out = vec![]; + for (i, c) in kids.iter().enumerate() { + let o = old.and_then(|old| match old.get(i) { + Some(b) if b.id == c.id => Some(b), + _ => by_id.get_or_insert_with(|| old.iter().map(|b| (b.id, b)).collect()).get(&c.id).copied(), + }); + if o.is_some_and(|o| Arc::ptr_eq(o, c)) { + continue; + } + let mut c = c.clone(); + if resolve_since(o.map(|o| &**o), &mut c, bounds, layout, changed) { + out.push((i, c)); + } + } + out +} + /// The art bounds of each symbol, measured once in a pass of [`Document::resolve_inline_art_with`]. /// A symbol is first asked for after its own type is resolved (the pass goes in /// [`InlineGraph::order`]), so its measurement stays current for the rest of the pass. @@ -436,6 +538,112 @@ impl std::fmt::Debug for InlineCycles { mod tests { use super::*; + thread_local! { + /// How many nodes [`resolve_since`] has visited on this thread. + pub(super) static VISITS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; + } + + /// The nodes visited since the last call. + fn visits() -> usize { + VISITS.with(|v| v.replace(0)) + } + + /// A copy of `d` resolved by the full pass, and the ids that pass returns. + fn fully_resolved(d: &Document) -> (Document, Vec<NodeId>) { + let mut full = d.clone(); + let ids = full.resolve_inline_art_with(&mut |_| {}); + (full, ids) + } + + /// The children of the layer at `i`, for an edit. + fn layer_kids(d: &mut Document, i: usize) -> &mut Vec<Arc<Node>> { + match Arc::make_mut(&mut d.layers[i]).children_mut() { + Some(kids) => kids, + None => panic!("layer {i} is a group"), + } + } + + /// 50 groups of 20 squares, symbol `S`, type showing `S` in the first group, and type showing + /// `S` in the opacity mask of the second. + fn many_groups() -> Document { + let mut d = Document::new(500.0, 500.0); + let square = stroked(&mut d, Rect::new(0.0, 0.0, 10.0, 10.0)); + symbol(&mut d, "S", vec![square]); + for _ in 0..50 { + let kids = (0..20).map(|_| stroked(&mut d, Rect::new(0.0, 0.0, 5.0, 5.0))).collect(); + let group = Node::group(d.alloc_id(), kids); + d.layers.push(Arc::new(group)); + } + let t = showing(&mut d, "S"); + layer_kids(&mut d, 0).push(t); + let masked = showing(&mut d, "S"); + Arc::make_mut(&mut d.layers[1]).extras_mut().mask = Some(Box::new(crate::OpacityMask::new((*masked).clone(), true))); + d + } + + #[test] + fn a_pass_after_an_edit_checks_only_the_trees_the_edit_changed() { + let mut d = many_groups(); + let first = d.resolve_inline_art_since(None, &mut |_| {}); + assert!(!first.partial); + assert_eq!(first.changed.len(), 2); + let last = d.clone(); + visits(); + let _ = fully_resolved(&d); + let full_visits = visits(); + // The edit moves a square in the 31st group, adds type showing S to the 41st, and gives the + // second group's opacity mask new type: its 20 squares stay the same nodes. + let moved = stroked(&mut d, Rect::new(1.0, 1.0, 6.0, 6.0)); + layer_kids(&mut d, 30)[5] = moved; + let added = showing(&mut d, "S"); + layer_kids(&mut d, 40).push(added.clone()); + let mask_type = showing(&mut d, "S"); + if let Some(m) = Arc::make_mut(&mut d.layers[1]).extras_if_any().and_then(|e| e.mask.as_deref_mut()) { + m.art = mask_type.clone(); + } + let (want, ids) = fully_resolved(&d); + assert_eq!(ids, [mask_type.id, added.id]); + visits(); + let pass = d.resolve_inline_art_since(Some((&last, &first.measured)), &mut |_| {}); + let partial_visits = visits(); + assert!(pass.partial); + assert_eq!(pass.changed, ids); + assert_eq!(d, want); + // The three changed groups, the mask's new type, the moved square and the added type. + assert_eq!(partial_visits, 6); + assert!(full_visits > 1000, "{full_visits}"); + assert_eq!(pass.measured, first.measured); + } + + #[test] + fn changed_symbols_or_symbol_sizes_take_the_full_pass() { + let mut d = many_groups(); + let mut pass = d.resolve_inline_art_since(None, &mut |_| {}); + // A natural size for S, its art unchanged. + let last = d.clone(); + d.unknown.insert(SYMBOL_SIZES.into(), serde_json::json!({ "S": [40.0, 20.0] })); + let (want, ids) = fully_resolved(&d); + assert_eq!(ids.len(), 2); + pass = d.resolve_inline_art_since(Some((&last, &pass.measured)), &mut |_| {}); + assert!(!pass.partial); + assert_eq!((&d, &pass.changed), (&want, &ids)); + // New art for S. + let last = d.clone(); + let bigger = stroked(&mut d, Rect::new(0.0, 0.0, 30.0, 30.0)); + d.symbols[0].art = Arc::new(Node::group(d.alloc_id(), vec![bigger])); + let (want, ids) = fully_resolved(&d); + assert_eq!(ids.len(), 2); + pass = d.resolve_inline_art_since(Some((&last, &pass.measured)), &mut |_| {}); + assert!(!pass.partial); + assert_eq!((&d, &pass.changed), (&want, &ids)); + // A measurement that no longer holds, with the same symbols and foreign data. + let last = d.clone(); + let stale = InlineMeasured(HashMap::from([("S".to_owned(), Some(Rect::new(0.0, 0.0, 1.0, 1.0)))])); + pass = d.resolve_inline_art_since(Some((&last, &stale)), &mut |_| {}); + assert!(!pass.partial); + assert!(pass.changed.is_empty()); + } + /// The position of each node in `order`. fn positions(order: &[usize]) -> Vec<usize> { let mut at = vec![0; order.len()]; diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 11711b3f1d..cbb783efdd 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -31,7 +31,7 @@ mod symbol_nine_slice; pub mod symbol_overrides; mod symbol_pixel_aligned; mod symbol_registration; -pub use inline::{SYMBOL_HALF, SYMBOL_SIZES}; +pub use inline::{InlineMeasured, InlinePass, SYMBOL_HALF, SYMBOL_SIZES}; pub use shared::Shared; pub use symbol_export_type::{SYMBOL_EXPORT_TYPE, SymbolExportType}; pub use symbol_nine_slice::{ diff --git a/crates/engine/src/cmd/inline.rs b/crates/engine/src/cmd/inline.rs index d2df2ada51..cb516465ff 100644 --- a/crates/engine/src/cmd/inline.rs +++ b/crates/engine/src/cmd/inline.rs @@ -3,7 +3,7 @@ use serde_json::{Value, json}; use vectorcraft_doc::text::INLINE_MAX_SCALE; -use vectorcraft_doc::{Document, InlineArt, NodeId, NodeKind, TextRun}; +use vectorcraft_doc::{Document, InlineArt, InlineMeasured, NodeId, NodeKind, TextRun}; use vectorcraft_text::edit; use super::brushsym::current_symbol; @@ -25,12 +25,33 @@ pub fn specs() -> Vec<CommandSpec> { /// Inline graphics follow their symbols: after an edit of a document that has (or had) symbols, /// resolve the inline art of every text again, in the layers and in the art of symbols, graph /// designs, pattern tiles and opacity masks, and lay out again the texts whose art changed (a -/// symbol's type before the type that shows that symbol inline). -pub(crate) fn refresh(before: &Document, d: &mut Document) { +/// symbol's type before the type that shows that symbol inline). `last` is the document the last +/// refresh left resolved, with what it measured: when nothing the inline art depends on changed +/// since, only the layer trees that differ from its own are checked +/// ([`Document::resolve_inline_art_since`]). Returns what this refresh measured, or `None` when +/// neither document has symbols and nothing was checked. +pub(crate) fn refresh(last: Option<&Resolved>, before: &Document, d: &mut Document) -> Option<InlineMeasured> { if before.symbols.is_empty() && d.symbols.is_empty() { - return; + return None; } - d.resolve_inline_art_with(&mut refresh_bounds); + #[cfg(test)] + let last = last.filter(|_| !FULL_PASS.get()); + let pass = d.resolve_inline_art_since(last.map(|(doc, m)| (&**doc, m)), &mut refresh_bounds); + #[cfg(test)] + PASSES.with(|p| p.borrow_mut().push((pass.partial, pass.changed.clone()))); + Some(pass.measured) +} + +/// A document a [`refresh`] left resolved, and what that refresh measured. +pub(crate) type Resolved = (std::sync::Arc<Document>, InlineMeasured); + +#[cfg(test)] +thread_local! { + /// Each [`refresh`] on this thread that checked the document: whether it checked only the + /// changed layer trees, and the ids of the texts in the layers that changed. + pub(crate) static PASSES: std::cell::RefCell<Vec<(bool, Vec<NodeId>)>> = const { std::cell::RefCell::new(vec![]) }; + /// Set: every [`refresh`] on this thread takes the full pass. + pub(crate) static FULL_PASS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) }; } fn insert_inline(s: &mut Session, p: &Value) -> Result<Value> { diff --git a/crates/engine/src/doc_state.rs b/crates/engine/src/doc_state.rs index 9cbdfb6827..f6f383fe5b 100644 --- a/crates/engine/src/doc_state.rs +++ b/crates/engine/src/doc_state.rs @@ -136,6 +136,10 @@ pub struct DocState { /// same document comes to the front, its type set in them is not measured again. While this /// reference lasts, its allocation holds no other document. Not saved. pub(crate) measured_in_own: Option<(std::sync::Weak<Document>, std::collections::HashSet<String>)>, + /// The document as the last edit's refresh of inline graphics left it, and what that refresh + /// measured: the next refresh checks only the layer trees that differ from it + /// ([`cmd::inline::refresh`]). Not saved. + pub(crate) inline_resolved: Option<cmd::inline::Resolved>, } /// Whether a document has an artboard for Delete Empty Artboards to delete, with the document that @@ -355,6 +359,7 @@ impl DocState { plugin_effects: Default::default(), art_to_fit: Default::default(), measured_in_own: None, + inline_resolved: None, } } /// `measure`'s answer for the document now. `measure` runs once for each version of the document, diff --git a/crates/engine/src/session/edit.rs b/crates/engine/src/session/edit.rs index 4f47b325b9..4e840c9364 100644 --- a/crates/engine/src/session/edit.rs +++ b/crates/engine/src/session/edit.rs @@ -53,7 +53,8 @@ impl Session { let mut symbol_synced = if st.doc.symbol_edit.is_some() { cmd::symboledit::sync(&before, Arc::make_mut(&mut st.doc)) } else { Ok(()) }; // Inline graphics in text follow their symbols. - cmd::inline::refresh(&before, Arc::make_mut(&mut st.doc)); + let measured = cmd::inline::refresh(st.inline_resolved.as_ref(), &before, Arc::make_mut(&mut st.doc)); + let mut resolved = measured.map(|m| (st.doc.clone(), m)); // The document the passes below start from, for the symbol to follow what they // change on its editing layer. let synced = st.doc.symbol_edit.is_some().then(|| st.doc.clone()); @@ -86,7 +87,10 @@ impl Session { let new = art(&st.doc); if symbol_synced.is_ok() && !matches!((&old, &new), (Some(a), Some(b)) if Arc::ptr_eq(a, b)) { let resynced = st.doc.clone(); - cmd::inline::refresh(synced, Arc::make_mut(&mut st.doc)); + let last = resolved.as_ref().or(st.inline_resolved.as_ref()); + if let Some(m) = cmd::inline::refresh(last, synced, Arc::make_mut(&mut st.doc)) { + resolved = Some((st.doc.clone(), m)); + } if !st.doc.text_threads.is_empty() { cmd::threads::reflow(&resynced, Arc::make_mut(&mut st.doc)); } @@ -100,6 +104,7 @@ impl Session { if !st.doc.variables.bindings.is_empty() { Arc::make_mut(&mut st.doc).prune_variable_bindings(); } + st.inline_resolved = resolved; if let Err(e) = symbol_synced { Err(e) } else if st.doc.too_deep(Some(&before)) { diff --git a/crates/engine/src/tests/inline.rs b/crates/engine/src/tests/inline.rs index 71caf14bf8..e491aefc34 100644 --- a/crates/engine/src/tests/inline.rs +++ b/crates/engine/src/tests/inline.rs @@ -504,6 +504,245 @@ fn saved_documents_keep_inline_graphics() { assert_eq!(t.cached_bounds, obj(&s, id).cached_bounds); } +/// `groups` groups of `each` 5 × 5 black rectangles added to the first layer in one edit; returns +/// the ids of each group's rectangles. +fn rect_groups(s: &mut Session, groups: usize, each: usize) -> Vec<Vec<NodeId>> { + s.edit("Rectangles", |d, _| { + let look = vectorcraft_doc::Appearance::basic(Paint::solid(Color::BLACK), Paint::None, 0.0); + let mut ids = vec![]; + let mut made = vec![]; + for g in 0..groups { + let kids: Vec<Arc<Node>> = (0..each) + .map(|i| { + let r = Rect::new(i as f64 * 6.0, g as f64 * 6.0, i as f64 * 6.0 + 5.0, g as f64 * 6.0 + 5.0); + Arc::new(Node::path(d.alloc_id(), vectorcraft_geom::shapes::rectangle(r), look.clone())) + }) + .collect(); + ids.push(kids.iter().map(|k| k.id).collect()); + made.push(Arc::new(Node::group(d.alloc_id(), kids))); + } + match Arc::make_mut(&mut d.layers[0]).children_mut() { + Some(kids) => kids.extend(made), + None => panic!("the first layer holds art"), + } + Ok(ids) + }) + .unwrap() +} + +/// Runs `step` on `full`, with every refresh of inline graphics taking the full pass, then on +/// `fast`; checks that both leave the same document and that each refresh returned the same changed +/// texts. Returns whether each of `fast`'s refreshes checked only the changed layer trees. +fn same_as_full_pass(full: &mut Session, fast: &mut Session, step: &dyn Fn(&mut Session)) -> Vec<bool> { + let take = || cmd::inline::PASSES.with(|p| std::mem::take(&mut *p.borrow_mut())); + take(); + cmd::inline::FULL_PASS.set(true); + step(full); + cmd::inline::FULL_PASS.set(false); + let want = take(); + step(fast); + let got = take(); + assert_eq!(*full.doc().unwrap().doc, *fast.doc().unwrap().doc); + let ids = |passes: &[(bool, Vec<NodeId>)]| passes.iter().map(|(_, ids)| ids.clone()).collect::<Vec<_>>(); + assert_eq!(ids(&got), ids(&want)); + assert!(want.iter().all(|(partial, _)| !partial)); + got.iter().map(|(partial, _)| *partial).collect() +} + +/// After an edit, inline graphics are checked again only in the layer trees the edit changed, and +/// the document and the changed texts are those of the full pass; a change to a symbol's art, its +/// natural size or anything else a symbol is measured with checks them all. +#[test] +fn refreshing_only_changed_trees_matches_the_full_pass() { + let setup = |s: &mut Session| { + circle_symbol(s, "Tap", 10.0); + circle_symbol(s, "Dot", 6.0); + let groups = rect_groups(s, 20, 10); + let id = text(s, "Tap here"); + s.execute("text.insertInline", &json!({"id": id.0, "at": 0, "symbol": "Tap"})).unwrap(); + // Type showing Dot inline becomes the opacity mask of a rectangle. + let masked = s.execute("shape.rectangle", &json!({"x": 300, "y": 300, "width": 50, "height": 50})).unwrap()["id"].clone(); + let mask = text(s, "Dot"); + s.execute("text.insertInline", &json!({"id": mask.0, "at": 0, "symbol": "Dot"})).unwrap(); + s.execute("transparency.makeOpacityMask", &json!({"ids": [masked, mask.0]})).unwrap(); + (groups, id) + }; + let (mut full, mut fast) = (session(), session()); + let (groups, id) = setup(&mut full); + assert_eq!(setup(&mut fast), (groups.clone(), id)); + let rect = groups[3][4].0; + let len = obj(&fast, id).plain_text().len(); + let only_changed = |passes: &[bool]| !passes.is_empty() && passes.iter().all(|&p| p); + let all = |passes: &[bool]| !passes.is_empty() && passes.iter().all(|&p| !p); + + // A rectangle beside 19 unchanged groups moves. + let passes = same_as_full_pass(&mut full, &mut fast, &|s| { + s.execute("select.set", &json!({"ids": [rect]})).unwrap(); + s.execute("object.move", &json!({"dx": 5, "dy": 0})).unwrap(); + }); + assert!(only_changed(&passes), "{passes:?}"); + // Type with an inline graphic is edited, gets a second one, and loses it again. + let passes = same_as_full_pass(&mut full, &mut fast, &|s| { + s.execute("text.editRange", &json!({"id": id.0, "start": len, "end": len, "insert": "!"})).unwrap(); + s.execute("text.insertInline", &json!({"id": id.0, "at": len, "symbol": "Dot"})).unwrap(); + s.execute("text.editRange", &json!({"id": id.0, "start": len, "end": len + INLINE_CHAR.len_utf8(), "insert": ""})).unwrap(); + }); + assert!(only_changed(&passes), "{passes:?}"); + // Dot's art is redefined: the type in the opacity mask follows it. + let passes = same_as_full_pass(&mut full, &mut fast, &|s| redefine_as_wide_ellipse(s, "Dot")); + assert!(passes.contains(&false), "{passes:?}"); + // Tap's natural size changes, its art unchanged. + let passes = same_as_full_pass(&mut full, &mut fast, &|s| { + s.edit("Size", |d, _| { + d.unknown.insert(vectorcraft_doc::SYMBOL_SIZES.into(), json!({ "Tap": [40.0, 20.0] })); + Ok(()) + }) + .unwrap(); + }); + assert!(all(&passes), "{passes:?}"); + let (b, want) = (inline_bounds(&obj(&fast, id)), fast.doc().unwrap().doc.symbol_art_bounds("Tap")); + assert!(b.is_some() && b == want, "{b:?} {want:?}"); + // 9-slice guides for Tap, its art unchanged. + let passes = same_as_full_pass(&mut full, &mut fast, &|s| { + s.execute("symbol.options", &json!({"name": "Tap", "nineSlice": true})).unwrap(); + }); + assert!(all(&passes), "{passes:?}"); + // Symbol editing mode, entered and left, a rectangle moved inside it. + same_as_full_pass(&mut full, &mut fast, &|s| { + s.execute("symbol.edit", &json!({"name": "Dot"})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 4, "height": 4})).unwrap(); + s.execute("symbol.exitEditing", &json!({})).unwrap(); + }); + // Undo and redo, then edits after them. + same_as_full_pass(&mut full, &mut fast, &|s| { + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("select.set", &json!({"ids": [rect]})).unwrap(); + s.execute("object.move", &json!({"dx": 0, "dy": 5})).unwrap(); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("edit.redo", &json!({})).unwrap(); + s.execute("object.move", &json!({"dx": -5, "dy": 0})).unwrap(); + }); + // Fonts scanned again, then another move. + same_as_full_pass(&mut full, &mut fast, &|s| { + s.execute("text.rescanFonts", &json!({})).unwrap(); + s.execute("select.set", &json!({"ids": [rect]})).unwrap(); + s.execute("object.move", &json!({"dx": 1, "dy": 1})).unwrap(); + }); +} + +/// The CPU time this thread has used, from Linux's scheduler statistics; `None` elsewhere. +fn thread_cpu() -> Option<std::time::Duration> { + let stat = std::fs::read_to_string("/proc/thread-self/schedstat").ok()?; + stat.split_whitespace().next()?.parse().ok().map(std::time::Duration::from_nanos) +} + +/// The time `f` takes in milliseconds: this thread's CPU time where Linux reports it, otherwise the +/// wall clock. +fn time_ms(f: impl FnOnce()) -> f64 { + let d = match thread_cpu() { + Some(before) => { + f(); + thread_cpu().map_or(std::time::Duration::ZERO, |after| after.saturating_sub(before)) + } + None => { + let start = std::time::Instant::now(); + f(); + start.elapsed() + } + }; + d.as_secs_f64() * 1000.0 +} + +/// The median, fastest and slowest of `runs`, as text. +fn spread(runs: &mut [f64]) -> String { + runs.sort_by(f64::total_cmp); + format!("{:>9.3} ({:.3}-{:.3})", runs[runs.len() / 2], runs[0], runs[runs.len() - 1]) +} + +/// Timings of the refresh of inline graphics after one rectangle moves, with the full pass and with +/// only the changed layer trees checked, in documents of 5,000, 50,000 and 200,000 rectangles in 100 +/// groups, with three symbols and one line of type showing one of them inline: the refresh alone, +/// on copies of the same edit, and the whole `object.move` command. 7 runs each, taking turns going +/// first. Ignored by default; it prints the median, fastest and slowest run and sets no bound on +/// them: `cargo test --release -p vectorcraft-engine --lib inline_refresh_perf -- --ignored --nocapture`. +#[test] +#[ignore = "a benchmark: run with --ignored --nocapture"] +fn inline_refresh_perf() { + const RUNS: usize = 7; + eprintln!("inline_refresh_perf: {}", if thread_cpu().is_some() { "thread CPU time" } else { "wall clock" }); + eprintln!("inline_refresh_perf: {:>7} {:<14} {:>28} {:>28}", "objects", "case", "full pass ms (min-max)", "changed trees ms (min-max)"); + for n in [5_000, 50_000, 200_000] { + let mut s = session(); + for name in ["A", "B", "C"] { + circle_symbol(&mut s, name, 10.0); + } + let groups = rect_groups(&mut s, 100, n / 100); + let id = text(&mut s, "Type"); + s.execute("text.insertInline", &json!({"id": id.0, "at": 0, "symbol": "B"})).unwrap(); + let rect = groups[50][7]; + s.execute("select.set", &json!({"ids": [rect.0]})).unwrap(); + s.execute("object.move", &json!({"dx": 1, "dy": 0})).unwrap(); + // The refresh alone, after the same move made on a copy of the resolved document. + let resolved = s.doc().unwrap().inline_resolved.clone().unwrap(); + let before = resolved.0.clone(); + // The rectangle and the group and layer above it become new nodes, as a move makes them. + let mut after = (*before).clone(); + assert!(after.node_mut(rect).is_some()); + // Each run times EACH refreshes, or EACH commands, and gives the time of one. + const EACH: usize = 20; + let (mut full, mut partial) = (vec![], vec![]); + for run in 0..RUNS { + let (mut a, mut b) = (vec![after.clone(); EACH], vec![after.clone(); EACH]); + let mut go_full = || { + cmd::inline::FULL_PASS.set(true); + full.push( + time_ms(|| { + for d in &mut a { + cmd::inline::refresh(Some(&resolved), &before, d); + } + }) / EACH as f64, + ); + cmd::inline::FULL_PASS.set(false); + }; + let mut go_partial = || { + partial.push( + time_ms(|| { + for d in &mut b { + cmd::inline::refresh(Some(&resolved), &before, d); + } + }) / EACH as f64, + ); + }; + if run % 2 == 0 { + go_full(); + go_partial(); + } else { + go_partial(); + go_full(); + } + assert_eq!(a, b); + } + eprintln!("inline_refresh_perf: {n:>7} {:<14} {:>28} {:>28}", "refresh", spread(&mut full), spread(&mut partial)); + // The whole command, moving the rectangle back and forth. + let (mut full, mut partial) = (vec![], vec![]); + for run in 0..2 * RUNS { + let take_full = (run / 2) % 2 == run % 2; + cmd::inline::FULL_PASS.set(take_full); + let ms = time_ms(|| { + for i in 0..EACH { + let dx = if i % 2 == 0 { -1 } else { 1 }; + s.execute("object.move", &json!({"dx": dx, "dy": 0})).unwrap(); + } + }) / EACH as f64; + cmd::inline::FULL_PASS.set(false); + if take_full { full.push(ms) } else { partial.push(ms) } + } + eprintln!("inline_refresh_perf: {n:>7} {:<14} {:>28} {:>28}", "object.move", spread(&mut full), spread(&mut partial)); + cmd::inline::PASSES.with(|p| p.borrow_mut().clear()); + } +} + #[test] fn create_outlines_turns_inline_graphics_into_symbol_instances() { let mut s = session(); diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index e9fc9a6820..e0ea3b31fa 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1506,6 +1506,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Manual kerning on inline graphics:** a manual kerning value on an inline graphic's character spaces it from the next character in reading order by the same distance as on a letter of its run's size, in left-to-right, right-to-left and vertical type; Auto and Optical kerning still apply no font pairs to it. This is VectorCraft's own rule. Test: `manual_kerning_on_an_inline_graphic_spaces_it_like_a_letter`. - **Inline graphics in symbol art follow their symbols:** when a symbol changes, type with an inline graphic of it is laid out again wherever the type is: in the layers, in the art of other symbols, graph designs and pattern tiles, and in opacity masks. A symbol's type is laid out before the type that shows that symbol inline, so a symbol whose art holds an inline graphic, its instances and the inline graphics that show it take its new size. Opening and reverting a document and Refresh Font List resolve them in the same order. An inline graphic of a symbol whose art shows that symbol inline, directly or through other symbols, is an empty slot. This is VectorCraft's own rule. Tests: `inline_graphics_in_symbol_art_follow_their_symbol`, `inline_graphics_in_masks_and_pattern_tiles_follow_their_symbol`, `symbols_are_resolved_after_the_symbols_they_show_inline`, `a_symbol_that_shows_itself_inline_is_an_empty_slot` in `crates/engine/src/tests/inline.rs`. - **Inline graphics of symbols that hold other symbols:** an inline graphic of a symbol whose art holds an instance of another symbol is sized by that symbol's own art, placed by the instance, and follows it when that symbol changes. A symbol's type is laid out after the type in the art of the symbols its instances show. An inline graphic of a symbol whose art reaches that symbol through an instance and an inline graphic is an empty slot; an instance that does not size the art, such as one a clipping path hides, does not count. An instance of a missing symbol, of a symbol without art, of a symbol that holds an instance of itself, or of a symbol whose art nests symbols 32 deep is measured by the 20 × 20 square. This is VectorCraft's own rule. Tests: `an_inline_graphic_follows_the_art_of_a_symbol_nested_in_its_symbol`, `symbols_are_resolved_after_the_symbols_their_instances_show`, `a_symbol_that_shows_itself_through_an_instance_is_an_empty_slot` in `crates/engine/src/tests/inline.rs`; `a_symbol_nested_in_symbol_art_is_measured_by_its_own_art`, `nested_instances_without_art_of_their_own_are_measured_by_the_square`, `only_instances_that_size_a_symbols_art_make_it_depend_on_their_symbol` in `crates/doc/src/inline.rs`. +- **Inline graphics after an edit, in large documents:** after an edit, a document with symbols checks its type's inline graphics again only in the layer trees that differ from the document the last check left, as long as the symbols, graph designs, pattern tiles and the symbols' natural sizes and 9-slice guides are unchanged and each symbol the type shows measures as before; otherwise every tree is checked, as before. The document and the texts laid out again are the same either way. Measured in one process (thread CPU time, median of 7 runs, 100 groups, three symbols, one inline graphic, one rectangle moved): the check went from 1.0 ms to under 0.05 ms at 50,000 rectangles and from 5.7 ms to under 0.05 ms at 200,000, and a whole `object.move` from 1.55 ms to 0.7 ms and from 11.9 ms to 6.2 ms; the rest of an edit still walks the document. Tests: `refreshing_only_changed_trees_matches_the_full_pass` in `crates/engine/src/tests/inline.rs`; `a_pass_after_an_edit_checks_only_the_trees_the_edit_changed`, `changed_symbols_or_symbol_sizes_take_the_full_pass` in `crates/doc/src/inline.rs`; timings: `inline_refresh_perf` (ignored). - **Recent font pickers (#3515):** The shared Character, Properties, Glyphs and Find Font family picker lists recently applied families first, once each, in most-recent order and limited by Preferences › Type › Number of Recent Fonts. Search and filters apply to both sections; unavailable families are omitted. Section headings cannot be selected or previewed. Confirmed character-range font edits update the same saved history; previews and failed edits do not. Requirement: [issue #3515](https://github.com/storytold/vectorcraft/issues/3515). - **Show samples on white (a VectorCraft addition):** Preferences › Type › Show samples on white (`fontSamplesOnWhite`, off by default) draws each family's sample in every font menu, and in Type → Font in the in-window menu bar, in dark type on a white area in every interface brightness. A highlighted row's color shows above and below the white area, and the names and the rest of the menu keep the interface's colors. The checkbox is dimmed while Enable in-menu font previews is off. Tests: `crates/ui-egui/src/tests/font_menu.rs`, `crates/ui-egui/src/font_menu/tests.rs`, `crates/ui-egui/src/prefs_dialog/tests.rs`. - **Show Similar Fonts: families without numbers come last:** in a font menu's Show Similar Fonts list and `text.similarFonts`, a family whose faces give none of the numbers the list compares (PANOSE, weight, width, heights, average width, italic angle) in common with the chosen family comes after every family of its script group that shares one, instead of right after the chosen family as an exact match. This is VectorCraft's own rule; the help page (https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/font-options-overview.html) describes the list only as fonts that look like the chosen one. Regression tests: `a_family_without_numbers_comes_after_the_measured_ones` and `likeness_is_a_distance` in `crates/text/src/tests/similar.rs`. From 6007ea7b06bed81e545115051177b2485d4eb19a Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 17 Nov 2026 10:11:06 -0800 Subject: [PATCH 109/176] PDF import: a Type 3 font's glyph procedures are checked for color once per document The scan that looks for d0 glyph procedures ran every time a page or a form listed a Type 3 font in a font dictionary of its own, and its result was dropped once the font had been noted. It now runs when the font is first noted for the document. Each page still maps the font's glyphs, and the note the import keeps for the font is unchanged. --- crates/pdf/src/import_scan.rs | 84 +++++++++++++------------ crates/pdf/src/tests/import_fidelity.rs | 50 +++++++++++++++ docs/target-app-parity.md | 1 + 3 files changed, 96 insertions(+), 39 deletions(-) diff --git a/crates/pdf/src/import_scan.rs b/crates/pdf/src/import_scan.rs index b65254eafa..fa76505614 100644 --- a/crates/pdf/src/import_scan.rs +++ b/crates/pdf/src/import_scan.rs @@ -663,47 +663,11 @@ impl Walker<'_, '_> { self.out.type3_cache_map.insert(hash, (f_key, to_unicode)); } } - let is_colour = if is_type3 { - let mut colour = false; - let mut seen_streams = HashSet::new(); - let mut decoded_bytes = 0usize; - const MAX_CHARPROC_BYTES: usize = 16 << 20; - if let Some(char_procs) = f.get::<Dict<'_>>(b"CharProcs") { - for key in char_procs.keys() { - if let Some(stream) = char_procs.get::<Stream<'_>>(key.as_ref()) { - if !seen_streams.insert(stream.cache_key()) { - continue; - } - if decoded_bytes >= MAX_CHARPROC_BYTES { - colour = true; - break; - } - if let Ok(data) = stream.decoded_within(MAX_CHARPROC_BYTES.saturating_sub(decoded_bytes)) { - decoded_bytes = decoded_bytes.saturating_add(data.len()); - let mut iter = TypedIter::new(data.as_ref()); - while let Some(op) = iter.next() { - match op { - TypedInstruction::ColorGlyph(_) => { - colour = true; - break; - } - TypedInstruction::ShapeGlyph(_) => break, - _ => {} - } - } - if colour { - break; - } - } - } - } - } - colour - } else { - false - }; + // A font is noted once for the document, so its glyph procedures are read only the + // first time any page or form lists it. self.fonts.entry(f_key).or_insert_with(|| { let embedded = embeds_glyphs(&f); + let is_colour = is_type3 && sets_glyph_colors(&f); FontNote { name, embedded, vertical: vertical_metrics(&f, embedded), is_type3, to_unicode, is_colour } }); } @@ -1108,6 +1072,48 @@ fn font_name(f: &Dict<'_>) -> Option<String> { Some(stripped.unwrap_or(base)) } +/// The most bytes of a Type 3 font's glyph procedures decoded to look for colored glyphs. +const MAX_CHARPROC_BYTES: usize = 16 << 20; + +// The glyph procedures decoded by `sets_glyph_colors` on this thread. +#[cfg(test)] +thread_local! { + pub(crate) static TEST_CHARPROC_DECODES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; +} + +/// Whether Type 3 font `f` has a glyph procedure that sets its own color (`d0`, ISO 32000-1 +/// §9.6.5): its procedures are read until one starts with `d0`, each up to its `d0` or `d1`. Past +/// [`MAX_CHARPROC_BYTES`] of them the font is taken to have one. +fn sets_glyph_colors(f: &Dict<'_>) -> bool { + let Some(char_procs) = f.get::<Dict<'_>>(b"CharProcs") else { return false }; + let mut seen_streams = HashSet::new(); + let mut decoded_bytes = 0usize; + for key in char_procs.keys() { + if let Some(stream) = char_procs.get::<Stream<'_>>(key.as_ref()) { + if !seen_streams.insert(stream.cache_key()) { + continue; + } + if decoded_bytes >= MAX_CHARPROC_BYTES { + return true; + } + #[cfg(test)] + TEST_CHARPROC_DECODES.with(|n| n.set(n.get() + 1)); + if let Ok(data) = stream.decoded_within(MAX_CHARPROC_BYTES.saturating_sub(decoded_bytes)) { + decoded_bytes = decoded_bytes.saturating_add(data.len()); + let mut iter = TypedIter::new(data.as_ref()); + while let Some(op) = iter.next() { + match op { + TypedInstruction::ColorGlyph(_) => return true, + TypedInstruction::ShapeGlyph(_) => break, + _ => {} + } + } + } + } + } + false +} + /// Whether font `f` carries its own glyphs: a font program in its descriptor (a composite font's in /// its descendant's), or a Type 3 font's glyph procedures. A font that doesn't is drawn with a /// stand-in, whose glyphs say nothing about which installed face the document means. diff --git a/crates/pdf/src/tests/import_fidelity.rs b/crates/pdf/src/tests/import_fidelity.rs index 251cc925bf..188ca0e80d 100644 --- a/crates/pdf/src/tests/import_fidelity.rs +++ b/crates/pdf/src/tests/import_fidelity.rs @@ -507,6 +507,56 @@ fn a_form_drawn_many_times_reads_its_font_resources_once() { assert_eq!(walk.fonts.len(), 1); } +/// A Type 3 font that every page lists in a font dictionary of its own, and a form lists in its +/// resources, has its glyph procedures read once for the document. Each page still maps the font's +/// glyphs, and the font whose glyphs set their own color (`d0`) is told from the one whose glyphs +/// don't (`d1`). +#[test] +fn a_type3_font_on_every_page_has_its_glyph_procedures_read_once() { + const PAGES: usize = 6; + let n = first_extra(PAGES); + let (shape, color, shape_a, shape_b, color_a, form) = (n, n + 1, n + 2, n + 3, n + 4, n + 5); + let font = |name: &str, procs: &str| { + format!( + "<< /Type /Font /Subtype /Type3 /Name /{name} /FontBBox [0 0 1000 1000] /FontMatrix [0.001 0 0 0.001 0 0] /CharProcs << {procs} >> /Encoding << /Type /Encoding /Differences [97 /a /b] >> /FirstChar 97 /LastChar 98 /Widths [1000 1000] /Resources << >> >>" + ) + }; + let objects = [ + font("Vcshape", &format!("/a {shape_a} 0 R /b {shape_b} 0 R")), + font("Vccolor", &format!("/a {color_a} 0 R /b {color_a} 0 R")), + stream("", "1000 0 0 0 1000 1000 d1 0 0 1000 1000 re f"), + stream("", "1000 0 0 0 1000 1000 d1 0 0 500 500 re f"), + stream("", "1000 0 d0 1 0 0 rg 0 0 1000 1000 re f"), + stream( + &format!("/Type /XObject /Subtype /Form /BBox [0 0 100 100] /Resources << /Font << /C {color} 0 R /S {shape} 0 R >> >>"), + "BT /S 12 Tf (ab) Tj /C 12 Tf (ab) Tj ET", + ), + ]; + let pages: Vec<PdfPage> = (0..PAGES) + .map(|_| PdfPage { + resources: format!("/Font << /S {shape} 0 R /C {color} 0 R >> /XObject << /X0 {form} 0 R >>"), + ..PdfPage::new(100.0, 100.0, "BT /S 24 Tf 10 30 Td (ab) Tj /C 24 Tf (ab) Tj ET /X0 Do") + }) + .collect(); + let extra: Vec<&str> = objects.iter().map(String::as_str).collect(); + let pdf = craft_pdf::syntax::Pdf::new(pdf_with(&pages, &extra, None)).unwrap(); + let mut fonts = crate::import_scan::FontNames::new(); + let mut ocgs = crate::import_scan::Ocgs::read(&pdf); + crate::import_scan::TEST_CHARPROC_DECODES.with(|d| d.set(0)); + for page in pdf.pages().iter() { + let scan = crate::import_scan::scan_page(page, &mut ocgs, false, &mut fonts, pdf.decode_limits().max_decoded_stream()).unwrap(); + let mapped: std::collections::HashSet<(u128, bool)> = scan.type3_cache_map.values().copied().collect(); + let noted: std::collections::HashSet<(u128, bool)> = fonts.keys().map(|k| (*k, false)).collect(); + assert_eq!(scan.type3_cache_map.len(), 2 * 257); + assert_eq!(mapped, noted); + let mut colors: Vec<(String, bool)> = fonts.values().map(|f| (f.name.clone(), f.is_colour)).collect(); + colors.sort(); + assert_eq!(colors, [("Vccolor".to_string(), true), ("Vcshape".to_string(), false)]); + } + // The `d1` font's two procedures and the `d0` font's one. + assert_eq!(crate::import_scan::TEST_CHARPROC_DECODES.with(std::cell::Cell::get), 3); +} + /// A value of the page's font dictionary that the reader can't parse (a name with a broken `#` /// escape, a number with a stray `-`) is left out when the page's fonts are noted, and the fonts /// after it are noted. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index e9fc9a6820..0bee598ceb 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -679,6 +679,7 @@ since 2026-10-01. - **EPS writes a repeated freeform gradient's image once:** a freeform gradient whose image samples the same on more than one fill (copies of a shape moved with their points, or one shape in a symbol's instances) has its samples written once in the setup, as a repeated image's are, and a fill whose image differs (other colors, another size) gets its own. A freeform fill drawn once is written where it is drawn, as before, and a fill whose placement cannot be drawn, or that arrives when the page is already at the 256 MB limit, is no longer sampled first (eps `tests::a_freeform_gradients_image_drawn_twice_writes_its_samples_once`, `tests::freeform_gradients_sampled_differently_dont_share_an_image`, `tests::a_field_taken_back_at_the_page_limit_leaves_no_image_behind`). Scores and hours unchanged. - **EPS releases the images of art left out at the page limit:** art taken back because it passes the 256 MB limit on the page no longer keeps the encoded samples of the placed images, colorized images and freeform fills it drew, and an image whose first placement does not fit under the limit is not kept after it is encoded. Later placements of that image are left out with the same warning without encoding it again while it still does not fit; once art taken back leaves room, it is encoded again and written where it is drawn. The page the EPS file draws is the same as before; a repeated image or field written after art taken back can take a lower resource number in the setup (eps `tests::a_rolled_back_node_frees_its_image_codes`, `tests::a_rolled_back_image_does_not_pin_an_earlier_field_code`, `tests::an_image_rejected_by_the_page_limit_keeps_no_unused_code`, `tests::an_image_rejected_by_the_page_limit_is_encoded_once`, `tests::an_image_rejected_in_art_taken_back_is_encoded_again_when_it_fits`). Scores and hours unchanged. - **PDF writes a warped image once:** with downsampling on, the pieces of an image bent by a Warp effect are resampled for the widest and the highest size any piece places the image at, so every piece paints one image XObject (a colorized image: one colorized image and its soft mask), instead of one image for each size a piece is placed at. Another placement of the same image is still resampled for its own size. Without downsampling, a colorized image and a CMYK image with a grayscale image mask on its grid are decoded and encoded once for all the sizes they are placed at (pdf `tests::compression::a_warped_image_is_written_once_for_all_its_pieces`, `tests::colorize::a_colorized_warped_image_is_written_once_for_all_its_pieces`, `export::images::tests::colorized_and_grid_masked_images_are_made_once_for_every_size_without_downsampling`). Scores and hours unchanged. +- **PDF import reads a Type 3 font's glyph procedures once:** a Type 3 font that many pages or forms list, each in a font dictionary of its own, has its glyph procedures checked for glyphs that set their own color once for the document, when the font is first noted, instead of again on every page and form. The pages open as before (pdf `tests::import_fidelity::a_type3_font_on_every_page_has_its_glyph_procedures_read_once`). Scores and hours unchanged. - **Distort Appearance with Transform effect options:** with Envelope Options › Distort Appearance on, a path whose Transform effect has Scale Strokes & Effects or Transform Patterns on, or copies it with a gradient, is bent as the same per-copy art it draws and expands as outside the envelope: each copy's own stroke weight, dashes, pattern placement and gradient (effects `bake::tests`). Scores and hours unchanged. - **Fitted gradients turn with the Transform effect:** a gradient fitted to the object (not placed with the Gradient tool) turns, reflects and stretches with the object when its Transform effect rotates, reflects or scales it unevenly, as Object › Transform already does: the gradient is fixed to its fit on the geometry the effect takes, then follows the effect and the effects after it as a placed gradient does. Under moves and even scales it draws as a refit does, and a Transform effect that scales the object to nothing across leaves it fitted, with Scale Strokes & Effects or Transform Patterns on too, and on each copy. This holds on the canvas and in Object › Expand of the fill, for an object's own effects, a fill's or stroke's own, and a group's, where the gradients fitted to its paths, to its own fill, to the groups inside it and to its images' and symbol instances' own fills each fix to their own object's fit. Existing documents with such a Transform effect on fitted-gradient art draw differently: before, the gradient refit to the turned outline. The Gradient tool still shows a fitted gradient's vector at its unturned fit. How gradients follow the effect is VectorCraft's own rule; what the effect does to the object is described in [Distort and transform effects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/distort-and-transform-effects-in-illustrator.html) (effects `bake::tests::a_fitted_gradient_turns_reflects_and_stretches_with_a_transform_effect`, `bake::tests::a_transform_effect_that_scales_to_nothing_leaves_a_fitted_gradient_fitted`, `group::tests::a_groups_transform_turns_the_gradients_fitted_to_its_members_and_its_own_fill`; render `objectfx::a_fitted_gradient_turns_and_reflects_with_its_transform_on_the_canvas`; engine `objexpand::a_fitted_gradient_turned_by_a_transform_expands_as_the_canvas_draws_it`). Scores and hours unchanged. - **Placed gradients follow Transform and Free Distort effects:** a gradient placed with the Gradient tool moves, turns and scales with the object when the object's Transform effect moves its outline, and each copy of the Transform effect takes it as many times as it takes the transform. Under Free Distort it moves and scales from the path's bounds before the effect to its bounds after it. This holds on the canvas, in export, in Expand Appearance, in Pathfinder and compound shapes, and in Object › Expand of the fill, for an object's own effects, a group's (the own fills of the group, of the groups inside it, of a symbol's art, and of the images and symbol instances it moves, included) and a fill's or stroke's own. A gradient on a path inside a group with a Transform effect now moves with the path (#2214 moved only the gradients of type), and so does a gradient on an image's or symbol instance's own fill. When a path keeps its shape because the effect would pass the geometry budget, the group's own gradients stay in place; a hidden path in a layer, which the layer's bounds leave out, does not hold them. A freeform gradient whose points were edited moves its points in the same way. How gradients follow each effect is VectorCraft's own rule; what each effect does to the object is described in [Distort and transform effects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/distort-and-transform-effects-in-illustrator.html) (effects `bake::tests::a_baked_transform_moves_a_placed_gradient_with_the_path`, `bake::tests::a_strokes_own_transform_and_free_distort_move_its_placed_gradient`, `bake::tests::a_fills_gradient_follows_the_effects_around_its_transform_with_options`, `bake::tests::baked_free_distort_moves_placed_gradients_from_the_bounds_to_the_distorted_bounds`, `group::tests::a_groups_transform_and_free_distort_move_the_gradients_placed_on_its_paths`, `group::tests::a_groups_transform_moves_the_gradient_of_its_own_fill`, `group::tests::a_nested_groups_own_gradient_follows_the_outer_groups_transform_and_free_distort`, `group::tests::a_groups_transform_moves_the_gradients_placed_on_an_images_own_fills`, `group::tests::shape_art_moves_gradients_with_a_transform_effect`, `group::tests::shape_art_moves_the_gradient_of_a_symbol_instances_art_with_its_transform`, `tests::art_past_the_budget_keeps_its_own_gradients_in_place`, `tests::a_hidden_path_past_the_budget_leaves_a_layers_gradients_free_to_move`, `tests::edited_freeform_points_follow_a_transform_effect_and_free_distort`; render `objectfx::a_paths_gradient_moves_with_its_transform_and_free_distort`; engine `objexpand::a_placed_gradient_moved_by_a_transform_or_free_distort_expands_as_the_canvas_draws_it`). Scores and hours unchanged. From f3fa4e0a17e7fbfb664608ce0a1680e691e61173 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 17 Nov 2026 10:26:17 -0800 Subject: [PATCH 110/176] PDF/.ai import: the text document reader moves its stories out instead of copying them Texts::read copied the stories, the default styles, the paragraph defaults and the frames out of the parsed text document and then dropped the document. It now looks every required path up first, reads the styles, Kinsoku sets and fonts from the whole document, and then moves those four parts out. Every document that read before reads to equal values, and every one that did not still does not. Reading a synthetic editing copy with 2,000 point-type stories (1.8 MB) takes a median of 60 ms of CPU time instead of 109 ms (7 alternating runs each, one process). The gain matters on documents with a lot of type. --- crates/eps/src/import/ate.rs | 136 +++++++++++++++++++++++++++++++++-- 1 file changed, 129 insertions(+), 7 deletions(-) diff --git a/crates/eps/src/import/ate.rs b/crates/eps/src/import/ate.rs index c971b250f2..622d1902ff 100644 --- a/crates/eps/src/import/ate.rs +++ b/crates/eps/src/import/ate.rs @@ -65,6 +65,14 @@ impl Val { } } + /// Removes the entry `key` of a dictionary and returns it, without copying it. + fn take(&mut self, key: &str) -> Option<Val> { + match self { + Val::Dict(d) => d.remove(key), + _ => None, + } + } + fn num(&self) -> Option<f64> { match self { Val::Num(n) if n.is_finite() => Some(*n), @@ -86,6 +94,14 @@ impl Val { } } + /// [`Self::list`] as an owned vector, without copying the items: empty when this isn't a list. + fn into_list(self) -> Vec<Val> { + match self { + Val::List(l) => l, + _ => Vec::new(), + } + } + fn nums(&self) -> Option<Vec<f64>> { self.list().iter().map(Val::num).collect() } @@ -660,20 +676,30 @@ impl Texts { }) .collect(); let main = doc.get("1")?; + main.get("1")?; + main.get("2")?; + doc.get("0")?.get("8")?.get("0")?; let sheets = |key: &str| -> Vec<Val> { let list = doc.get("0").and_then(|d| d.get(key)).and_then(|s| s.get("0")).map(Val::list).unwrap_or_default(); list.iter().take(MAX_SHEETS).map(|s| s.get("0").cloned().unwrap_or(Val::Dict(BTreeMap::new()))).collect() }; + let char_sheets = sheets("5"); + let para_sheets = sheets("6"); + let kinsoku_sets = kinsoku_sets(&doc); + // Every path is there (looked up above), so the stories, defaults and frames move out of the + // document without a copy. + let mut doc = doc; + let mut main = doc.take("1")?; Some(Texts { - stories: main.get("1")?.list().to_vec(), + stories: main.take("1")?.into_list(), fonts, - defaults: main.get("2")?.clone(), - para_defaults: main.get("3").cloned().unwrap_or(Val::Dict(BTreeMap::new())), - char_sheets: sheets("5"), - para_sheets: sheets("6"), - frames: doc.get("0")?.get("8")?.get("0")?.list().to_vec(), + defaults: main.take("2")?, + para_defaults: main.take("3").unwrap_or(Val::Dict(BTreeMap::new())), + char_sheets, + para_sheets, + frames: doc.take("0")?.take("8")?.take("0")?.into_list(), patterns: HashMap::new(), - kinsoku_sets: kinsoku_sets(&doc), + kinsoku_sets, }) } @@ -3084,4 +3110,100 @@ mod tests { let (placed, at, _) = first(&s, true); assert!(placed && at.is_some_and(|x| (x - (own + 3.0)).abs() < 1e-6), "{at:?} for {}", own + 3.0); } + + /// [`Val::take`] and [`Val::into_list`] hand over the value they find without copying it. + #[test] + fn taking_a_value_keeps_its_storage() { + let mut v = read(b"/1 [ (a story) << /0 (its frame) >> ] /2 (defaults)").unwrap(); + let (Some(Val::List(l)), Some(Val::Str(s))) = (v.get("1"), v.get("2")) else { panic!("a list and a string") }; + let (list, string) = (l.as_ptr(), s.as_ptr()); + let taken = v.take("1").unwrap().into_list(); + assert_eq!(taken.as_ptr(), list); + assert_eq!(taken.len(), 2); + let Some(Val::Str(s)) = v.take("2") else { panic!("a string") }; + assert_eq!(s.as_ptr(), string); + assert_eq!(v, Val::Dict(BTreeMap::new())); + assert_eq!(v.take("1"), None); + assert_eq!(Val::Num(1.0).take("1"), None); + assert_eq!(Val::Str("x".into()).into_list(), Vec::new()); + } + + /// [`Texts::read`] gives the same stories, defaults, frames, styles, Kinsoku sets and fonts as + /// copying each of them out of the parsed document does, and reads nothing where that finds + /// nothing. + #[test] + fn the_text_document_reads_the_same_as_copying_its_parts() { + type Parts = (Vec<Val>, Val, Val, Vec<Val>, Vec<Val>, Vec<Val>, Vec<Option<Kinsoku>>, Vec<(String, Option<String>)>); + let copied = |document: &str| -> Option<Parts> { + let doc = names::numbered(read(document.as_bytes())?); + let fonts = doc.get("0")?.get("1")?.get("0")?.list(); + let fonts = fonts + .iter() + .map(|f| { + let record = f.get("0").and_then(|f| f.get("0")); + let text = |k: &str| record.and_then(|r| r.get(k)).and_then(Val::str); + (text("0").unwrap_or_default().to_string(), text("5").and_then(record_version).map(str::to_string)) + }) + .collect(); + let main = doc.get("1")?; + let sheets = |key: &str| -> Vec<Val> { + let list = doc.get("0").and_then(|d| d.get(key)).and_then(|s| s.get("0")).map(Val::list).unwrap_or_default(); + list.iter().take(MAX_SHEETS).map(|s| s.get("0").cloned().unwrap_or(Val::Dict(BTreeMap::new()))).collect() + }; + Some(( + main.get("1")?.list().to_vec(), + main.get("2")?.clone(), + main.get("3").cloned().unwrap_or(Val::Dict(BTreeMap::new())), + doc.get("0")?.get("8")?.get("0")?.list().to_vec(), + sheets("5"), + sheets("6"), + kinsoku_sets(&doc), + fonts, + )) + }; + let read_parts = |document: &str| -> Option<Parts> { + // Padded so that the data's end, `~>`, stays on one line. + let mut document = document.to_string(); + while crate::import::tests_native::native_with_text("", &document).contains("\n%>\n") { + document.push('\n'); + } + let t = Texts::read(crate::import::tests_native::native_with_text("", &document).as_bytes())?; + let fonts = t.fonts.iter().map(|f| (f.name.clone(), f.version.clone())).collect(); + Some((t.stories, t.defaults, t.para_defaults, t.frames, t.char_sheets, t.para_sheets, t.kinsoku_sets, fonts)) + }; + let plain = crate::import::tests_native::text_document(&[ + ("First story", 0, (10.0, 20.0), (1.0, 2.0), 0.0), + ("Second, longer story", 2, (30.0, 40.0), (3.0, 4.0), 5.0), + ("Third", 1, (50.0, 60.0), (5.0, 6.0), 0.0), + ]); + let full = plain + .replacen( + "/8 << /0 [", + "/4 << /0 [ << /0 << /0 (PhotoshopKinsokuHard) >> >> << /0 << /0 (Own) >> >> ] >> \ + /5 << /0 [ << /0 << /0 (Normal) /6 << /1 9.0 >> >> >> << /1 0 >> ] >> \ + /6 << /0 [ << /0 << /0 (Body) /5 << /0 2 >> >> >> ] >> /8 << /0 [", + 1, + ) + .replacen("/2 << /1 12.0 >>", "/2 << /1 12.0 /0 1 >> /3 << /0 2 /33 1 >>", 1); + let cases = [ + ("every part", full.clone(), true), + ("no paragraph defaults", plain.clone(), true), + ("stories that aren't a list", full.replacen("\n/1 << /1 [", "\n/1 << /1 5 /7 [", 1), true), + ("frames that aren't a list", full.replacen("/8 << /0 [", "/8 << /0 5 /7 [", 1), true), + ("no defaults", full.replacen("/2 << /1 12.0 /0 1 >>", "", 1), false), + ("no frames", full.replacen("/8 << /0 [", "/9 << /0 [", 1), false), + ("no stories", full.replacen("\n/1 << /1 [", "\n/1 << /7 [", 1), false), + ("no fonts", full.replacen("/0 << /1 << /0 [", "/0 << /1 << /7 [", 1), false), + ]; + for (case, document, reads) in cases { + assert!(case == "every part" || document != full, "{case} changes the document"); + let want = copied(&document); + assert_eq!(want.is_some(), reads, "{case}"); + assert_eq!(read_parts(&document), want, "{case}"); + } + let Some((stories, defaults, para_defaults, frames, char_sheets, para_sheets, kinsoku, fonts)) = read_parts(&full) else { panic!("read") }; + assert_eq!((stories.len(), frames.len(), char_sheets.len(), para_sheets.len(), fonts.len()), (3, 3, 2, 1, 1)); + assert_eq!(kinsoku, [Some(Kinsoku::Hard), None]); + assert!(defaults.get("0").is_some() && para_defaults.get("33").is_some()); + } } From 34587834ac4896b9bda73452358b8535e14b7d20 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 17 Nov 2026 10:24:54 -0800 Subject: [PATCH 111/176] SVG import: an image's bytes are hashed for its key once per import Importer::image hashed the whole image buffer for its key on every <image> and <use> that showed it, and doc.images then kept only the first result. Every use of one data URL or linked file gets the same buffer, so the key is now kept for that buffer, by its address, for the rest of the import, with the buffer held so the address is not reused. Keys, stored images, links and warnings are unchanged; the tests compare the whole document with an import that hashes every image. With one 3.4 MB PNG data URL shown by 500 <use> elements, the import took a median 1,883 ms of thread CPU time when every image was hashed and 28 ms with the keys kept. --- crates/svg/src/import.rs | 4 + crates/svg/src/import/importer.rs | 268 +++++++++++++++++++++++++++++- docs/target-app-parity.md | 1 + 3 files changed, 269 insertions(+), 4 deletions(-) diff --git a/crates/svg/src/import.rs b/crates/svg/src/import.rs index 6348b6e141..8b115d17cf 100644 --- a/crates/svg/src/import.rs +++ b/crates/svg/src/import.rs @@ -208,6 +208,7 @@ pub(crate) fn import_finding( blends: fx::blends(&xml, &scan.markers), filter_sources: fx::sources(&xml, &scan.markers, |h| files.data_href(h)), files, + image_keys: HashMap::new(), non_scaling: found.non_scaling, data: found.data, events: found.events, @@ -371,6 +372,9 @@ struct Importer { filter_sources: HashMap<String, fx::Source>, /// The files `<image>` elements link to. files: files::Files, + /// The image key of each raster image usvg got, by the address of its bytes, with the bytes + /// held so that the address isn't given to other bytes during the import. + image_keys: HashMap<usize, (Arc<Vec<u8>>, String)>, /// Ids of the shapes whose strokes don't scale ([`vector_effect`]). non_scaling: HashSet<String>, /// The `data-*` attributes of elements, by id ([`user_data`]). diff --git a/crates/svg/src/import/importer.rs b/crates/svg/src/import/importer.rs index 9badabc601..e456db24db 100644 --- a/crates/svg/src/import/importer.rs +++ b/crates/svg/src/import/importer.rs @@ -778,6 +778,7 @@ impl Importer { usvg::ImageKind::WEBP(d) => (d, "image/webp"), usvg::ImageKind::SVG(tree) => return self.svg_image(tree, acc), }; + let source = bytes; let size = i.size(); let (pw, ph) = vectorcraft_doc::header_size(bytes).unwrap_or((size.width().round().max(1.0) as u32, size.height().round().max(1.0) as u32)); // A turned CMYK image is stored as the CMYK TIFF of its inks, the size of the PNG usvg got. @@ -790,10 +791,7 @@ impl Importer { let linked = self.files.linked(i.kind()); let missing = linked.is_some_and(|l| l.missing); let link = linked.map(|l| l.link.clone()); - let key = match &link { - Some(l) => linked_key(bytes, &l.path), - None => format!("img-{:016x}", fnv1a(bytes)), - }; + let key = self.image_key(source, bytes, link.as_ref().map(|l| l.path.as_str())); self.doc.images.entry(key.clone()).or_insert_with(|| { let blob = ImageBlob { mime: mime.into(), bytes: bytes.clone(), proxy: missing.then(|| bytes.clone()) }; if link.is_some() && !missing { blob.with_proxy() } else { blob } @@ -811,6 +809,29 @@ impl Importer { Some(node) } + /// The image key of the raster image usvg got as `source`, stored as `bytes` (the CMYK TIFF + /// that replaces a turned CMYK image, else `source`), linked to `path` when it is linked. The + /// bytes are hashed for the first image that shows `source`; the images after it that show + /// the same bytes get the key kept for it. + fn image_key(&mut self, source: &Arc<Vec<u8>>, bytes: &[u8], path: Option<&str>) -> String { + let at = Arc::as_ptr(source) as usize; + #[cfg(test)] + let kept = !tests::UNKEPT.get(); + #[cfg(not(test))] + let kept = true; + if kept && let Some((_, key)) = self.image_keys.get(&at) { + return key.clone(); + } + #[cfg(test)] + tests::IMAGE_HASHES.set(tests::IMAGE_HASHES.get() + 1); + let key = match path { + Some(path) => linked_key(bytes, path), + None => format!("img-{:016x}", fnv1a(bytes)), + }; + self.image_keys.insert(at, (source.clone(), key.clone())); + key + } + /// An SVG shown as an image (a data URL or a linked file) → its art, `acc` mapping its size. /// Its ids are its own: they mean nothing in the SVG around it. fn svg_image(&mut self, tree: &usvg::Tree, acc: Affine) -> Option<Node> { @@ -868,6 +889,7 @@ mod tests { blends: HashMap::new(), filter_sources: HashMap::new(), files: Files::default(), + image_keys: HashMap::new(), non_scaling: HashSet::new(), data: HashMap::new(), events: HashMap::new(), @@ -889,4 +911,242 @@ mod tests { assert!(matches!(im.error, Some(SvgError::TooManyImages(crate::MAX_NESTED_SVG_IMAGES)))); assert_eq!(im.error.unwrap().to_string(), "the SVG expands to more than 256 nested SVG images"); } + + thread_local! { + /// How many times this thread's imports hashed an image's bytes for its key. + pub(super) static IMAGE_HASHES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; + /// When set, this thread's imports hash the bytes of every image for its key, without + /// the keys kept for earlier images. + pub(super) static UNKEPT: std::cell::Cell<bool> = const { std::cell::Cell::new(false) }; + } + + /// `svg` imported on this thread with `opts`, with image keys kept or not, and how many times + /// image bytes were hashed for keys. + fn import_counting(svg: &str, opts: &crate::ImportOptions, kept: bool) -> (Document, Vec<String>, usize) { + UNKEPT.set(!kept); + IMAGE_HASHES.set(0); + let imported = crate::import::import(svg, opts, crate::MAX_NODES); + UNKEPT.set(false); + let (doc, warnings) = imported.unwrap(); + (doc, warnings, IMAGE_HASHES.get()) + } + + /// The image objects of `doc` in paint order. + fn image_objects(doc: &Document) -> Vec<ImageObject> { + let mut out = vec![]; + doc.walk(|n| { + if let NodeKind::Image(im) = &n.kind { + out.push((**im).clone()); + } + }); + out + } + + fn svg_of(body: &str) -> String { + format!(r#"<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="200" height="200">{body}</svg>"#) + } + + /// A `w` × `h` PNG of pixels made from `seed`. + fn png(w: u32, h: u32, seed: u32) -> Vec<u8> { + let mut state = seed.wrapping_mul(2_654_435_761).wrapping_add(1); + let img = image::RgbaImage::from_fn(w, h, |_, _| { + state = state.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); + let [r, g, b, _] = state.to_le_bytes(); + image::Rgba([r, g, b, 255]) + }); + let mut out = vec![]; + img.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); + out + } + + fn data_url(mime: &str, bytes: &[u8]) -> String { + format!("data:{mime};base64,{}", crate::base64_encode(bytes)) + } + + /// A little-endian, uncompressed 1 × 1 CMYK TIFF of the inks `cmyk`. + fn cmyk_tiff(cmyk: [u8; 4]) -> Vec<u8> { + let entry = |tag: u16, kind: u16, count: u32, value: u32| { + [&tag.to_le_bytes()[..], &kind.to_le_bytes(), &count.to_le_bytes(), &value.to_le_bytes()].concat() + }; + let entries = 11u16; + let bits_at = 8 + 2 + u32::from(entries) * 12 + 4; + let data_at = bits_at + 8; + let mut out = [b"II".as_slice(), &[0x2a, 0], &8u32.to_le_bytes(), &entries.to_le_bytes()].concat(); + for e in [ + entry(256, 4, 1, 1), + entry(257, 4, 1, 1), + entry(258, 3, 4, bits_at), + entry(259, 3, 1, 1), + entry(262, 3, 1, 5), + entry(273, 4, 1, data_at), + entry(274, 3, 1, 1), + entry(277, 3, 1, 4), + entry(278, 4, 1, 1), + entry(279, 4, 1, 4), + entry(284, 3, 1, 1), + ] { + out.extend(e); + } + out.extend(0u32.to_le_bytes()); + for _ in 0..4 { + out.extend(8u16.to_le_bytes()); + } + assert_eq!(out.len(), data_at as usize); + out.extend(cmyk); + out + } + + /// `svg` imported with `opts` hashes image bytes `hashes` times for keys, and once for each + /// image without kept keys; both imports give the same document and warnings. + fn same_as_hashing_every_image(svg: &str, opts: &crate::ImportOptions, hashes: usize) -> (Document, Vec<String>) { + let (doc, warnings, n) = import_counting(svg, opts, true); + let (every, every_warnings, every_n) = import_counting(svg, opts, false); + assert_eq!(every_n, image_objects(&every).len(), "without kept keys, each image is hashed"); + assert_eq!(n, hashes, "image bytes hashed for keys"); + assert_eq!(warnings, every_warnings); + assert_eq!(image_objects(&doc), image_objects(&every), "the same image objects"); + assert_eq!(doc.images, every.images, "the same stored images"); + assert!(doc == every, "the same document"); + (doc, warnings) + } + + /// Every `<use>` of one image, and every `<image>` with the same data URL, shows bytes usvg + /// got once: they are hashed once, and every image has the key of the image's bytes. + #[test] + fn an_image_shown_many_times_is_hashed_once() { + let png = png(3, 2, 1); + let href = data_url("image/png", &png); + let uses: String = (0..6).map(|i| format!(r##"<use href="#p" x="{}"/>"##, i * 10)).collect(); + let inline: String = (0..6).map(|i| format!(r#"<image href="{href}" x="{}" width="3" height="2"/>"#, i * 10)).collect(); + for body in [format!(r#"<defs><image id="p" href="{href}" width="3" height="2"/></defs>{uses}"#), inline] { + let (doc, warnings) = same_as_hashing_every_image(&svg_of(&body), &crate::ImportOptions::default(), 1); + assert!(warnings.is_empty(), "{warnings:?}"); + let objects = image_objects(&doc); + assert_eq!(objects.len(), 6); + let key = format!("img-{:016x}", fnv1a(&png)); + assert!(objects.iter().all(|o| o.key == key && o.link.is_none() && (o.width, o.height) == (3, 2)), "{objects:?}"); + assert_eq!(doc.images.keys().collect::<Vec<_>>(), [&key]); + assert_eq!((doc.images[&key].mime.as_str(), &**doc.images[&key].bytes, doc.images[&key].proxy.is_none()), ("image/png", &png[..], true)); + } + } + + /// One image is hashed once; two images of different bytes twice, with keys of their own; two + /// data URLs written differently that hold the same bytes are hashed once each, and share the + /// key and the stored image of those bytes. + #[test] + fn each_buffer_of_image_bytes_is_hashed_once() { + let (a, b) = (png(2, 2, 1), png(2, 2, 2)); + let image = |href: &str| format!(r#"<image href="{href}" width="2" height="2"/>"#); + let opts = crate::ImportOptions::default(); + let (doc, _) = same_as_hashing_every_image(&svg_of(&image(&data_url("image/png", &a))), &opts, 1); + assert_eq!(image_objects(&doc)[0].key, format!("img-{:016x}", fnv1a(&a))); + let two = [image(&data_url("image/png", &a)), image(&data_url("image/png", &b)), image(&data_url("image/png", &a))].concat(); + let (doc, _) = same_as_hashing_every_image(&svg_of(&two), &opts, 2); + let keys: Vec<String> = image_objects(&doc).into_iter().map(|o| o.key).collect(); + assert_eq!(keys, [format!("img-{:016x}", fnv1a(&a)), format!("img-{:016x}", fnv1a(&b)), format!("img-{:016x}", fnv1a(&a))]); + assert_eq!(doc.images.len(), 2); + let spelled = [image(&data_url("image/png", &a)), image(&data_url("image/png;x=y", &a))].concat(); + let (doc, _) = same_as_hashing_every_image(&svg_of(&spelled), &opts, 2); + let keys: Vec<String> = image_objects(&doc).into_iter().map(|o| o.key).collect(); + assert_eq!(keys, [format!("img-{:016x}", fnv1a(&a)), format!("img-{:016x}", fnv1a(&a))]); + assert_eq!(doc.images.len(), 1); + } + + /// Every image of one linked file, or of one missing file, is hashed once: the file is read + /// once, and every image has the key of its bytes and its path, with its link. + #[test] + fn a_linked_or_missing_file_shown_many_times_is_hashed_once() { + let png = png(4, 2, 3); + let reads = std::sync::atomic::AtomicUsize::new(0); + let read = |path: &str| { + reads.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + path.ends_with("a.png").then(|| (png.clone(), vectorcraft_doc::LinkInfo::new(path))) + }; + let opts = crate::ImportOptions { folder: Some("/f"), read: Some(&read) }; + for (name, missing) in [("a.png", false), ("gone.png", true)] { + let body: String = (0..5).map(|i| format!(r#"<image href="{name}" x="{}" width="4" height="2"/>"#, i * 10)).collect(); + reads.store(0, std::sync::atomic::Ordering::Relaxed); + let (doc, warnings) = same_as_hashing_every_image(&svg_of(&body), &opts, 1); + assert_eq!(reads.load(std::sync::atomic::Ordering::Relaxed), 2, "{name}: one read for each of the two imports"); + assert_eq!(warnings.iter().any(|w| w.contains(name)), missing, "{name}: {warnings:?}"); + let objects = image_objects(&doc); + assert_eq!(objects.len(), 5); + let path = objects[0].link.as_ref().expect("linked").path.clone(); + assert!(path.ends_with(name), "{path}"); + let stored = doc.images[&objects[0].key].clone(); + assert_eq!(objects[0].key, linked_key(&stored.bytes, &path), "{name}"); + assert!(objects.iter().all(|o| o.key == objects[0].key && o.link.as_ref().is_some_and(|l| l.path == path)), "{name}"); + assert_eq!(doc.images.len(), 1); + assert_eq!(*stored.bytes == png, !missing, "{name}: the file's bytes, or a placeholder"); + assert_eq!(stored.is_proxy(), missing, "{name}"); + } + } + + /// A CMYK TIFF shown many times is stored as a CMYK TIFF and hashed once, its key that of the + /// stored TIFF. + #[test] + fn a_cmyk_image_shown_many_times_is_hashed_once() { + let tif = cmyk_tiff([255, 0, 0, 0]); + let href = data_url("image/tiff", &tif); + let uses: String = (0..4).map(|i| format!(r##"<use href="#p" x="{}"/>"##, i * 10)).collect(); + let body = format!(r#"<defs><image id="p" href="{href}" width="10" height="10"/></defs>{uses}"#); + let (doc, _) = same_as_hashing_every_image(&svg_of(&body), &crate::ImportOptions::default(), 1); + let objects = image_objects(&doc); + assert_eq!(objects.len(), 4); + let blob = &doc.images[&objects[0].key]; + assert_eq!(blob.mime, "image/tiff"); + assert!(blob.cmyk().is_some(), "stored with its inks"); + assert_eq!(objects[0].key, format!("img-{:016x}", fnv1a(&blob.bytes))); + assert!(objects.iter().all(|o| o.key == objects[0].key)); + } + + /// This thread's CPU time in seconds where the system reports it, else the time since a first + /// call. + fn cpu_seconds() -> f64 { + static START: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new(); + let schedstat = std::fs::read_to_string("/proc/thread-self/schedstat").ok(); + match schedstat.as_deref().and_then(|s| s.split_whitespace().next()?.parse::<f64>().ok()) { + Some(ns) => ns / 1e9, + None => START.get_or_init(std::time::Instant::now).elapsed().as_secs_f64(), + } + } + + /// The import's time for one PNG data URL shown by many `<use>` elements, hashing every image + /// and keeping keys alternating in one process: `cargo test --release -p vectorcraft-svg --lib + /// importer::tests::image_key_timing -- --ignored --nocapture`. + #[test] + #[ignore = "timing, run by hand"] + fn image_key_timing() { + for (side, uses) in [(512, 100), (1024, 500)] { + let png = png(side, side, 7); + let refs: String = (0..uses).map(|i| format!(r##"<use href="#p" transform="translate({} {})"/>"##, i % 20, i / 20)).collect(); + let svg = svg_of(&format!(r#"<defs><image id="p" href="{}" width="10" height="10"/></defs>{refs}"#, data_url("image/png", &png))); + let run = |kept: bool| { + let t = cpu_seconds(); + let (doc, _, _) = import_counting(&svg, &crate::ImportOptions::default(), kept); + let spent = cpu_seconds() - t; + assert_eq!(image_objects(&doc).len(), uses); + spent + }; + run(false); + run(true); + let (mut every, mut kept) = (vec![], vec![]); + for round in 0..7 { + if round % 2 == 0 { + every.push(run(false)); + kept.push(run(true)); + } else { + kept.push(run(true)); + every.push(run(false)); + } + } + let median = |v: &mut Vec<f64>| { + v.sort_by(f64::total_cmp); + v[v.len() / 2] + }; + let ms = |v: &[f64]| v.iter().map(|s| format!("{:.1}", s * 1e3)).collect::<Vec<_>>().join(" "); + println!("{uses} uses of a {} byte PNG: every image {} ms, kept {} ms", png.len(), ms(&every), ms(&kept)); + println!("{uses} uses: median every image {:.1} ms, kept {:.1} ms", median(&mut every) * 1e3, median(&mut kept) * 1e3); + } + } } diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index e9fc9a6820..e17f192e8a 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2104,6 +2104,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - An image that SVG import stores again as PNG keeps the ICC profile its TIFF, PNG, JPEG or WebP file carries, as Open and Place keep it, as a PNG `iCCP` chunk, when the profile's color space is the stored samples': gray for gray samples, RGB for RGB ones (<https://www.w3.org/TR/png-3/#11iCCP>). By default, SVG reads an image's colors in the profile built into the image (<https://www.w3.org/TR/SVG11/color.html#ColorProfileProperty>). A profile of another color space, one too short to be a profile, and the profile of a TIFF whose pixels its own reader converts to RGBA (one with an alpha or other extra channel, or CCITT Group 3) are left out, and the image is still imported (`a_raster_written_again_as_png_keeps_its_icc_profile` in `crates/svg/tests/it/image_orientation.rs`). - SVG import leaves out an SVG shown as an image that it can't read (text that isn't XML, an SVG without a size) and goes on with the images after it, as SVG 2's error processing describes (<https://www.w3.org/TR/SVG2/conform.html>). Only images that decode count toward the 256 nested SVG images an SVG may show, so an image after many broken ones is imported. Every nested SVG image read, decoded or not, counts toward VectorCraft's own limits of 1,024 reads and 512 MB of text per import; past them, nested SVG images are left out with a warning (`crates/svg/tests/it/import_details.rs`). - SVG import decodes each image data URL (RFC 2397, <https://www.rfc-editor.org/rfc/rfc2397#section-2>) of an `<image>` or `<feImage>` once, in the imported SVG and in the SVGs shown as its images, however many `<use>` elements, filters or SVG images show it; every use gets the same image. The data URLs of one import decode to at most 512 MB together, VectorCraft's own limit: decoding stops where a URL would pass it, and that image is left out with a warning (`crates/svg/src/import/files.rs`, `crates/svg/tests/it/import_details.rs`). + - SVG import hashes the bytes of each raster image for its image key once per import, however many `<use>` elements or `<image>` elements with the same data URL or linked file show them; the other images get the same key, and the keys, stored images and links are the same as before. With one 3.4 MB PNG data URL shown by 500 `<use>` elements, importing took a median 1,883 ms of thread CPU time when every image was hashed and 28 ms with the keys kept, on Linux with other builds running (`crates/svg/src/import/importer.rs`). - SVG import measures what an SVG expands to before the SVG reader builds it: every copy a `<use>` shows (<https://www.w3.org/TR/SVG2/struct.html#UseElement>), chains of `<use>`s included, and the style values each copy gets from its `style` attribute and from the style sheet rules that match it. An SVG that expands to more than 999,999 elements (500,000 on the web) or to more than 64 MB of copied style values is refused with an error, and so is a loop of `<use>` references that would be copied without end. The declarations the import's own style cascade keeps count toward the 64 MB too, once for each element a rule matches, including those of rules the reader drops, such as ones with `:not()`. Matching the style sheets' selectors against those elements may take at most 50,000,000 tests; past that the SVG is refused, so a selector that never matches can't keep the import busy. These limits are VectorCraft's own. An SVG shown as an image, from a data URL or a linked SVG file, counts toward the same limits as the SVG showing it, and one past any of them refuses the whole import (`crates/svg/src/import/budget.rs`, `crates/svg/tests/it/import_details.rs`). - SVG import reads the files that a linked SVG file's own `<image>` elements link to, relative paths from that file's folder (<https://www.rfc-editor.org/rfc/rfc3986#section-5.1.3>), as it reads the imported SVG's links: a raster stays linked, an SVG file imports as vector art, and one that can't be read gets the placeholder, its link and a warning. SVG 2 tells a viewer not to load these links (<https://www.w3.org/TR/SVG2/conform.html#secure-static-mode>); reading them is VectorCraft's own rule. The same href in SVG files of two folders names two files. A link that leads back to an SVG file showing it gets the placeholder and a warning, and reading the links of linked SVG files stops at the nesting depth cap and at 1,024 reads and 512 MB per import, the same limits decoded nested SVG images have, counted separately from them. The text of every linked SVG file read counts, and so does every file read for the links of a linked SVG file, raster or SVG; rasters the imported SVG links to don't. Once either limit is passed, no file linked from a linked SVG file is read and its image is left out with a warning, and an SVG file the imported SVG links to is still shown, without the files its own links name, with a warning. Another href to an SVG file already read, spelled differently or in another SVG file, does not read it again, unless a link back or the depth cap changes what it shows there (`crates/svg/tests/it/import_details.rs`, `crates/svg/src/import/files.rs`). - File › Place and a file dropped on the canvas refuse a PNG, JPEG, GIF or WebP file whose pixels can't be read, such as one cut short by a download or a sync still running, and the status bar shows "Couldn't place <name>: the image's pixels can't be read". Paste and Relink refuse such an image too, and Update Links, or Open when it reads the file again, counts it as missing. A JPEG cut short still places when its pixels can be decoded (`file.place`, `crates/engine/src/tests_place.rs`). From a9ac500b1ee9cc8e0cdf04aaaba272c6c58f6377 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 17 Nov 2026 10:35:34 -0800 Subject: [PATCH 112/176] Separations Preview: a second Alt-click on the only visible plate's eye shows every plate An Alt-click (Option-click on macOS) on a plate's eye in the Separations Preview panel shows that plate alone. Alt-clicking the same eye again, while that plate is the only one of the document's plates shown, now shows every plate, spot plates included, as the help page describes: https://helpx.adobe.com/illustrator/using/printing-color-separations.html - view.separationsPreview takes soloToggle: plate for this click. A plate shown among others becomes the only plate shown, as the help page describes for the first Alt-click. A hidden plate, another plate while one shows alone, or any plate while none is shown also becomes the only plate shown (VectorCraft's own rules). only still shows just the named plate when repeated. Neither adds an undo step. - The eye's tooltip names the second Alt-click, in every catalog. Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/cmd/colormgmt.rs | 9 ++- crates/engine/src/tests/colormgmt.rs | 72 ++++++++++++++++++++++++ crates/ui-egui/src/i18n/bg.tsv | 2 +- crates/ui-egui/src/i18n/bs.tsv | 2 +- crates/ui-egui/src/i18n/ca.tsv | 2 +- crates/ui-egui/src/i18n/cs.tsv | 2 +- crates/ui-egui/src/i18n/da.tsv | 2 +- crates/ui-egui/src/i18n/de.tsv | 2 +- crates/ui-egui/src/i18n/el.tsv | 2 +- crates/ui-egui/src/i18n/es.tsv | 2 +- crates/ui-egui/src/i18n/fi.tsv | 2 +- crates/ui-egui/src/i18n/fr.tsv | 2 +- crates/ui-egui/src/i18n/gu.tsv | 2 +- crates/ui-egui/src/i18n/hi.tsv | 2 +- crates/ui-egui/src/i18n/hu.tsv | 2 +- crates/ui-egui/src/i18n/id.tsv | 2 +- crates/ui-egui/src/i18n/it.tsv | 2 +- crates/ui-egui/src/i18n/ja.tsv | 2 +- crates/ui-egui/src/i18n/ka.tsv | 2 +- crates/ui-egui/src/i18n/ko.tsv | 2 +- crates/ui-egui/src/i18n/nl.tsv | 2 +- crates/ui-egui/src/i18n/pl.tsv | 2 +- crates/ui-egui/src/i18n/pt-br.tsv | 2 +- crates/ui-egui/src/i18n/ru.tsv | 2 +- crates/ui-egui/src/i18n/sv.tsv | 2 +- crates/ui-egui/src/i18n/tr.tsv | 2 +- crates/ui-egui/src/i18n/uk.tsv | 2 +- crates/ui-egui/src/i18n/vi.tsv | 2 +- crates/ui-egui/src/i18n/zh-hans.tsv | 2 +- crates/ui-egui/src/i18n/zh-hant.tsv | 2 +- crates/ui-egui/src/panels/separations.rs | 25 ++++++-- crates/ui-egui/src/widgets.rs | 4 +- docs/mcp.md | 7 +++ docs/target-app-parity.md | 1 + 34 files changed, 139 insertions(+), 35 deletions(-) diff --git a/crates/engine/src/cmd/colormgmt.rs b/crates/engine/src/cmd/colormgmt.rs index a529a3bea9..b1f506ebb0 100644 --- a/crates/engine/src/cmd/colormgmt.rs +++ b/crates/engine/src/cmd/colormgmt.rs @@ -121,7 +121,7 @@ pub fn specs() -> Vec<CommandSpec> { "Separations Preview", [], None, - "{on?: bool, plates?: [names], toggle?: plate, only?: plate} Separations Preview: show the chosen plates (one plate = greyscale ink coverage) → {on, plates: [{name, spot, visible, rgb}]}", + "{on?: bool, plates?: [names], toggle?: plate, only?: plate, soloToggle?: plate (only that plate, or every plate when it is the only one shown)} Separations Preview: show the chosen plates (one plate = grayscale ink coverage) → {on, plates: [{name, spot, visible, rgb}]}", always, separations ), @@ -1036,6 +1036,13 @@ fn separations(s: &mut Session, p: &Value) -> Result<Value> { if let Some(n) = text_param(p, "only", C)? { v.separations = Some(vec![check(n)?]); } + // The panel's Alt-click on a plate's eye: that plate alone, or every plate when it already + // shows alone among the active document's plates. + if let Some(n) = text_param(p, "soloToggle", C)? { + let n = check(n)?; + let alone = v.separations.as_ref().is_some_and(|vis| all.iter().filter(|a| vis.contains(a)).eq([&n])); + v.separations = Some(if alone { all.clone() } else { vec![n] }); + } if let Some(n) = text_param(p, "toggle", C)? { let n = check(n)?; let vis = v.separations.get_or_insert_with(|| all.clone()); diff --git a/crates/engine/src/tests/colormgmt.rs b/crates/engine/src/tests/colormgmt.rs index 2d024f552b..660b24d6f6 100644 --- a/crates/engine/src/tests/colormgmt.rs +++ b/crates/engine/src/tests/colormgmt.rs @@ -594,6 +594,78 @@ fn separations_preview_compares_the_visible_plates_as_a_set() { assert!(r["plates"].as_array().unwrap().iter().all(|p| p["visible"] == false), "{r}"); } +/// Each plate's visibility in a `view.separationsPreview` or `color.plates` reply, in plate order. +fn visible_plates(r: &Value) -> Vec<bool> { + r["plates"].as_array().unwrap().iter().map(|p| p["visible"].as_bool().unwrap()).collect() +} + +/// A session whose document has the process plates and the spot plate `Brand Orange`. +fn session_with_spot_plate() -> Session { + let mut s = session(); + s.execute("swatch.new", &json!({"name": "Brand Orange", "color": {"c": 0, "m": 60, "y": 100, "k": 0}, "global": true})).unwrap(); + s.execute("swatch.setSpot", &json!({"name": "Brand Orange"})).unwrap(); + let a = NodeId(s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap()); + s.execute("paint.setFill", &json!({"ids": [a.0], "swatch": "Brand Orange"})).unwrap(); + s +} + +/// `soloToggle` (the panel's Alt-click on a plate's eye) shows that plate alone, and every plate +/// when it already shows alone. A hidden plate, a plate among others, another solo plate and an +/// empty set of plates all give the named plate alone. It leaves the document's undo list and +/// modified state alone. +#[test] +fn separations_preview_solo_toggle_shows_every_plate_the_second_time() { + let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner()); + let _v = DefaultView::new(); + let mut s = session_with_spot_plate(); + let undo = s.doc().unwrap().history.undo.len(); + let dirty = s.doc().unwrap().is_dirty(); + let solo = |s: &mut Session, n: &str| visible_plates(&s.execute("view.separationsPreview", &json!({"soloToggle": n})).unwrap()); + // Off: the preview turns on with the plate alone. + assert_eq!(solo(&mut s, "Cyan"), [true, false, false, false, false]); + assert_eq!(vectorcraft_render::proof::view().separations, Some(vec!["Cyan".to_string()])); + // The same plate again: every plate, the spot plate included, and the preview stays on. + assert_eq!(solo(&mut s, "Cyan"), [true; 5]); + assert!(vectorcraft_render::proof::view().separations.is_some(), "the preview stays on"); + // A plate shown among others, then another plate while one shows alone. + assert_eq!(solo(&mut s, "Magenta"), [false, true, false, false, false]); + assert_eq!(solo(&mut s, "Cyan"), [true, false, false, false, false]); + // A hidden plate. + s.execute("view.separationsPreview", &json!({"toggle": "Black"})).unwrap(); + assert_eq!(solo(&mut s, "Yellow"), [false, false, true, false, false]); + // No plate shown. + s.execute("view.separationsPreview", &json!({"plates": []})).unwrap(); + assert_eq!(solo(&mut s, "Black"), [false, false, false, true, false]); + // The spot plate alone, then every plate. + assert_eq!(solo(&mut s, "Brand Orange"), [false, false, false, false, true]); + assert_eq!(solo(&mut s, "Brand Orange"), [true; 5]); + // A plate the document doesn't have is an error and leaves the view as it is. + let before = vectorcraft_render::proof::view(); + assert!(s.execute("view.separationsPreview", &json!({"soloToggle": "Mauve"})).is_err()); + assert_eq!(vectorcraft_render::proof::view(), before); + assert_eq!(s.doc().unwrap().history.undo.len(), undo, "no undo step"); + assert_eq!(s.doc().unwrap().is_dirty(), dirty, "not marked modified"); + // `only` stays a setter: the same plate again keeps it alone. + s.execute("view.separationsPreview", &json!({"only": "Cyan"})).unwrap(); + let r = s.execute("view.separationsPreview", &json!({"only": "Cyan"})).unwrap(); + assert_eq!(visible_plates(&r), [true, false, false, false, false]); +} + +/// A plate counts as shown alone when no other plate of the active document shows: names left in +/// the visible set by another document's plates don't count. +#[test] +fn separations_preview_solo_toggle_counts_the_active_documents_plates() { + let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner()); + let _v = DefaultView::new(); + let mut s = session_with_spot_plate(); + s.execute("view.separationsPreview", &json!({"plates": ["Cyan", "Brand Orange"]})).unwrap(); + // A new document without the spot plate: Cyan is the only one of its plates shown. + s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap(); + assert_eq!(visible_plates(&s.execute("color.plates", &json!({})).unwrap()), [true, false, false, false]); + let r = s.execute("view.separationsPreview", &json!({"soloToggle": "Cyan"})).unwrap(); + assert_eq!(visible_plates(&r), [true; 4]); +} + #[test] fn proof_setup_simulates_tritanopia() { let _g = GLOBAL.lock().unwrap_or_else(|e| e.into_inner()); diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index bb039bb08e..794c31aa46 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -3489,7 +3489,7 @@ digits Malayalam Малаялам Show Vivid/Muted Показване на ярки/заглушени Show Warm/Cool Показване на топли/студени Show {kind} Brushes Показване на четки от вида {kind} - Show/hide plate (Alt-click: only this plate) Показване/скриване на плака (Alt-клик: само тази плака) + Show/hide plate (Alt-click: only this plate; Alt-click again: all plates) Показване/скриване на плака (Alt-клик: само тази плака; Alt-клик отново: всички плаки) Show: Показване: Shown with the optimised preview. Показано с оптимизирания преглед. Side 1: Страна 1: diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 99f23d313c..ccd86d03bc 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -2197,7 +2197,7 @@ digits Malayalam Malajalam Overprint Preview (separations) Pregled pretiska (separacije) Show All Plates Prikaži sve ploče Show all plates Prikaži sve ploče - Show/hide plate (Alt-click: only this plate) Prikaži/sakrij ploču (Alt-klik: samo ova ploča) + Show/hide plate (Alt-click: only this plate; Alt-click again: all plates) Prikaži/sakrij ploču (Alt-klik: samo ova ploča; ponovni Alt-klik: sve ploče) Simulate Paper Simuliraj papir Use Black Point Compensation Koristi kompenzaciju crne tačke Working CMYK (don't tag) Radni CMYK (bez oznake) diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index c54311799d..3c774d43bb 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -4530,7 +4530,7 @@ digits Malayalam Malaiàlam Show Vivid/Muted Mostra els vius/apagats Show Warm/Cool Mostra els càlids/freds Show {kind} Brushes Mostra els pinzells {kind} - Show/hide plate (Alt-click: only this plate) Mostra o amaga la planxa (Alt+clic: només aquesta planxa) + Show/hide plate (Alt-click: only this plate; Alt-click again: all plates) Mostra o amaga la planxa (Alt+clic: només aquesta planxa; Alt+clic de nou: totes les planxes) Show: Mostra: Shown with the optimised preview. Es mostra amb la previsualització optimitzada. Shrink Text to Fit Redueix el text perquè hi càpiga diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index a5d7bb948a..094b74be57 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -2270,7 +2270,7 @@ digits Malayalam Malajálamské Overprint Preview (separations) Náhled přetisků (separace) Show All Plates Zobrazit všechny desky Show all plates Zobrazit všechny desky - Show/hide plate (Alt-click: only this plate) Zobrazit/skrýt desku (Alt+kliknutí: jen tato deska) + Show/hide plate (Alt-click: only this plate; Alt-click again: all plates) Zobrazit/skrýt desku (Alt+kliknutí: jen tato deska; další Alt+kliknutí: všechny desky) Simulate Paper Simulovat papír Use Black Point Compensation Použít kompenzaci černého bodu Working CMYK (don't tag) Pracovní CMYK (neoznačovat) diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 08100f593f..3d1e0f7b61 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -4761,7 +4761,7 @@ digits Malayalam Malayalam Overprint Preview (separations) Forhåndsvisning af overtryk (separationer) Show All Plates Vis alle plader Show all plates Vis alle plader - Show/hide plate (Alt-click: only this plate) Vis/skjul plade (Alt-klik: kun denne plade) + Show/hide plate (Alt-click: only this plate; Alt-click again: all plates) Vis/skjul plade (Alt-klik: kun denne plade; Alt-klik igen: alle plader) Simulate Paper Simulér papir Use Black Point Compensation Brug sortpunktskompensation Working CMYK (don't tag) Arbejds-CMYK (mærk ikke) diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 10147b2d45..70259b7545 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -3557,7 +3557,7 @@ digits Malayalam Malayalam Show Vivid/Muted Lebhaft/Gedeckt einblenden Show Warm/Cool Warm/Kalt einblenden Show {kind} Brushes {kind}pinsel einblenden - Show/hide plate (Alt-click: only this plate) Platte ein-/ausblenden (Alt-Klick: nur diese Platte) + Show/hide plate (Alt-click: only this plate; Alt-click again: all plates) Platte ein-/ausblenden (Alt-Klick: nur diese Platte; erneuter Alt-Klick: alle Platten) Show: Anzeigen: Shown with the optimised preview. Wird mit der optimierten Vorschau angezeigt. Side 1: Seite 1: diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 1ebf6e5684..6bfbdeb5c7 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -4229,7 +4229,7 @@ digits Malayalam Μαλαγιάλαμ Show Vivid/Muted Εμφάνιση έντονων/απαλών Show Warm/Cool Εμφάνιση θερμών/ψυχρών Show {kind} Brushes Εμφάνιση πινέλων {kind} - Show/hide plate (Alt-click: only this plate) Εμφάνιση/απόκρυψη πλάκας (Alt-κλικ: μόνο αυτή η πλάκα) + Show/hide plate (Alt-click: only this plate; Alt-click again: all plates) Εμφάνιση/απόκρυψη πλάκας (Alt-κλικ: μόνο αυτή η πλάκα· ξανά Alt-κλικ: όλες οι πλάκες) Shown with the optimised preview. Εμφανίζεται με τη βελτιστοποιημένη προεπισκόπηση. Side 1: Πλευρά 1: Side 2: Πλευρά 2: diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index a456910a16..c985be7429 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -3593,7 +3593,7 @@ digits Malayalam Malayálam Show Vivid/Muted Mostrar vivos/apagados Show Warm/Cool Mostrar cálidos/fríos Show {kind} Brushes Mostrar pinceles de {kind} - Show/hide plate (Alt-click: only this plate) Mostrar/ocultar plancha (Alt+clic: solo esta plancha) + Show/hide plate (Alt-click: only this plate; Alt-click again: all plates) Mostrar/ocultar plancha (Alt+clic: solo esta plancha; Alt+clic otra vez: todas las planchas) Show: Mostrar: Shown with the optimised preview. Se muestra con la vista previa optimizada. Side 1: Lado 1: diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index bff46fc0d7..01af7ded67 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -2231,7 +2231,7 @@ digits Malayalam Malajalam Overprint Preview (separations) Päällepainatuksen esikatselu (erottelut) Show All Plates Näytä kaikki painolevyt Show all plates Näytä kaikki painolevyt - Show/hide plate (Alt-click: only this plate) Näytä/piilota painolevy (Alt-napsautus: vain tämä painolevy) + Show/hide plate (Alt-click: only this plate; Alt-click again: all plates) Näytä/piilota painolevy (Alt-napsautus: vain tämä painolevy; uusi Alt-napsautus: kaikki painolevyt) Simulate Paper Simuloi paperia Use Black Point Compensation Käytä mustan pisteen kompensointia Working CMYK (don't tag) Työ-CMYK (ei tunnistetta) diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 3be3497f97..f390c990fd 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -3581,7 +3581,7 @@ digits Malayalam Malayalam Show Vivid/Muted Afficher vives/atténuées Show Warm/Cool Afficher chaudes/froides Show {kind} Brushes Afficher les formes de type {kind} - Show/hide plate (Alt-click: only this plate) Afficher/masquer la plaque (Alt+clic : cette plaque uniquement) + Show/hide plate (Alt-click: only this plate; Alt-click again: all plates) Afficher/masquer la plaque (Alt+clic : cette plaque uniquement, puis à nouveau toutes les plaques) Show: Afficher : Shown with the optimised preview. Affiché avec l’aperçu optimisé. Side 1: Côté 1 : diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index c427fc527c..7d391f00f9 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -3731,7 +3731,7 @@ Show its progress, see Cancel and write log lines તેની પ્રગતિ બતાવવી, રદ કરવાની વિનંતી જોવી અને લૉગ લાઇનો લખવી Show segmented color wheel સેગમેન્ટેડ રંગ ચક્ર બતાવો Show smooth color wheel સ્મૂધ રંગ ચક્ર બતાવો - Show/hide plate (Alt-click: only this plate) પ્લેટ બતાવો/છુપાવો (Alt-ક્લિક: માત્ર આ પ્લેટ) + Show/hide plate (Alt-click: only this plate; Alt-click again: all plates) પ્લેટ બતાવો/છુપાવો (Alt-ક્લિક: માત્ર આ પ્લેટ; ફરી Alt-ક્લિક: બધી પ્લેટ) Show: બતાવો: Shown with the optimised preview. ઑપ્ટિમાઇઝ્ડ પ્રીવ્યૂ સાથે બતાવેલ. Side 1: બાજુ 1: diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index cbfb4f51d1..a7edfc8674 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -4873,7 +4873,7 @@ antiAlias Sharp शार्प Show Vivid/Muted चमकीले/मंद दिखाएँ Show Warm/Cool शो वार्म / कूल Show: दिखाएँ: - Show/hide plate (Alt-click: only this plate) प्लेट दिखाएँ/छिपाएँ (Alt-क्लिक: केवल यही प्लेट) + Show/hide plate (Alt-click: only this plate; Alt-click again: all plates) प्लेट दिखाएँ/छिपाएँ (Alt-क्लिक: केवल यही प्लेट; फिर से Alt-क्लिक: सभी प्लेटें) Shown with the optimised preview. आशावादी प्रीव्यू के साथ दिखाया गया है। Shrink Text to Fit टेक्स्ट को फिट करने के लिए सिकोड़ें Side 1: साइड 1: diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 0f81a72036..553c4fe020 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -4246,7 +4246,7 @@ mark-style Japanese Japán Show Vivid/Muted Élénk/tompa változatok Show Warm/Cool Meleg/hideg változatok Show {kind} Brushes Ecsetek megjelenítése: {kind} - Show/hide plate (Alt-click: only this plate) Nyomólemez megjelenítése/elrejtése (Alt+kattintás: csak ez a lemez) + Show/hide plate (Alt-click: only this plate; Alt-click again: all plates) Nyomólemez megjelenítése/elrejtése (Alt+kattintás: csak ez a lemez; újabb Alt+kattintás: minden lemez) Show: Megjelenítés: Shown with the optimised preview. Az optimalizált előnézettel együtt látható. Shrink Text to Fit Szöveg zsugorítása a kerethez diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 28ea2b5ab3..b9b2b47449 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -2020,7 +2020,7 @@ digits Malayalam Malayalam Overprint Preview (separations) Pratinjau overprint (separasi) Show All Plates Tampilkan semua pelat Show all plates Tampilkan semua pelat - Show/hide plate (Alt-click: only this plate) Tampilkan/sembunyikan pelat (Alt-klik: hanya pelat ini) + Show/hide plate (Alt-click: only this plate; Alt-click again: all plates) Tampilkan/sembunyikan pelat (Alt-klik: hanya pelat ini; Alt-klik lagi: semua pelat) Simulate Paper Simulasikan kertas Use Black Point Compensation Gunakan kompensasi titik hitam Working CMYK (don't tag) CMYK kerja (tanpa tag) diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 8f2ed3216c..44aaff0484 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -3638,7 +3638,7 @@ digits Malayalam Malayalam Show Vivid/Muted Mostra vivaci/tenui Show Warm/Cool Mostra caldi/freddi Show {kind} Brushes Mostra pennelli di tipo {kind} - Show/hide plate (Alt-click: only this plate) Mostra/nascondi lastra (Alt+clic: solo questa lastra) + Show/hide plate (Alt-click: only this plate; Alt-click again: all plates) Mostra/nascondi lastra (Alt+clic: solo questa lastra; di nuovo Alt+clic: tutte le lastre) Show: Mostra: Shown with the optimised preview. Mostrato con l'anteprima ottimizzata. Side 1: Lato 1: diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index c429f204a1..6b102791d6 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -3428,7 +3428,7 @@ mark-style Japanese 日本式 Show all plates すべての版を表示 Show handles when multiple anchors are selected 複数のアンカーを選択したときにハンドルを表示 Show {kind} Brushes {kind}ブラシを表示 - Show/hide plate (Alt-click: only this plate) 版の表示/非表示 (Alt+クリック: この版のみ) + Show/hide plate (Alt-click: only this plate; Alt-click again: all plates) 版の表示/非表示 (Alt+クリック: この版のみ、もう一度 Alt+クリック: すべての版) Show: 表示: Shown with the optimised preview. 最適化プレビューで表示されます。 Side 1: 辺 1: diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 414f45171c..e69a8d1284 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -4189,7 +4189,7 @@ digits Malayalam მალაიალამური Overprint Preview (separations) ზედდაბეჭდვის წინასწარი ნახვა (სეპარაციები) Show All Plates ყველა ფირფიტის ჩვენება Show all plates ყველა ფირფიტის ჩვენება - Show/hide plate (Alt-click: only this plate) ფირფიტის ჩვენება/დამალვა (Alt-დაწკაპუნებით: მხოლოდ ეს ფირფიტა) + Show/hide plate (Alt-click: only this plate; Alt-click again: all plates) ფირფიტის ჩვენება/დამალვა (Alt-დაწკაპუნებით: მხოლოდ ეს ფირფიტა; ხელახლა Alt-დაწკაპუნებით: ყველა ფირფიტა) Simulate Paper ქაღალდის იმიტაცია Use Black Point Compensation შავი წერტილის კომპენსაციის გამოყენება Working CMYK (don't tag) სამუშაო CMYK (ტეგის გარეშე) diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index dbda53243f..10fd383bdd 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -3417,7 +3417,7 @@ mark-style Japanese 일본식 Show all plates 모든 분판 표시 Show handles when multiple anchors are selected 여러 앵커 선택 시 핸들 표시 Show {kind} Brushes {kind} 브러시 표시 - Show/hide plate (Alt-click: only this plate) 분판 표시/숨기기(Alt 클릭: 이 분판만) + Show/hide plate (Alt-click: only this plate; Alt-click again: all plates) 분판 표시/숨기기(Alt 클릭: 이 분판만, 다시 Alt 클릭: 모든 분판) Show: 표시: Shown with the optimised preview. 최적화된 미리 보기와 함께 표시됩니다. Side 1: 면 1: diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 69aef91cfc..28207fcba1 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -2635,7 +2635,7 @@ digits Malayalam Malayalam Overprint Preview (separations) Overprintvoorbeeld (separaties) Show All Plates Alle platen weergeven Show all plates Alle platen weergeven - Show/hide plate (Alt-click: only this plate) Plaat weergeven/verbergen (Alt-klik: alleen deze plaat) + Show/hide plate (Alt-click: only this plate; Alt-click again: all plates) Plaat weergeven/verbergen (Alt-klik: alleen deze plaat; nogmaals Alt-klik: alle platen) Simulate Paper Papier simuleren Use Black Point Compensation Zwartpuntcompensatie gebruiken Working CMYK (don't tag) Werk-CMYK (niet taggen) diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 0147515ffe..4261858b2f 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -2188,7 +2188,7 @@ digits Malayalam Malajalam Overprint Preview (separations) Podgląd nadruku (rozbarwienia) Show All Plates Pokaż wszystkie płyty Show all plates Pokaż wszystkie płyty - Show/hide plate (Alt-click: only this plate) Pokaż/ukryj płytę (kliknięcie z Alt: tylko ta płyta) + Show/hide plate (Alt-click: only this plate; Alt-click again: all plates) Pokaż/ukryj płytę (kliknięcie z Alt: tylko ta płyta; ponowne kliknięcie z Alt: wszystkie płyty) Simulate Paper Symuluj papier Use Black Point Compensation Użyj kompensacji punktu czerni Working CMYK (don't tag) Roboczy CMYK (bez znacznika) diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 8201db7ab6..32b169e072 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -3027,7 +3027,7 @@ digits Malayalam Malaiala Show handles when multiple anchors are selected Mostrar alças quando vários pontos de ancoragem estão selecionados Show in Folder Mostrar na Pasta Show {kind} Brushes Mostrar Pincéis de {kind} - Show/hide plate (Alt-click: only this plate) Mostrar/ocultar placa (Alt-clique: somente esta placa) + Show/hide plate (Alt-click: only this plate; Alt-click again: all plates) Mostrar/ocultar placa (Alt-clique: somente esta placa; Alt-clique de novo: todas as placas) Show: Mostrar: Shown with the optimised preview. Exibido com a visualização otimizada. Side 1: Lado 1: diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index d1593508d3..9f9cca68d4 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -3625,7 +3625,7 @@ digits Malayalam Малаялам Show Vivid/Muted Показать яркие/приглушённые Show Warm/Cool Показать тёплые/холодные Show {kind} Brushes Показать кисти {kind} - Show/hide plate (Alt-click: only this plate) Показать/скрыть пластину (Alt+щелчок: только эту пластину) + Show/hide plate (Alt-click: only this plate; Alt-click again: all plates) Показать/скрыть пластину (Alt+щелчок: только эту пластину; повторный Alt+щелчок: все пластины) Show: Показать: Shown with the optimised preview. Показано с оптимизированным просмотром. Side 1: Сторона 1: diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 5c0420fcd3..8bd8db8070 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -3509,7 +3509,7 @@ digits Malayalam Malayalam Show Vivid/Muted Visa livfull/dämpad Show Warm/Cool Visa varm/kall Show {kind} Brushes Visa {kind}-penslar - Show/hide plate (Alt-click: only this plate) Visa/dölj plåt (Alt-klick: endast den här plåten) + Show/hide plate (Alt-click: only this plate; Alt-click again: all plates) Visa/dölj plåt (Alt-klick: endast den här plåten; Alt-klick igen: alla plåtar) Show: Visa: Shown with the optimised preview. Visas med den optimerade förhandsgranskningen. Side 1: Sida 1: diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 910a7fc5b1..f72d2dd16c 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -3380,7 +3380,7 @@ digits Malayalam Malayalam Show Vivid/Muted Canlı/Sessiz Göster Show Warm/Cool Sıcak/Soğuk Göster Show {kind} Brushes {kind} Fırçalarını Göster - Show/hide plate (Alt-click: only this plate) Plakayı göster/gizle (Alt tuşuyla tıklayın: yalnızca bu plaka) + Show/hide plate (Alt-click: only this plate; Alt-click again: all plates) Plakayı göster/gizle (Alt tuşuyla tıklayın: yalnızca bu plaka; yeniden Alt tuşuyla tıklayın: tüm plakalar) Show: Göster: Shown with the optimised preview. Optimize edilmiş önizlemeyle gösterilir. Side 1: 1. Taraf: diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index dbd6d2609e..8e4105faf0 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -3630,7 +3630,7 @@ digits Malayalam Малаялам Show Vivid/Muted Показати яскраві/приглушені Show Warm/Cool Показати теплі/холодні Show {kind} Brushes Показати пензлі {kind} - Show/hide plate (Alt-click: only this plate) Показати/приховати пластину (Alt+клацання: тільки цю пластину) + Show/hide plate (Alt-click: only this plate; Alt-click again: all plates) Показати/приховати пластину (Alt+клацання: тільки цю пластину; повторне Alt+клацання: усі пластини) Show: Показати: Shown with the optimised preview. Показано оптимізованим переглядом. Side 1: Сторона 1: diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 519c5d8f0d..1cb163dd86 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -3996,7 +3996,7 @@ mark-style Japanese Kiểu Nhật Show Vivid/Muted Hiện màu sống động/tối Show Warm/Cool Hiện màu nóng/lạnh Show {kind} Brushes Hiện cọ {kind} - Show/hide plate (Alt-click: only this plate) Hiện/ẩn bản in (Alt-bấm: chỉ bản in này) + Show/hide plate (Alt-click: only this plate; Alt-click again: all plates) Hiện/ẩn bản in (Alt-bấm: chỉ bản in này; Alt-bấm lần nữa: tất cả bản in) Show: Hiện: Shown with the optimised preview. Hiển thị với bản xem trước được tối ưu hóa. Side 1: Mặt 1: diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index c6696a9ec6..822c1fba0f 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -3452,7 +3452,7 @@ digits Malayalam 马拉雅拉姆数字 Show Vivid/Muted 显示鲜艳/柔和 Show Warm/Cool 显示暖色/冷色 Show {kind} Brushes 显示{kind}画笔 - Show/hide plate (Alt-click: only this plate) 显示/隐藏色版 (Alt-单击:仅此色版) + Show/hide plate (Alt-click: only this plate; Alt-click again: all plates) 显示/隐藏色版 (Alt-单击:仅此色版;再次 Alt-单击:所有色版) Show: 显示: Shown with the optimised preview. 与优化预览一起显示。 Side 1: 侧边 1: diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 1480422931..3e6a88c04d 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -4771,7 +4771,7 @@ digits Malayalam 馬來亞拉姆數字 Show Vivid/Muted 顯示鮮豔/柔和 Show Warm/Cool 顯示暖色/冷色 Show {kind} Brushes 顯示{kind}筆刷 - Show/hide plate (Alt-click: only this plate) 顯示/隱藏色版 (Alt-按一下:僅此色版) + Show/hide plate (Alt-click: only this plate; Alt-click again: all plates) 顯示/隱藏色版 (Alt-按一下:僅此色版;再次 Alt-按一下:所有色版) Show: 顯示: Shown with the optimised preview. 於最佳化預覽時顯示。 Side 1: 側面 1: diff --git a/crates/ui-egui/src/panels/separations.rs b/crates/ui-egui/src/panels/separations.rs index bdb4210920..2b3e112c5f 100644 --- a/crates/ui-egui/src/panels/separations.rs +++ b/crates/ui-egui/src/panels/separations.rs @@ -1,5 +1,6 @@ //! Separations Preview panel: process plates C/M/Y/K plus spot plates with eye toggles (one visible -//! plate renders as greyscale ink coverage; Alt-click an eye to show only that plate), and the +//! plate renders as grayscale ink coverage; Alt-click an eye to show only that plate, and Alt-click +//! the eye of the plate shown alone to show every plate), and the //! colour-management controls behind Edit → Color Settings… / Assign Profile… and View → Proof //! Setup (working spaces, color management policies, intent, black-point compensation, proof //! target, gamut check). @@ -59,11 +60,11 @@ fn plates_section(app: &mut VectorcraftApp, ui: &mut Ui) { let vis = visible(&p.name); let mut clicked = false; ui.add_enabled_ui(on, |ui| { - clicked = widgets::toggle_icon(ui, "eye", vis, 18.0, tl!("Show/hide plate (Alt-click: only this plate)")); + clicked = + widgets::toggle_icon(ui, "eye", vis, 18.0, tl!("Show/hide plate (Alt-click: only this plate; Alt-click again: all plates)")); }); if clicked && on { - let key = if alt { "only" } else { "toggle" }; - run(app, "view.separationsPreview", json!({ key: p.name })); + run(app, "view.separationsPreview", eye_click(&p.name, alt)); } let (r, _) = ui.allocate_exact_size(vec2(14.0, 14.0), Sense::hover()); let q = |x: f32| (x.clamp(0.0, 1.0) * 255.0).round() as u8; @@ -75,6 +76,12 @@ fn plates_section(app: &mut VectorcraftApp, ui: &mut Ui) { }); } +/// The `view.separationsPreview` params for a click on plate `name`'s eye: with Alt, that plate +/// alone, or every plate when it already shows alone; without, the plate shown or hidden. +fn eye_click(name: &str, alt: bool) -> Value { + if alt { json!({"soloToggle": name}) } else { json!({"toggle": name}) } +} + /// A dropdown of the `kind` profiles after `extra` (a built-in entry, shown in the UI language); /// profile names are shown as they are. Returns the chosen name. pub(crate) fn profile_dropdown(ui: &mut Ui, id: &str, current: &str, kind: ProfileKind, extra: Option<&str>) -> Option<String> { @@ -345,6 +352,16 @@ mod tests { assert!(panel.iter().all(|(id, _)| cms::ProofTarget::parse(id).is_some_and(|t| t.id() == *id))); } + /// An Alt-click on a plate's eye sends `soloToggle`, which `view.separationsPreview` takes, and + /// a plain click sends `toggle`. + #[test] + fn an_alt_click_on_a_plates_eye_sends_solo_toggle() { + assert_eq!(eye_click("Cyan", true), json!({"soloToggle": "Cyan"})); + assert_eq!(eye_click("Brand Orange", false), json!({"toggle": "Brand Orange"})); + let spec = vectorcraft_engine::cmd::command_specs().iter().find(|c| c.id == "view.separationsPreview"); + assert!(spec.is_some_and(|c| c.params.contains("soloToggle?:"))); + } + /// Assign Profile's three choices: no profile, the working space assigned as the profile, or /// another profile; a choice the document already has runs nothing. #[test] diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index fb291b8525..a24a37d361 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -210,7 +210,7 @@ pub(crate) mod accessibility_tests { let tree = tree(|ui| { icon_button(ui, "link", "Constrain Proportions", true, 24.0); toggle_icon(ui, "eye", true, 18.0, "Show all plates"); - toggle_icon(ui, "eye", false, 18.0, "Show/hide plate (Alt-click: only this plate)"); + toggle_icon(ui, "eye", false, 18.0, "Show/hide plate (Alt-click: only this plate; Alt-click again: all plates)"); orientation_button(ui, false, true, "Portrait"); orientation_button(ui, true, false, "Landscape"); layout_button(ui, &[(0, 0), (1, 0)], true, "Grid by Row"); @@ -220,7 +220,7 @@ pub(crate) mod accessibility_tests { let off = |label| assert_eq!(role_and_state(&tree, label), (Role::Button, Some(Toggled::False)), "{label}"); on("Constrain Proportions"); on("Show all plates"); - off("Show/hide plate (Alt-click: only this plate)"); + off("Show/hide plate (Alt-click: only this plate; Alt-click again: all plates)"); on("Portrait"); off("Landscape"); on("Grid by Row"); diff --git a/docs/mcp.md b/docs/mcp.md index 092faabc4c..08296e15f3 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1169,6 +1169,13 @@ styles and brushes. `color.removeProfile`, `view.proofSetup`, `view.proofColors`, `view.overprintPreview`, `view.separationsPreview` and `swatch.setSpot` reject a param of the wrong type, such as `"bpc": "no"`, `"on": 1`, `"to": 5` or `"colors": "#fff"`, and change nothing. Omitting a param or giving null keeps its default. +`view.separationsPreview {soloToggle: plate}` is the Separations panel's Alt-click on a plate's eye: it shows that +plate alone, and when that plate is already the only one of the active document's plates shown, it shows every +plate, spot plates included ([Print color separations](https://helpx.adobe.com/illustrator/using/printing-color-separations.html) +describes the second Alt-click or Option-click on the eye bringing every separation back, and the first one showing +that plate alone). A hidden plate, another plate while one shows alone, or any plate while none is shown becomes +the only plate shown; these cases are VectorCraft's own rules. `only` always shows just the named plate, so +repeating it changes nothing. Neither adds an undo step. The Separations panel's Assign rows (where Edit › Assign Profile… goes) act on the profile of the document's color mode: Don't Color Manage This Document runs `edit.assignProfile` with null for that model (no profile, so the colors show through the working space), Working RGB or Working CMYK with the working space's name (that profile stays diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index e9fc9a6820..ca1c481321 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2064,6 +2064,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - The Place dialog has a Show Import Options checkbox after Link, Template and Replace ([Place multiple files in a document](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/import-other-file-types/place-multiple-files-in-a-document.html)). On (VectorCraft's default, saved with the preferences), each PDF, DXF or text file asks for its import options before it is placed, also in the place cursor; off (`file.place {showImportOptions: false}`), it is placed with the options last confirmed for its format, and only an encrypted PDF asks, for its password. Text Import Options now starts from the options confirmed last (`crates/ui-egui/src/tests/place.rs`). - A Shift-click with the loaded place cursor opens the current file's import options (text, DXF, PDF page or embedded PSD) and OK places it at the click, with Show Import Options on or off and for a cursor loaded by `file.place.queue` ([Place multiple files](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf)). VectorCraft's own rules: a file without such a dialog places as a click does, Cancel leaves the file unplaced, a Shift-drag places at the dragged size, and headless the Shift-click places as a click (`crates/tools/src/place.rs`, `crates/engine/src/tests/place.rs`, `crates/ui-egui/src/tests/place.rs`). - Separations Preview shows placed and embedded raster images on the visible plates, as it shows vector art (#4153): an RGB image's pixels are separated into process inks with the proof setup's intent, a CMYK image shows its own inks, a hidden plate's ink leaves the image, and with one plate visible the image shows that plate's ink as a grey. Raster images carry no spot ink, so a spot plate shown alone shows them as paper; a colorized image shows its color's plates. Emoji and other bitmap glyphs follow the same rule. The plate-filtered pixels and their reduced-size copies are kept apart from the image's own pixels, for each set of visible plates, proof setup and color settings, and with the preview off nothing changes. Evidence: `tests::colorize::separations_preview_shows_an_rgb_images_process_inks`, `separations_preview_shows_a_cmyk_images_own_inks`, `separations_preview_keeps_an_images_pixels_per_plate_set`. Print preview fidelity remains the open gap, so scores and hours are unchanged. + - In the Separations Preview panel, an Alt-click (Option-click on macOS) on the eye of the plate shown alone shows every plate again, spot plates included, as [the help page](https://helpx.adobe.com/illustrator/using/printing-color-separations.html) describes for a second modified click on the eye (`view.separationsPreview {soloToggle: plate}`); an Alt-click on a plate shown among others shows only that plate, as the help page describes for the first one. VectorCraft's own rules: an Alt-click on a hidden plate, on another plate while one shows alone or while no plate is shown shows only that plate, and `only` still shows just the named plate when repeated (`crates/engine/src/tests/colormgmt.rs`, `crates/ui-egui/src/panels/separations.rs`). - Desktop print transport uses `craft-print` for CUPS and modern Windows. Sheet composition, copies, separations and colour management remain in VectorCraft. The Print dialog's Media list also carries the Japanese papers — JIS B4 257 × 364 mm, JIS B5 182 × 257 mm and JIS B6 128 × 182 mm beside the ISO B4/B5 (250 × 353 and 176 × 250 mm, kept so settings and presets saved before them keep their paper), and はがき 100 × 148 mm, 往復はがき 148 × 200 mm, 封筒 長形3号 120 × 235 mm, 長形4号 90 × 225 mm, 角形2号 240 × 332 mm, 角形3号 216 × 277 mm and 四六判 127 × 188 mm; the JSON id or the dialog label names a paper, any case and spacing (`B5 (JIS)` or `b5jis`) (`crates/pdf/src/print/settings.rs`, `crates/pdf/src/tests/print.rs`). The print-preview and physical-device fidelity gaps remain, so print scores and hours are unchanged. - The Print dialog's Document Ink Options list shows an icon before each spot ink's name, and a click on it prints that one ink as process inks (on the Cyan, Magenta, Yellow and Black plates, with no plate of its own) or as a spot ink again, as [the help page](https://helpx.adobe.com/illustrator/using/printing-color-separations.html) describes for single spot colors. Other spot inks keep their plates, and spot gradient stops and DCS images' spot plates follow each ink's choice (`print.setup {settings: {output: {inks: [{name, convertToProcess: true}]}}}`, kept with the document and in print presets; `print.preview` lists every ink as `documentInks`). These are VectorCraft's own rules: Convert All Spot Colors to Process converts every spot ink and dims the icons while keeping each ink's own choice, a converted ink's Print, Frequency and Angle are dimmed and kept, and process inks and Registration have no icon. Evidence: `print::one_spot_ink_converts_to_process_and_the_others_keep_their_plates`, `print::converting_every_spot_ink_overrides_and_keeps_each_inks_own_choice`, `print::a_spot_gradient_stop_prints_its_process_plates`, `cmykimages::a_dcs_image_converts_only_the_spot_ink_chosen`, `tests::print::a_spot_ink_converted_to_process_is_saved_and_listed_without_a_plate`, `dialogs::tests_print::a_spot_inks_icon_converts_it_to_process_and_back`. Print scores and hours are unchanged. - The Print dialog's Output section has Overprint Black under Convert All Spot Colors to Process, off by default and available with Separations ([Print color separations](https://helpx.adobe.com/illustrator/using/printing-color-separations.html) lists it among the separation options): black art then leaves the inks under it on the other plates (`print.setup {settings: {output: {overprintBlack: true}}}`, kept with the document and in print presets). Solid 100% K or 100% gray fills, strokes and characters (to within half a percent, as Edit › Edit Colors › Overprint Black counts them), and gradients whose every stop (every color point of a freeform gradient) is, overprint; rich, RGB, Lab, spot-linked and lighter blacks are not marked, paints already set to overprint keep that setting, and only the printed copy is marked. These limits are VectorCraft's own rules. Characters set to overprint now also leave the inks below them on printed PDF plates, a type object's own fill in a PDF is drawn with its blending mode, and Edit › Edit Colors › Overprint Black counts a gradient with a stop linked to a spot swatch as a spot black, as it counts a solid one, and a freeform gradient by the color points it draws from. On a plate, an overprinting paint that puts none of that plate's ink down is drawn as nothing; on PostScript plates so is up to half a percent of another ink in a color that counts as black, and any other faint ink stays on the plate. Evidence: `print::overprint_black_keeps_the_inks_under_solid_black_on_separations`, `print::overprint_black_keeps_the_cyan_under_near_and_freeform_blacks_on_postscript_plates`, `print::overprinting_paints_keep_their_faint_ink_on_postscript_plates`, `print::overprinting_type_leaves_the_inks_below_on_separations`, `print::a_type_objects_own_black_fill_overprints_on_separations`, `tests::print::overprint_black_is_saved_with_the_setup_and_in_presets`, `overprint::tests::a_gradient_with_a_spot_linked_stop_is_black_only_with_spot`, `overprint::tests::a_freeform_gradient_is_black_when_every_point_is`. Print scores and hours are unchanged. From cc57835f8ff969527c0d561241c8d1450af95e4b Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 17 Nov 2026 10:42:53 -0800 Subject: [PATCH 113/176] Font menu: a new sample size keeps the list on its rows A size picked from inside the open menu changed the row height while the list kept its scroll offset in points, so the rows in view moved to other families. The list now keeps the same row at the top of its view at the new height. Screen readers find Small, Medium and Large as radio buttons in a group named Font Preview Size, with the current size chosen. Tests check both, and the module doc is rewrapped to the file's width. --- crates/ui-egui/src/font_menu.rs | 38 +++++++++++----- crates/ui-egui/src/font_menu/tests.rs | 65 +++++++++++++++++++++++++++ docs/target-app-parity.md | 2 +- 3 files changed, 94 insertions(+), 11 deletions(-) diff --git a/crates/ui-egui/src/font_menu.rs b/crates/ui-egui/src/font_menu.rs index 5e48887c61..07d7e7a5d0 100644 --- a/crates/ui-egui/src/font_menu.rs +++ b/crates/ui-egui/src/font_menu.rs @@ -15,9 +15,10 @@ //! Technology filter's Variable lists only variable font families. Preferences › Type › Enable //! in-menu font previews and Font Preview Size turn the samples off or size the rows. While the //! samples are shown, a row under the filters sets Font Preview Size to Small, Medium or Large -//! ([`apply_preview_size`]), which sizes the rows of every font menu. The menu lays -//! out its filters on the same five rows wherever it opens, with the size row under them while the -//! samples are shown. However narrow its field, it opens at least wide enough for those rows and for a family name up to 220 points wide with its sample +//! ([`apply_preview_size`]), which sizes the rows of every font menu, and the list stays on the +//! rows it showed. The menu lays out its filters on the same five rows wherever it opens, with the +//! size row under them while the samples are shown. However narrow its field, it opens at least +//! wide enough for those rows and for a family name up to 220 points wide with its sample //! beside it, up to 60% of the window; each sample fills its row's height. Recently used families //! appear first, in the order they were last applied, within the same search and filters as the //! remaining families. In the Character and Properties panels and the Control bar, @@ -467,6 +468,9 @@ struct MenuState { header: f32, /// The width of the widest row of filters without wrapping, last frame. filters: f32, + /// The rows' height last frame, and how far down the list its view began, in rows. At a new + /// height (Font Preview Size) the list scrolls back to the same row. + scrolled: Option<(f32, f32)>, /// The families the wheel steps through, listed at its first notch over the closed field and /// kept for that text selection while the pointer stays on it: each step makes its family a recent one, which would /// otherwise move it in the order. The Document filter's families are kept the same way: a @@ -1514,14 +1518,20 @@ fn filters(ui: &mut Ui, st: &mut MenuState, t: &Tokens, document: bool, row: Opt let gap = ui.spacing().item_spacing.x; let text = |s: &str| egui::RichText::new(s).size(FILTER_SIZE); let mut width = ui.label(text(tl!("Font Preview Size")).color(t.text_dim)).rect.width(); - for (size, height) in PREVIEW_SIZES { - let on = (height - row).abs() < 0.5; - let resp = ui.selectable_label(on, text(preview_size_label(size))); - width += gap + resp.rect.width(); - if resp.clicked() { - ui.data_mut(|d| d.insert_temp(preview_size_id(), size)); + // Screen readers find the three sizes in a radio group named after the row. + let group = egui::UiBuilder::new().accessibility_role(egui::accesskit::Role::RadioGroup).accessibility_label(tl!("Font Preview Size")); + ui.scope_builder(group, |ui| { + for (size, height) in PREVIEW_SIZES { + let on = (height - row).abs() < 0.5; + let label = preview_size_label(size); + let resp = ui.selectable_label(on, text(label)); + resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::RadioButton, true, on, label)); + width += gap + resp.rect.width(); + if resp.clicked() { + ui.data_mut(|d| d.insert_temp(preview_size_id(), size)); + } } - } + }); widest = widest.max(width); }); } @@ -1712,8 +1722,16 @@ fn rows(ui: &mut Ui, range: std::ops::Range<usize>, h: Listed<'_>, sample: Optio let place = egui::Rect::from_min_size(egui::pos2(left, top + i as f32 * row_h), vec2(width, row_h)); ui.scroll_to_rect_animation(place, align, egui::style::ScrollAnimation::none()); }; + // At a new row height (Font Preview Size, set from the menu), the view stays on the rows it + // showed: the scroll offset is in points. + let at = (ui.clip_rect().top() - top) / row_h; + let kept = st.scrolled.filter(|&(h, _)| !opening && (h - row_h).abs() > 0.5).map(|(_, at)| at); + st.scrolled = Some((row_h, kept.unwrap_or(at))); if let Some((i, align)) = scroll_target(st, &rows, opening, keyed) { scroll_to(ui, i, align); + } else if let Some(at) = kept { + let place = egui::Rect::from_min_size(egui::pos2(left, top + at * row_h), vec2(width, row_h)); + ui.scroll_to_rect_animation(place, Some(egui::Align::TOP), egui::style::ScrollAnimation::none()); } let mut chosen: Option<(String, Option<String>)> = None; let mut hovered: Option<usize> = None; diff --git a/crates/ui-egui/src/font_menu/tests.rs b/crates/ui-egui/src/font_menu/tests.rs index 2f06f9f41f..3ff86c5ace 100644 --- a/crates/ui-egui/src/font_menu/tests.rs +++ b/crates/ui-egui/src/font_menu/tests.rs @@ -1554,3 +1554,68 @@ fn a_preview_size_asked_for_sets_the_preference_and_keeps_the_preview() { "undo takes the type away: no step was added for the size" ); } + +/// Screen readers find Small, Medium and Large as radio buttons in a group named Font Preview +/// Size, with the size of the rows chosen. +#[test] +fn the_preview_size_row_is_a_radio_group_showing_the_size() { + use crate::widgets::accessibility_tests::{named, role_and_state, tree}; + use egui::accesskit::{Role, Toggled}; + // The bundled fonts alone: fonts that tests running alongside add stay out of the rows. + let db = vectorcraft_text::FontDb::with_font_dirs(vec![]); + let sizes = ["small", "medium", "large"]; + for size in sizes { + let mut st = super::MenuState::default(); + let look = super::MenuLook { row: super::preview_row(size), ..Default::default() }; + let nodes = tree(|ui| { + let _ = super::list_of(ui, &db, egui::Id::unique("size-group"), &mut st, "Inter", None, look); + }); + assert_eq!(named(&nodes, "Font Preview Size").role(), Role::RadioGroup, "at {size}"); + for other in sizes { + let chosen = if other == size { Toggled::True } else { Toggled::False }; + assert_eq!(role_and_state(&nodes, super::preview_size_label(other)), (Role::RadioButton, Some(chosen)), "{other} at {size}"); + } + } +} + +/// A new Font Preview Size chosen in the open menu keeps the list on the rows it showed: the +/// view starts the same number of rows down at the new height, not the same number of points. +#[test] +fn a_new_preview_size_keeps_the_list_on_its_rows() { + // The bundled fonts alone: fonts that tests running alongside add stay out of the rows. + let db = vectorcraft_text::FontDb::with_font_dirs(vec![]); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut st = super::MenuState::default(); + // One frame `height` points high at `size`: the list's offset, top, view height and content height. + let frame = |height: f32, size: &str, st: &mut super::MenuState| { + let area = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, height)); + let look = super::MenuLook { row: super::preview_row(size), ..Default::default() }; + let mut shown = None; + let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(area), ..Default::default() }, |ui| { + let mut child = ui.new_child(egui::UiBuilder::new().max_rect(area)); + // Opening on the last family scrolls the list to its end. + let list = super::list_of(&mut child, &db, egui::Id::unique("keep-rows"), st, "Source Serif 4", None, look); + shown = Some((list.state.clamped_offset().y, list.inner_rect.top(), list.inner_rect.height(), list.content_size.y)); + }); + out.textures_delta.clear(); + shown.unwrap_or_else(|| panic!("the list was not drawn")) + }; + let (_, top, _, _) = frame(900.0, "medium", &mut st); + // A fresh opening, with room for fewer rows than the list holds. + let mut st = super::MenuState::default(); + let mut medium = (0.0, 0.0, 0.0, 0.0); + for _ in 0..4 { + medium = frame(top + 64.0, "medium", &mut st); + } + let (offset, _, view, content) = medium; + assert!(content > view + 0.5 && offset > 0.5, "the list is scrolled: {medium:?}"); + let rows_down = offset / super::preview_row("medium"); + let mut large = (0.0, 0.0, 0.0, 0.0); + for _ in 0..3 { + large = frame(top + 64.0, "large", &mut st); + } + let expected = rows_down * super::preview_row("large"); + assert!((large.0 - expected).abs() < 0.5, "the view starts {rows_down} rows down: offset {} for {expected}", large.0); + super::wait_for_samples(&ctx); +} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index dddfbe44bf..760a270015 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1882,7 +1882,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur The font menu's Font Technology › Variable (under the kind filter, as [Find, apply, and adjust variable fonts](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/find-apply-and-adjust-variable-fonts.html) places Variable in the classification filter's Font Technology section) lists only the families with variation axes, a family with a variable file beside static ones included, and works together with the script, kind, ★ and search filters; it stays set from one opening to the next. Measured by `font_menu::tests::the_variable_filter_lists_only_variable_families`, `font_menu::tests::the_variable_filter_is_named_as_fonts_are`, `tests_axes::a_family_with_variation_axes_is_variable` and `tests_sysfonts::a_family_with_a_variable_file_beside_static_ones_is_variable`. The font menu's Document filter (beside ★) lists only the families that type in the current document is set in, as the quick filter for fonts used in the document does on the [font browser overview](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/font-options-overview.html). It works together with the search, script, kind, Variable and ★ filters, Recent Fonts and Show Similar Fonts, steers the closed field's wheel, follows edits and undo while the menu is open, and is shared by every font menu for the session like the other filters. VectorCraft's own rules: hidden, locked, masked, symbol, pattern and graph design type counts, styles no type uses do not, a composite font lists under its own name, a family the document names but this computer lacks is not listed (Find Font reports it), a document without available fonts lists nothing with its own message, and with no document open the filter is unavailable. Measured by `font_menu::tests::the_document_filter_lists_the_families_the_documents_type_uses`, `font_menu::tests::the_document_filter_combines_with_the_others_and_follows_edits`, `font_menu::tests::the_document_filter_counts_type_in_graph_designs` and `font_menu::tests::the_document_filter_on_an_empty_document_or_none`. The font menu's Recently Added filter (on its own row under Font Technology) lists only the installed families added in the last 30 days, the newest at the top, as the [user guide](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=486) and the [font browser overview](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/font-options-overview.html) describe it (`vectorcraft_text::FontDb::recently_added`). It works together with the search, script, kind, Variable, ★ and Document filters, lists only the families every active filter matches, steers the closed field's wheel, and is shared by every font menu for the session like the other filters. VectorCraft's own rules: a family is dated by the creation time of its newest font file on this computer (a file the file system keeps no creation time for, or one dated in the future, does not count), the 30th day is included, families added at the same instant are in name order, the recently used families appear in that order without the Recent Fonts section, Show Similar Fonts orders only the families the filter lists, a family leaves the list when its 30 days end while the menu is open, an empty list keeps the filter on and says no fonts match, and fonts bundled with the app or loaded from documents are never listed. Measured by `font_menu::tests::the_recently_added_filter_lists_new_families_newest_first`, `font_menu::tests::the_recently_added_filter_drops_families_as_their_30_days_end`, `font_menu::tests::the_recently_added_filter_lists_a_font_installed_just_now`, `tests::recently_added::families_added_in_the_last_30_days_are_listed_newest_first`, `tests::recently_added::a_family_is_dated_by_its_newest_valid_file` and `tests::sysfonts::installed_fonts_are_recently_added_by_their_files_creation_time`. - While the samples are shown, the font menu's row under the filters sets the sample size to Small, Medium or Large from inside the menu, as the [font browser overview](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/font-options-overview.html) and the [user guide](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=485) describe the sample size control; with Enable in-menu font previews off, the row is not shown, as the user guide describes. VectorCraft's own rules: the row sits under the filters and sets Preferences › Type › Font Preview Size (`fontPreviewSize`), so every font menu takes the new row height, the Composite Fonts and Dimension dialogs' included; the current size is selected and a click on it changes nothing; a saved value that is none of the three sizes shows Medium and a click replaces it; the change adds no undo step and leaves a font previewed on the selected type in place. Measured by `font_menu::tests::the_preview_size_row_asks_for_the_size_clicked` and `font_menu::tests::a_preview_size_asked_for_sets_the_preference_and_keeps_the_preview`. + While the samples are shown, the font menu's row under the filters sets the sample size to Small, Medium or Large from inside the menu, as the [font browser overview](https://helpx.adobe.com/illustrator/desktop/design-with-text/fonts-and-scripts/font-options-overview.html) and the [user guide](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=485) describe the sample size control; with Enable in-menu font previews off, the row is not shown, as the user guide describes. VectorCraft's own rules: the row sits under the filters and sets Preferences › Type › Font Preview Size (`fontPreviewSize`), so every font menu takes the new row height, the Composite Fonts and Dimension dialogs' included, and the open list stays on the rows it showed; the current size is selected and a click on it changes nothing; screen readers find the three sizes as radio buttons in a group named Font Preview Size; a saved value that is none of the three sizes shows Medium and a click replaces it; the change adds no undo step and leaves a font previewed on the selected type in place. Measured by `font_menu::tests::the_preview_size_row_asks_for_the_size_clicked`, `font_menu::tests::a_preview_size_asked_for_sets_the_preference_and_keeps_the_preview`, `font_menu::tests::the_preview_size_row_is_a_radio_group_showing_the_size` and `font_menu::tests::a_new_preview_size_keeps_the_list_on_its_rows`. The font database looks up a name that is neither a loaded nor an installed family among the other names of the loaded and installed fonts once for each style it is asked in, and keeps the answer until fonts are added or rescanned. Laying out a story of 1,000 paragraphs set in a font that is not installed, with 400 more fonts loaded, takes a median of 56 to 71 ms instead of 409 to 507 ms on Windows 11 (`CRAFT_FONTS_DIR=<craft-fonts checkout> cargo test --release -p vectorcraft-text --lib missing_font_story_layout_timing -- --ignored --nocapture`). A font family removed while the app runs leaves the font menus when the app scans the font folders again (when its window comes to the front after a font folder changed, or Refresh Font List), also when type had used it: that type then draws in the fallback font and Find Font lists the font as missing, until the font is installed again and the folders are scanned. - **Files (M4):** From 76078f1991ae03660ce5e55ac17dfe1feccd0cd8 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 17 Nov 2026 10:44:47 -0800 Subject: [PATCH 114/176] PDF import: a DeviceCMYK image in a PDF/X file opens with the output intent's profile A file whose catalog has a CMYK /GTS_PDFX output intent describes its DeviceCMYK colors with that intent's profile. A DeviceCMYK image in such a file now opens tagged with that profile, so a CMYK image that a PDF/X export writes as DeviceCMYK opens with its profile again. An image drawn where a /DefaultCMYK is in scope keeps no profile, since the default replaces DeviceCMYK there. The scope is read per image from the resources it is drawn with, and the image cache keeps the tagged and untagged reads apart. --- crates/pdf/src/import/builder.rs | 1 + crates/pdf/src/import/device.rs | 10 ++- crates/pdf/src/import/entry.rs | 4 ++ crates/pdf/src/import/state.rs | 3 + crates/pdf/src/import_image.rs | 34 ++++++++-- crates/pdf/src/import_scan.rs | 15 +++++ crates/pdf/src/tests/cmykimages.rs | 102 +++++++++++++++++++++++++++-- docs/mcp.md | 5 +- 8 files changed, 160 insertions(+), 14 deletions(-) diff --git a/crates/pdf/src/import/builder.rs b/crates/pdf/src/import/builder.rs index a9cd9ada7c..eb8742f2db 100644 --- a/crates/pdf/src/import/builder.rs +++ b/crates/pdf/src/import/builder.rs @@ -43,6 +43,7 @@ impl<'p> Builder<'p> { image_keys: HashMap::new(), raster_scales: HashMap::new(), cmyk_keys: HashSet::new(), + intent_cmyk: None, separation_paints: HashMap::new(), opaque: HashSet::new(), warnings: vec![], diff --git a/crates/pdf/src/import/device.rs b/crates/pdf/src/import/device.rs index 3fcefd7b8e..97c4fddb65 100644 --- a/crates/pdf/src/import/device.rs +++ b/crates/pdf/src/import/device.rs @@ -1,4 +1,4 @@ -use super::entry::{INVISIBLE_TEXT_NOTE, MAX_NESTED, OUTLINED_TEXT_NOTE, UNSORTED, WHITE_KEY}; +use super::entry::{INTENT_KEY, INVISIBLE_TEXT_NOTE, MAX_NESTED, OUTLINED_TEXT_NOTE, UNSORTED, WHITE_KEY}; use super::state::{ Builder, Decoded, Frame, FrameKind, GlyphRun, blend, fill_rule, gray_png, line_width, mean_scale, resize_alpha, rgba_png, same_outline, stroke_layer, stroke_outline, @@ -242,8 +242,11 @@ impl<'a> Device<'a> for Builder<'_> { match image { Image::Raster(r) => { let white = self.white_images; + // A DeviceCMYK image takes the output intent's profile only where no DefaultCMYK + // replaces DeviceCMYK, so it is cached apart from the same image drawn where one does. + let intent = !white && self.intent_cmyk.is_some() && self.scan.cmyk_defaults.get(&r.stream().dict().obj_id()) == Some(&false); // Inside an alpha mask the same image is read again, white (its own cache key). - let key = craft_pdf::interpret::CacheKey::cache_key(&r) ^ if white { WHITE_KEY } else { 0 }; + let key = craft_pdf::interpret::CacheKey::cache_key(&r) ^ if white { WHITE_KEY } else { 0 } ^ if intent { INTENT_KEY } else { 0 }; let st = r.stream(); let (w, h) = (r.width(), r.height()); // CMYK images keep their samples (read once per image). @@ -251,7 +254,8 @@ impl<'a> Device<'a> for Builder<'_> { let cmyk = if known || white { None } else { - crate::import_image::cmyk(st, w, h).unwrap_or_else(|why| { + let intent = self.intent_cmyk.as_deref().filter(|_| intent); + crate::import_image::cmyk(st, w, h, intent).unwrap_or_else(|why| { self.warn(why); None }) diff --git a/crates/pdf/src/import/entry.rs b/crates/pdf/src/import/entry.rs index 8f84b9a332..5b945c6b25 100644 --- a/crates/pdf/src/import/entry.rs +++ b/crates/pdf/src/import/entry.rs @@ -9,6 +9,9 @@ use super::{ /// Mixed into an image's cache key when it is read white inside an alpha soft mask. pub(super) const WHITE_KEY: u128 = 0x7717_e000_a1fa; +/// Mixed into an image's cache key when a DeviceCMYK image there takes the output intent's profile. +pub(super) const INTENT_KEY: u128 = 0x1e7e_0c3c_0b5a; + /// The name of the paths text imports as. pub(super) const TEXT_OUTLINES: &str = "<Text Outlines>"; @@ -281,6 +284,7 @@ fn read_opened( b.unsure = route && ocgs.list.iter().any(|g| (all_on && !g.on) || !g.print); b.taken = taken; b.warnings = notes; + b.intent_cmyk = crate::import_image::output_intent_cmyk(pdf); b.colors.uncalibrated_rgb = opts.uncalibrated_rgb && picked.iter().filter_map(|&n| pages.get(n)).any(crate::pages::has_private_data); let cache = InterpreterCache::new(); let mut x = 0.0; diff --git a/crates/pdf/src/import/state.rs b/crates/pdf/src/import/state.rs index 1eeb8a5539..b5f9ed0895 100644 --- a/crates/pdf/src/import/state.rs +++ b/crates/pdf/src/import/state.rs @@ -103,6 +103,9 @@ pub(super) struct Builder<'p> { pub(super) raster_scales: HashMap<u128, (f32, f32)>, /// The images kept with their CMYK samples ([`crate::import_image`]). pub(super) cmyk_keys: HashSet<u128>, + /// The file's PDF/X output intent profile of CMYK, which DeviceCMYK images are tagged with + /// ([`crate::import_image::output_intent_cmyk`]). + pub(super) intent_cmyk: Option<Vec<u8>>, /// Images in a Separation space, by key: the paint of their ink, or `None` when they open in /// RGB (an ink that can't be told, tints that can't be read). pub(super) separation_paints: HashMap<u128, Option<Paint>>, diff --git a/crates/pdf/src/import_image.rs b/crates/pdf/src/import_image.rs index cafae6d448..ecab9e6e08 100644 --- a/crates/pdf/src/import_image.rs +++ b/crates/pdf/src/import_image.rs @@ -5,15 +5,17 @@ //! ([`ImageBlob::cmyk_tiff`]). An ICC-based image keeps the CMYK profile its color space holds //! ([`icc_profile`]): the TIFF carries it, and a kept JPEG carries it in place of its own //! ([`jpeg_with_icc`]), or, when its segments can't hold it, is stored as a CMYK TIFF carrying it. +//! In a file with a PDF/X output intent of CMYK, a DeviceCMYK image keeps that intent's profile +//! the same way ([`output_intent_cmyk`]), since the intent describes DeviceCMYK there. //! A mask (`/SMask`, `/Mask`) doesn't change that: the importer //! carries it as the image's opacity mask ([`has_mask`]). A DeviceN image of process plates only //! keeps them the same way, as a CMYK image ([`process_devicen`]). An image of one ink (a //! Separation, or a DeviceN of one colorant) keeps it: its tints are read as a grayscale image //! ([`tint_gray`]) that the ink colorizes. Every other image is read as RGB by the interpreter. -use craft_pdf::syntax::Filter; use craft_pdf::syntax::object::stream::{ImageColorSpace, ImageDecodeParams}; use craft_pdf::syntax::object::{Array, Dict, Name, Stream}; +use craft_pdf::syntax::{Filter, Pdf}; use vectorcraft_doc::ImageBlob; use vectorcraft_doc::cmyk::{Inks, MAX_CMYK_PIXELS, jpeg_components, jpeg_with_icc}; @@ -55,7 +57,11 @@ fn icc_profile(d: &Dict<'_>) -> Option<Vec<u8>> { if it.next::<Name<'_>>()?.as_ref() != b"ICCBased" { return None; } - let s = it.next::<Stream<'_>>()?; + cmyk_profile(&it.next::<Stream<'_>>()?) +} + +/// The four-component CMYK profile stream `s` holds, when an image can be tagged with it. +fn cmyk_profile(s: &Stream<'_>) -> Option<Vec<u8>> { if s.dict().get::<u8>(b"N") != Some(4) { return None; } @@ -64,6 +70,23 @@ fn icc_profile(d: &Dict<'_>) -> Option<Vec<u8>> { valid_icc(&icc, *b"CMYK").then(|| icc.into_owned()) } +/// The CMYK profile of the catalog's PDF/X output intent (`/S /GTS_PDFX` with a four-component +/// `DestOutputProfile`), which DeviceCMYK colors are in. `None` without one. +pub(crate) fn output_intent_cmyk(pdf: &Pdf) -> Option<Vec<u8>> { + let xref = pdf.xref(); + let intents = xref.get::<Dict<'_>>(xref.root_id())?.get::<Array<'_>>(b"OutputIntents")?; + let pdfx = intents.iter::<Dict<'_>>().take(MAX_INTENTS).find(|i| i.get::<Name<'_>>(b"S").is_some_and(|s| s.as_ref() == b"GTS_PDFX"))?; + cmyk_profile(&pdfx.get::<Stream<'_>>(b"DestOutputProfile")?) +} + +/// The output intents read before giving up on finding the PDF/X one. +const MAX_INTENTS: usize = 16; + +/// Is the image's color space DeviceCMYK (or its inline abbreviation)? +fn device_cmyk(d: &Dict<'_>) -> bool { + d.get::<Name<'_>>(key(d, b"ColorSpace", b"CS")).is_some_and(|n| matches!(n.as_ref(), b"DeviceCMYK" | b"CMYK")) +} + /// Each component's Decode range (`[0 1]` each when the array is missing or malformed). fn decode_ranges(d: &Dict<'_>) -> [(f32, f32); 4] { let mut out = [(0.0, 1.0); 4]; @@ -78,14 +101,15 @@ fn decode_ranges(d: &Dict<'_>) -> [(f32, f32); 4] { } /// The image `st` (`width` × `height` pixels) in CMYK: `Ok(None)` when it isn't a CMYK image, -/// `Err` (a warning) when it is one that is read as RGB. -pub(crate) fn cmyk(st: &Stream<'_>, width: u32, height: u32) -> Result<Option<ImageBlob>, &'static str> { +/// `Err` (a warning) when it is one that is read as RGB. `intent` is the file's PDF/X output intent +/// profile of CMYK ([`output_intent_cmyk`]), which a DeviceCMYK image is tagged with. +pub(crate) fn cmyk(st: &Stream<'_>, width: u32, height: u32, intent: Option<&[u8]>) -> Result<Option<ImageBlob>, &'static str> { let d = st.dict(); if !cmyk_space(d) { return process_devicen(st, width, height); } let ranges = decode_ranges(d); - let icc = icc_profile(d); + let icc = icc_profile(d).or_else(|| intent.filter(|_| device_cmyk(d)).map(<[u8]>::to_vec)); let filters = st.filters(); if ranges == INVERTED && matches!(filters.as_slice(), [Filter::DctDecode]) { let raw = st.raw_data(); diff --git a/crates/pdf/src/import_scan.rs b/crates/pdf/src/import_scan.rs index b65254eafa..b68bfb9207 100644 --- a/crates/pdf/src/import_scan.rs +++ b/crates/pdf/src/import_scan.rs @@ -280,6 +280,10 @@ pub(crate) struct Scan { /// Something overprints with overprint mode 0, where a `DeviceCMYK` colour's zero components /// knock out; the document's overprint is the nonzero one (mode 1). pub zero_mode: bool, + /// The images the page draws (image XObjects by object, inline images as `None`), each with + /// whether it is drawn where a `/DefaultCMYK` is in scope, which replaces DeviceCMYK there + /// (ISO 32000-2 §8.6.5.6). An image drawn both ways is `true`. + pub cmyk_defaults: HashMap<Option<ObjectIdentifier>, bool>, /// The colorant names of the Separation and DeviceN spaces the page sets (`cs`, `CS`), and of /// those of the shading patterns it sets (`scn`, `SCN`) and of the shadings it draws (`sh`), /// each once (none when the page uses more than [`MAX_INKS`] inks or changes ink more than @@ -710,6 +714,12 @@ impl Walker<'_, '_> { } } + /// An image drawn with `res` in scope, as the interpreter looks up its `/DefaultCMYK`. + fn drawn_image(&mut self, id: Option<ObjectIdentifier>, res: &Resources<'_>) { + let default = res.get_color_space(&Name::new_unescaped(b"DefaultCMYK")).is_some(); + *self.out.cmyk_defaults.entry(id).or_default() |= default; + } + fn walk(&mut self, data: &[u8], res: &Resources<'_>, depth: u32) { let mut iter = TypedIter::new(data); self.note_fonts(res); @@ -874,12 +884,17 @@ impl Walker<'_, '_> { | TypedInstruction::ShowTexts(_) | TypedInstruction::NextLineAndShowText(_) | TypedInstruction::ShowTextWithParameters(_) => self.shown(), + TypedInstruction::InlineImage(_) => self.drawn_image(None, res), TypedInstruction::XObject(x) => { if !self.is_visible() { continue; } let Some(s) = res.get_x_object(x.0) else { continue }; let d = s.dict(); + if d.get::<Name<'_>>(b"Subtype").as_deref() == Some(b"Image") { + self.drawn_image(d.obj_id(), res); + continue; + } if d.get::<Name<'_>>(b"Subtype").as_deref() != Some(b"Form") || d.get::<[f32; 4]>(b"BBox").is_none() { continue; } diff --git a/crates/pdf/src/tests/cmykimages.rs b/crates/pdf/src/tests/cmykimages.rs index af3b5f313c..ec157a8182 100644 --- a/crates/pdf/src/tests/cmykimages.rs +++ b/crates/pdf/src/tests/cmykimages.rs @@ -36,21 +36,33 @@ fn stream(dict: &str, data: &[u8]) -> Vec<u8> { /// A 300 × 100 pt page with a CMYK rectangle and image XObjects `images` (dictionary entries /// after the type, stream data), 50 pt wide each: objects 5…, then the `extra` objects. fn pdf_with_images(images: &[(String, Vec<u8>)], extra: &[Vec<u8>]) -> Vec<u8> { + pdf_with(images, extra, "", "") +} + +/// [`pdf_with_images`] with `catalog` added to the catalog's entries and `resources` to the +/// page's resources. +fn pdf_with(images: &[(String, Vec<u8>)], extra: &[Vec<u8>], catalog: &str, resources: &str) -> Vec<u8> { let xobjects: String = (0..images.len()).map(|i| format!("/Im{i} {} 0 R ", 5 + i)).collect(); let mut content = String::from("0 1 0.6 0.2 k 0 80 300 20 re f\n"); for i in 0..images.len() { content.push_str(&format!("q 50 0 0 50 {} 10 cm /Im{i} Do Q\n", 10 + 60 * i)); } let mut objs = vec![ - b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(), + format!("<< /Type /Catalog /Pages 2 0 R {catalog}>>").into_bytes(), b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_vec(), - format!("<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 100] /Resources << /XObject << {xobjects}>> >> /Contents 4 0 R >>").into_bytes(), + format!("<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 100] /Resources << /XObject << {xobjects}>> {resources}>> /Contents 4 0 R >>") + .into_bytes(), stream("", content.as_bytes()), ]; for (dict, data) in images { objs.push(stream(&format!("/Type /XObject /Subtype /Image {dict}"), data)); } objs.extend_from_slice(extra); + pdf_of(&objs) +} + +/// A PDF file of `objs`, numbered from 1, whose catalog is object 1. +fn pdf_of(objs: &[Vec<u8>]) -> Vec<u8> { let mut out = b"%PDF-1.4\n".to_vec(); let mut at = vec![]; for (i, o) in objs.iter().enumerate() { @@ -179,12 +191,14 @@ fn a_cmyk_jpeg_passes_through_open_and_every_pdf_export() { assert!(out.warnings.iter().all(|w| !w.contains("image")), "{settings}: {:?}", out.warnings); // And open again: the same JPEG, carrying the profile it was written in when it was // ICC-based. + // ICC-based, or DeviceCMYK in a PDF/X file, whose output intent's profile it then carries. let back = import(&out.bytes).unwrap(); let blob = blobs(&back)[0]; - if icc_n.is_some() { + let intent = settings.get("standard").is_some().then(|| cms::icc_bytes(&cms::active_settings().cmyk).unwrap().to_vec()); + if let Some(icc) = w[0].icc.clone().or(intent) { assert_eq!(blob.mime, "image/jpeg", "{settings}"); assert_eq!(blob.cmyk(), b[0].cmyk(), "{settings}: the same samples"); - assert_eq!(blob.cmyk_icc_profile(), w[0].icc, "{settings}: the profile it was written in"); + assert_eq!(blob.cmyk_icc_profile().as_deref(), Some(&*icc), "{settings}: the profile it was written in"); } else { assert_eq!(blob.bytes.as_slice(), jpg.as_slice(), "{settings}"); } @@ -677,6 +691,86 @@ fn a_cmyk_image_in_the_output_intents_profile_is_device_cmyk() { assert!(w.space == "ICCBased" && w.icc.as_deref() == Some(&*working), "{w:?}"); } +/// A DeviceCMYK image in a file with a PDF/X output intent of CMYK opens tagged with the intent's +/// profile, so a CMYK image written as DeviceCMYK in that profile opens with it again. Without an +/// output intent it opens untagged. +#[test] +fn a_device_cmyk_image_opens_with_the_pdfx_output_intents_profile() { + let ink = [0u8, 102, 255, 0]; + let working = cms::icc_bytes(&cms::active_settings().cmyk).unwrap(); + for (s, tagged) in [(json!({"standard": "pdfX4"}), true), (json!({"standard": "pdfX3"}), true), (json!({}), false)] { + let d = image_doc(cmyk_tiff_with(ink, 4, 4, &working), 4, 4); + let out = export_with_report(&d, &opts(s.clone())).unwrap_or_else(|e| panic!("{s}: {e}")); + let w: Vec<Written> = written(&out.bytes).into_iter().filter(|w| w.space != "DeviceGray").collect(); + assert!(w.len() == 1 && w[0].space == "DeviceCMYK", "{s}: {w:?}"); + let opened = import(&out.bytes).unwrap(); + let icc = blobs(&opened)[0].cmyk_icc_profile(); + assert_eq!(icc.as_deref(), tagged.then_some(&*working), "{s}"); + } +} + +/// In a file whose catalog has a CMYK `/GTS_PDFX` output intent, a DeviceCMYK image opens tagged +/// with the intent's profile; another kind of output intent tags nothing, and neither does the +/// intent on a page whose resources replace DeviceCMYK with a `/DefaultCMYK`. +#[test] +fn a_device_cmyk_image_takes_the_output_intent_unless_a_default_cmyk_replaces_it() { + let (intent, other) = (cmyk_profile(|_| {}), cms::icc_bytes(&cms::active_settings().cmyk).unwrap().to_vec()); + assert_ne!(intent, other); + let image = [(cmyk_dict(2, 2, ""), flat([0, 102, 255, 0], 4))]; + let profiles = [stream("/N 4", &intent), stream("/N 4", &other)]; + let pdfx = "/OutputIntents [<< /Type /OutputIntent /S /GTS_PDFX /OutputConditionIdentifier (Test) /DestOutputProfile 6 0 R >>] "; + let pdfa = "/OutputIntents [<< /Type /OutputIntent /S /GTS_PDFA1 /OutputConditionIdentifier (Test) /DestOutputProfile 6 0 R >>] "; + let default_cmyk = "/ColorSpace << /DefaultCMYK [/ICCBased 7 0 R] >> "; + for (catalog, resources, expected) in [(pdfx, "", Some(&intent)), ("", "", None), (pdfa, "", None), (pdfx, default_cmyk, None)] { + let d = import(&pdf_with(&image, &profiles, catalog, resources)).unwrap(); + let b = blobs(&d); + assert_eq!(b.len(), 1, "{catalog} {resources}"); + assert_eq!(b[0].cmyk().unwrap().data, flat([0, 102, 255, 0], 4), "{catalog} {resources}: the inks as they were"); + assert_eq!(b[0].cmyk_icc_profile().as_deref(), expected.map(Vec::as_slice), "{catalog} {resources}"); + } +} + +/// A `/DefaultCMYK` stops the output intent from tagging a DeviceCMYK image only where it is in +/// scope: on the page's own image when only a form on the page has one, the image keeps the +/// intent's profile; drawn inside that form, it opens untagged; and the same image drawn on a page +/// with a `/DefaultCMYK` and then on a page without one opens untagged on the first and tagged on +/// the second. +#[test] +fn the_output_intent_tags_a_device_cmyk_image_only_where_no_default_cmyk_is_in_scope() { + let (intent, other) = (cmyk_profile(|_| {}), cms::icc_bytes(&cms::active_settings().cmyk).unwrap().to_vec()); + let default = "/ColorSpace << /DefaultCMYK [/ICCBased 8 0 R] >>"; + // Objects: 1 catalog, 2 pages, 3 and 4 the pages, 5 their content, 6 the image, 7 and 8 the + // profiles, 9 a form with a `/DefaultCMYK`. + let file = |pages: &[&str], content: &str, form: &str| { + let kids: String = (0..pages.len()).map(|i| format!("{} 0 R ", 3 + i)).collect(); + let page = |res: &str| format!("<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 100] /Resources << {res} >> /Contents 5 0 R >>").into_bytes(); + let form_dict = format!("/Type /XObject /Subtype /Form /BBox [0 0 1 1] /Resources << /XObject << /Im0 6 0 R >> {default} >>"); + pdf_of(&[ + b"<< /Type /Catalog /Pages 2 0 R /OutputIntents [<< /Type /OutputIntent /S /GTS_PDFX /OutputConditionIdentifier (Test) /DestOutputProfile 7 0 R >>] >>".to_vec(), + format!("<< /Type /Pages /Kids [{kids}] /Count {} >>", pages.len()).into_bytes(), + page(pages[0]), + page(pages.get(1).copied().unwrap_or("")), + stream("", content.as_bytes()), + stream(&format!("/Type /XObject /Subtype /Image {}", cmyk_dict(2, 2, "")), &flat([0, 102, 255, 0], 4)), + stream("/N 4", &intent), + stream("/N 4", &other), + stream(&form_dict, form.as_bytes()), + ]) + }; + let image = "q 50 0 0 50 10 10 cm /Im0 Do Q "; + let form = "q 50 0 0 50 80 10 cm /Fm0 Do Q "; + let cases = [ + (file(&["/XObject << /Im0 6 0 R /Fm0 9 0 R >>"], &format!("{image}{form}"), "0 0 0 1 k 0 0 1 1 re f"), vec![Some(&intent)]), + (file(&["/XObject << /Fm0 9 0 R >>"], form, "/Im0 Do"), vec![None]), + (file(&[&format!("/XObject << /Im0 6 0 R >> {default}"), "/XObject << /Im0 6 0 R >>"], image, ""), vec![None, Some(&intent)]), + ]; + for (i, (bytes, expected)) in cases.into_iter().enumerate() { + let d = import(&bytes).unwrap(); + let profiles: Vec<Option<Vec<u8>>> = all_images(&d).iter().map(|b| b.cmyk_icc_profile().map(|p| p.to_vec())).collect(); + assert_eq!(profiles, expected.into_iter().map(|p| p.cloned()).collect::<Vec<_>>(), "case {i}"); + } +} + /// With Don't Include Profiles set, a CMYK JPEG kept as it is is DeviceCMYK without its own /// `ICC_PROFILE` segments, its compressed inks unchanged; one resampled and compressed again is /// written without a profile too. Left unset, the JPEG data stays as it is. diff --git a/docs/mcp.md b/docs/mcp.md index a3fa36ce1f..a8e5630397 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1450,8 +1450,9 @@ Imported colours keep their model: DeviceCMYK and CMYK ICC colours stay CMYK (a file painted mostly in CMYK opens as a CMYK document), DeviceGray is Gray, and Separation and DeviceN inks become spot swatches the art links to at its tint (gradient stops too). CMYK images (DeviceCMYK, or ICC-based with four components) keep their ink amounts: a CMYK JPEG as it is, any other as a CMYK TIFF -(masked CMYK images, and ones with 1, 2 or 4 bits per sample, open in RGB with a warning). Placing a CMYK TIFF keeps it -CMYK too. +(masked CMYK images, and ones with 1, 2 or 4 bits per sample, open in RGB with a warning). In a file with a CMYK +`/GTS_PDFX` output intent, a DeviceCMYK image carries the output intent's profile, except where it is drawn with a +`/DefaultCMYK` in the resources in scope. Placing a CMYK TIFF keeps it CMYK too. `colorMode: "rgb" | "cmyk"` opens any file in that mode instead, its colours converted as `file.documentColorMode` does (`grays` too): From ba3c7197f7df674eb57216d063fe968d929bdc98 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 17 Nov 2026 10:34:14 -0800 Subject: [PATCH 115/176] Twist: preserve boundary tangents --- crates/doc/src/live/warp.rs | 40 +++++++++++++++++++++++++++++------ crates/effects/src/catalog.rs | 8 ++++++- crates/effects/src/tests.rs | 22 +++++++++++++++++++ docs/mcp.md | 3 +++ docs/target-app-parity.md | 2 ++ 5 files changed, 67 insertions(+), 8 deletions(-) diff --git a/crates/doc/src/live/warp.rs b/crates/doc/src/live/warp.rs index dd48e8ef65..3257b0fee6 100644 --- a/crates/doc/src/live/warp.rs +++ b/crates/doc/src/live/warp.rs @@ -508,8 +508,8 @@ pub fn map_smooth_within(path: &PathData, max_piece: f64, max: usize, f: impl Fn map_pieces_within(path, max_piece, max, &f, |p, h| mapped_handle(&f, p, h)) } -/// Handle `h` of point `p` mapped through `f`: `f(p)` plus `f`'s derivative at `p` along `h - p` -/// (a central difference), so the image curve leaves `f(p)` the way `f` takes the curve. +/// The mapped handle uses `f`'s derivative at `p` toward `h`, computed with a second-order +/// one-sided difference. fn mapped_handle(f: &impl Fn(Point) -> Point, p: Point, h: Point) -> Point { let v = h - p; let len = v.hypot(); @@ -517,13 +517,23 @@ fn mapped_handle(f: &impl Fn(Point) -> Point, p: Point, h: Point) -> Point { if len.is_nan() || len <= 0.0 || len.is_infinite() { return f(p); } - // A thousandth of the handle, or more where the coordinates are so large that so short a - // step would round away (#7069): the samples stay a billionth of the coordinates apart, and - // at most at the handle's own end. + // The step grows with the coordinates when a thousandth of the handle would round away. + // Both samples lie between the anchor and the handle. let size = p.x.abs().max(p.y.abs()).max(1.0); let step = (1e-3f64).max(size * 1e-9 / len).min(1.0); - let d = (f(p + v * step) - f(p - v * step)) / (2.0 * step); - f(p) + d + let at = f(p); + let midpoint = p + v * (step * 0.5); + let sample = p + v * step; + let far = f(sample) - at; + let near_offset = midpoint - p; + let far_offset = sample - p; + let uneven = (near_offset * 2.0 - far_offset).hypot() > far_offset.hypot() * 1e-6; + // The second-order formula requires evenly spaced samples. + if midpoint == p || midpoint == sample || uneven { + return at + far / step; + } + let near = f(midpoint) - at; + at + (near * 4.0 - far) / step } /// [`map_nonlinear_within`]'s pieces, with `handle(point, handle)` giving each mapped handle. @@ -613,3 +623,19 @@ pub(super) fn resample(poly: &[Point], m: usize) -> Vec<Point> { } out } + +#[cfg(test)] +mod handle_tests { + use super::*; + + #[test] + fn a_midpoint_rounded_to_an_endpoint_keeps_the_handle_direction() { + for x in [1e16, 1e16 + 2.0, -1e16] { + for offset in [-6.0, -2.0, 2.0, 6.0] { + let p = Point::new(x, 0.0); + let h = Point::new(x + offset, 0.0); + assert_eq!(mapped_handle(&|point| point, p, h), h); + } + } + } +} diff --git a/crates/effects/src/catalog.rs b/crates/effects/src/catalog.rs index ea727b804c..91c709add6 100644 --- a/crates/effects/src/catalog.rs +++ b/crates/effects/src/catalog.rs @@ -277,7 +277,13 @@ pub fn effect_catalog() -> Vec<EffectInfo> { "{h: amount (10), v: amount (10), relative: bool (true: % of size), anchors: bool (true), in: bool (true), out: bool (true), seed: int (0)}", json!({"h": 10.0, "v": 10.0, "relative": true, "anchors": true, "in": true, "out": true, "seed": 0}), ), - g("distort.twist", "Twist…", DT, "{angle: deg (-3600..3600, 10)}", json!({"angle": 10.0})), + g( + "distort.twist", + "Twist…", + DT, + "{angle: deg (-3600..3600, 10)} Outer-circle anchors stay fixed; their handles follow the inward tangent.", + json!({"angle": 10.0}), + ), g( "distort.zigZag", "Zig Zag…", diff --git a/crates/effects/src/tests.rs b/crates/effects/src/tests.rs index 52b38f986d..994f69745c 100644 --- a/crates/effects/src/tests.rs +++ b/crates/effects/src/tests.rs @@ -1708,6 +1708,28 @@ fn twist_joins_its_pieces_smoothly() { } } +#[test] +fn twist_boundary_handles_follow_the_inward_tangent() { + let line = PathData::single(SubPath::polyline(&[Point::new(40.0, 30.0), Point::new(60.0, 30.0)], false)); + let bounds = Rect::new(40.0, 30.0, 60.0, 30.0); + for angle in [90.0_f64, 400.0, -720.0] { + let out = apply_geometry(&[fx("distort.twist", json!({"angle": angle}))], &line, bounds); + let anchors = &out.subpaths[0].anchors; + let start = anchors.first().unwrap(); + let end = anchors.last().unwrap(); + assert_eq!(start.p, Point::new(40.0, 30.0)); + assert_eq!(end.p, Point::new(60.0, 30.0)); + for (actual, expected) in [ + (start.h_out - start.p, vectorcraft_geom::Vec2::new(1.0, -angle.to_radians())), + (end.h_in - end.p, vectorcraft_geom::Vec2::new(-1.0, angle.to_radians())), + ] { + assert!(actual.hypot() > 1e-9); + let error = (actual.x * expected.y - actual.y * expected.x).atan2(actual.dot(expected)).to_degrees().abs(); + assert!(error < 0.05, "{angle} degrees: boundary tangent differs by {error} degrees"); + } + } +} + #[test] fn twist_fixes_the_outer_circle_and_rotates_inside() { let out = run("distort.twist", json!({"angle": 0}), &square()); diff --git a/docs/mcp.md b/docs/mcp.md index 092faabc4c..0c76252eb4 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -809,6 +809,9 @@ stroke instead of the whole object: `run_command effect.apply {"effect": "path.o `effect.remove`, `effect.setParams` (`visible` toggles one) and `effect.duplicate` address that item's effects; `apply_effect` uses the active item. `effect.list` reports each object's item effects under `applied[].items`. +`distort.twist` keeps anchors on its outer circle fixed. Their handles follow the tangent of the +rotation inside that circle, including for positive and negative angles. + On a path directly inside a graph series, `appearance.setItem`, `appearance.addFill`, `appearance.addStroke`, `appearance.removeItem`, `appearance.moveItem`, `appearance.duplicateItem`, `appearance.clear`, `appearance.reduceToBasic`, `appearance.showAllHidden`, `appearance.transfer`, `appearance.copyFrom`, `paint.default`, diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index e9fc9a6820..2eb2ae3de8 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -588,6 +588,8 @@ since 2026-10-01. ## Evidence: what ships today, by area +- Twist keeps boundary handles tangent to the rotation inside its outer circle. Regressions cover 90, 400, and -720 degree twists, unchanged boundary anchors, and a sampling midpoint that rounds to an endpoint at large coordinates (`twist_boundary_handles_follow_the_inward_tangent` and `a_midpoint_rounded_to_an_endpoint_keeps_the_handle_direction`). + - **Recolor picker follow-up (#8031/#4028):** native Lab numeric entry, document/loaded-library swatches in the Color Picker, and Assign-row Pick from Swatches / Limit to Library menus. #4090 provided the double-click picker and #5113 the Assign sliders. Regression tests `native_lab_entry_in_color_picker` and `row_context_menu_pick_from_swatches_and_limit_to_library` exercise the fields and menu callbacks rather than writing their result state. Area score and hours unchanged. - **Save refusal (#6146):** ordinary File > Save to its own location offers Save As after a terminal permission/read-only refusal, suggesting the original name and format, preserving options for the unchanged format and opening the chosen format’s Save options on a change. Cancel keeps the failed-save state. Busy pickers, recovery-copy errors, other failures, explicit destinations and Close/Quit keep the existing dialog. Engine, UI and MCP regression cases are in `cmd/fileio/tests_readonly.rs`, `io/tests_read_only_save.rs` and MCP `tests/fileio.rs`; focused UI regressions passed; engine regression execution and native panel acceptance pending. Scores and hours unchanged. From bbf11feac38f760053b417bbf65d7d8a4848f89e Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 17 Nov 2026 10:45:44 -0800 Subject: [PATCH 116/176] Stroke: Delete and Escape skip width points hidden on a brushed stroke Width points selected before their stroke took a brush show no handles, but the Width tool still took Delete, Backspace and Escape for them. The tool now leaves those keys to the app, as it does with no width points selected. - The Profile list shows its hover border whenever a click opens it, including on a brushed stroke with a profile, where it lists Uniform. - A test checks that the list's hover text and the Width tool's status message are the same string, so the two share their catalog rows. - An engine test checks that a press or a double-click on a brushed compound path puts the message in the status bar and runs no command. - The doc comment of Session::brushed_strokes_profiled says when type counts, and the progress-doc line names the double-click and says that art and pattern brushes do not follow a width profile yet. --- crates/engine/src/cmd/stroke.rs | 5 ++-- crates/engine/src/tests/widthtool.rs | 18 +++++++++++++++ crates/tools/src/distort.rs | 2 +- crates/tools/src/distort/width.rs | 23 +++++++++++-------- crates/ui-egui/src/panels/stroke.rs | 2 +- .../ui-egui/src/panels/tests_strokedepth.rs | 8 +++++++ docs/target-app-parity.md | 2 +- 7 files changed, 46 insertions(+), 14 deletions(-) diff --git a/crates/engine/src/cmd/stroke.rs b/crates/engine/src/cmd/stroke.rs index 038483182f..25095da32c 100644 --- a/crates/engine/src/cmd/stroke.rs +++ b/crates/engine/src/cmd/stroke.rs @@ -443,8 +443,9 @@ impl Session { /// /// The art of graph designs is left out, and so are images and symbol instances without an /// active row. The result is also `None` with nothing selected, with an object inside a symbol - /// instance selected, with type among the targets, and with a target that has no stroke row, - /// since `stroke.set` gives such a target a plain stroke. + /// instance selected, with type among the targets while no Appearance row is active for it, + /// and with a target that has no stroke row, since `stroke.set` gives such a target a plain + /// stroke. pub fn brushed_strokes_profiled(&self) -> Option<bool> { const C: &str = "stroke.set"; let st = self.active()?; diff --git a/crates/engine/src/tests/widthtool.rs b/crates/engine/src/tests/widthtool.rs index fda761de61..6b2ed12c54 100644 --- a/crates/engine/src/tests/widthtool.rs +++ b/crates/engine/src/tests/widthtool.rs @@ -40,6 +40,24 @@ fn the_width_tool_edits_a_compound_paths_stroke() { assert_eq!(s.journal.last().unwrap().1["id"], json!(c.0)); } +/// A compound path whose stroke draws with a brush: a press or a double-click on a member puts the +/// tool's reason in the status bar and leaves the stroke and the undo history as they were. +#[test] +fn the_width_tool_says_why_it_leaves_a_brushed_compound_path_alone() { + let (mut s, c, _) = compound(); + s.execute("brush.apply", &json!({"ids": [c.0], "name": "3 pt. Round"})).unwrap(); + let steps = s.journal.len(); + let v = ViewInfo::default(); + s.select_tool("width", v).unwrap(); + for (kind, reason) in [(PointerKind::Down, true), (PointerKind::Drag, false), (PointerKind::Up, false), (PointerKind::DoubleClick, true)] { + let ui = s.pointer(&PointerEvent::new(kind, 200.0, 301.0), v).unwrap(); + let said = ui.iter().any(|r| matches!(r, UiRequest::Status(m) if m == vectorcraft_tools::distort::KEEPS_SIZE)); + assert_eq!(said, reason, "{kind:?}: {ui:?}"); + } + assert_eq!(profile(&s, c), None); + assert_eq!(s.journal.len(), steps, "no command ran"); +} + #[test] fn width_point_commands_given_a_member_edit_the_compound() { let (mut s, c, members) = compound(); diff --git a/crates/tools/src/distort.rs b/crates/tools/src/distort.rs index 30cb1cd4c5..b4cd0a957c 100644 --- a/crates/tools/src/distort.rs +++ b/crates/tools/src/distort.rs @@ -27,7 +27,7 @@ use crate::Tool; pub use liquify::LiquifyTool; pub use perspective::{PerspectiveGridTool, PerspectiveSelectionTool}; pub use puppet::{PinSet, PuppetWarpTool, mesh_for, mesh_input, rest_and_pins, warp_from_rest}; -pub use width::{WidthTool, stroke_owner}; +pub use width::{KEEPS_SIZE, WidthTool, stroke_owner}; /// Create a distortion tool by id (None = not one of ours). pub fn create(id: &str) -> Option<Box<dyn Tool>> { diff --git a/crates/tools/src/distort/width.rs b/crates/tools/src/distort/width.rs index 7eda93305e..005b8e9473 100644 --- a/crates/tools/src/distort/width.rs +++ b/crates/tools/src/distort/width.rs @@ -21,10 +21,10 @@ //! drag does: add a width point on a stroke, or move or widen the one under it. //! //! A stroke drawn with a brush is left alone, as a width profile does not change it: a press or a -//! double-click on it, and Delete/Backspace with its width points selected, send no command and -//! show why in the status bar ([`KEEPS_SIZE`]). A press or double-click on it deselects the -//! width points, the cursor over it offers no edit, and its width points selected before it took -//! the brush show no handles. +//! double-click on it sends no command and shows why in the status bar ([`KEEPS_SIZE`]). Without +//! Shift, the press or double-click deselects the width points, and the cursor over it offers no +//! edit. Its width points selected before it took the brush show no handles, and Delete, +//! Backspace and Escape do what they do with no width points selected. use std::cell::Cell; use std::sync::Arc; @@ -469,11 +469,12 @@ impl Tool for WidthTool { } /// Delete/Backspace remove the selected width points and Escape deselects them; with none /// selected the keys do what they do with other tools (Clear deletes the selected objects, and - /// Escape leaves isolation mode, for one). + /// Escape leaves isolation mode, for one). Width points of a brushed stroke, which show no + /// handles, count as none selected. fn claims_key(&self, cx: &ToolContext, key: ToolKey) -> bool { matches!(key, ToolKey::Delete | ToolKey::Backspace | ToolKey::Escape) && self.drag.is_none() - && self.selected.as_ref().is_some_and(|(id, _)| !self.selected_indices(cx, *id).is_empty()) + && self.selected.as_ref().is_some_and(|(id, _)| !self.selected_indices(cx, *id).is_empty() && !self.keeps_size(cx, *id)) } /// A dropped press ends the drag, and the width points selected when the button went down are /// selected again. @@ -497,7 +498,7 @@ impl Tool for WidthTool { } self.selected = None; if self.keeps_size(cx, id) { - return vec![Action::Status(KEEPS_SIZE.into())]; + return vec![]; } vec![Action::Exec("stroke.widthPoint.remove".into(), json!({"id": id.0, "indices": indices}))] } @@ -694,7 +695,8 @@ mod tests { assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Down, 150.0, 201.0)), vec![Action::Status(KEEPS_SIZE.into())]); } - /// Width points selected before the stroke took a brush: Delete removes none and says why. + /// Width points selected before the stroke took a brush show no handles and count as none + /// selected: the tool leaves Delete and Escape to the app, and removes none. #[test] fn delete_leaves_the_width_points_of_a_brushed_stroke() { let (mut d, id) = doc_line(); @@ -710,7 +712,10 @@ mod tests { d.node_mut(id).unwrap().appearance.stroke_mut().unwrap().brush = Some("3 pt. Round".into()); let c = ToolContext { revision: (0, 1), ..cx(&d, &s, &p) }; assert!(t.overlays(&c).is_empty(), "no handles show on a stroke the tool no longer edits"); - assert_eq!(t.key(&c, ToolKey::Delete, Mods::default()), vec![Action::Status(KEEPS_SIZE.into())]); + for key in [ToolKey::Delete, ToolKey::Backspace, ToolKey::Escape] { + assert!(!t.claims_key(&c, key), "{key:?} is the app's"); + } + assert_eq!(t.key(&c, ToolKey::Delete, Mods::default()), vec![]); assert!(t.selected.is_none()); } diff --git a/crates/ui-egui/src/panels/stroke.rs b/crates/ui-egui/src/panels/stroke.rs index 25c32db77e..edf4af5428 100644 --- a/crates/ui-egui/src/panels/stroke.rs +++ b/crates/ui-egui/src/panels/stroke.rs @@ -537,7 +537,7 @@ pub(crate) fn profile_dropdown(app: &VectorcraftApp, ui: &mut Ui, shown: Option< let sense = if uniform { Sense::hover() } else { Sense::click() }; let (r, resp) = ui.allocate_exact_size(vec2(PROFILE_DROPDOWN_WIDTH, 24.0), sense); ui.painter().rect_filled(r, 2, t.input); - let border = if resp.hovered() && !keeps_size { t.text } else { t.input_border }; + let border = if resp.hovered() && !uniform { t.text } else { t.input_border }; ui.painter().rect_stroke(r, 2, Stroke::new(1.0, border), StrokeKind::Inside); let body = Rect::from_min_max(r.min + vec2(6.0, 5.0), pos2(r.right() - 20.0, r.bottom() - 5.0)); let (shape, icon) = if keeps_size { (t.text_disabled, t.text_disabled) } else { (t.text_strong, t.icon) }; diff --git a/crates/ui-egui/src/panels/tests_strokedepth.rs b/crates/ui-egui/src/panels/tests_strokedepth.rs index aa4dfb9fa1..c4f2a9fff4 100644 --- a/crates/ui-egui/src/panels/tests_strokedepth.rs +++ b/crates/ui-egui/src/panels/tests_strokedepth.rs @@ -281,6 +281,14 @@ fn mixed_selection_dims_the_dropdown_only_when_every_stroke_has_a_brush() { assert_eq!(listed(&ctx, &mut app).len(), WidthProfile::PRESETS.len()); } +/// The dimmed dropdown's hover text is the Width tool's status message, word for word, so the two +/// share their catalog rows. +#[test] +fn the_hover_text_is_the_width_tools_status_message() { + let literal = format!("tl!(\"{}\")", vectorcraft_tools::distort::KEEPS_SIZE); + assert!(include_str!("stroke.rs").contains(&literal), "panels/stroke.rs has no {literal}"); +} + #[test] fn every_arrowhead_preview_draws_its_head() { use vectorcraft_doc::Arrowhead; diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 046a1b2ffd..931f7b1d06 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -775,7 +775,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Width-point finite-arithmetic follow-up (G1/M3):** Adjoining adjustments avoid intermediate overflow; non-finite normalized or resulting factors are rejected before committing. Engine regressions in `tests/widthpoints.rs` cover finite extremes, small nonzero results, atomic rejection, Undo/Redo and native save/reopen. Historical focused validation on the `a3357121` integration observed 2 expected RED failures with 11 passing controls, then all 13 tests passing with the repair; none were ignored. All three added regressions passed in current full CI. A full CI retry on the five-unit combined source at `a0671777` passed all seven stages with 6,613 test outcomes on 2026-10-14. An earlier full-CI run on the identical source panicked in the randomized `ai_mutated_save_never_panics` test; the cause remains unresolved. This five-fix batch does not claim to repair that failure. Scores and hours unchanged. - **Width-point creation (G1):** double-click a stroked segment with the Width tool to open Width Point Edit using sampled side widths. OK creates the point and optionally adjusts adjoining widths in one undo step. Cancel or Delete discards a prospective point without changing the document or redo history. Command and pointer tests cover profiles, compound paths, adjoining adjustment, existing-point editing and Undo/Redo. Message-catalog checks and full CI passed; the original capture verifies opening and Cancel, and the dialog layout was reviewed (2026-10-13: 28 focused Width tests, all seven cargo xtask ci stages, and a headless opening/Cancel capture with original PNG review). [Variable-width strokes](https://helpx.adobe.com/illustrator/using/stroke-object.html). - **Escape deselects width points:** with the Width tool, Escape deselects the selected width points, on the key the reference app's [Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html) page lists for deselecting a width point. The path, its widths and the undo history do not change. With no width point selected, Escape does what it does with the other tools, such as leaving isolation mode. -- **Width profiles on brushed strokes:** brush art does not follow a stroke's width profile, so while every stroke the list edits draws with a brush, the Profile list in the Stroke panel, the Properties panel and the Control bar is dimmed and says why when hovered (VectorCraft's own rule). It opens no list while every one of those strokes is uniform, and only Uniform, which removes the profiles, while one has a profile. The Flip Along and Flip Across buttons beside it are off. The strokes are the ones `stroke.set` edits: the active Appearance stroke row in each selected object that has an equal row and the top stroke in the others, else a selected group's or compound shape's own stroke, else the objects' strokes. Images and symbol instances, which take no stroke from the list, do not count. A selection where some of them have no brush, or an object has no stroke, keeps the full list. The Width tool adds, edits and deletes no width points on a brushed stroke, and a press on one, or Delete with its width points selected, says why in the status bar; without Shift the press deselects the width points of other strokes, and the cursor over a brushed stroke offers no edit. A plain stroke under a selected brushed one stays reachable, and width points selected before their stroke took a brush show no handles. Tests: `panels::tests_strokedepth::{dropdown_is_dimmed_while_the_brush_keeps_its_size, the_active_stroke_row_decides_whether_the_dropdown_is_dimmed, a_groups_own_brushed_stroke_dims_the_dropdown, selecting_another_object_without_an_edit_updates_the_dimming, flip_buttons_leave_a_brushed_strokes_profile_alone, mixed_selection_dims_the_dropdown_only_when_every_stroke_has_a_brush}`, `panels::properties::tests::the_width_profile_of_a_brushed_stroke_offers_only_uniform`, `tests::appearance::{brushed_strokes_profiled_reads_the_strokes_stroke_set_edits, brushed_strokes_profiled_reads_a_compound_shapes_own_stroke, brushed_strokes_profiled_reads_a_targeted_layers_active_stroke_row, brushed_strokes_profiled_leaves_out_symbol_instances, brushed_strokes_profiled_falls_back_to_the_top_stroke_where_the_active_row_has_no_match}`, `distort::width::tests::{brushed_stroke_is_left_alone_with_a_reason, delete_leaves_the_width_points_of_a_brushed_stroke, a_press_on_a_brushed_stroke_deselects_and_its_cursor_offers_no_edit, shift_on_a_brushed_stroke_keeps_the_selected_width_points, a_plain_stroke_under_a_selected_brushed_one_stays_reachable, a_brush_applied_under_a_still_pointer_takes_away_the_hover, a_brush_added_to_the_library_is_seen_at_the_next_revision}`. +- **Width profiles on brushed strokes:** brush art does not follow a stroke's width profile, so while every stroke the list edits draws with a brush, the Profile list in the Stroke panel, the Properties panel and the Control bar is dimmed and says why when hovered (VectorCraft's own rule while brushes ignore width profiles; art and pattern brushes that follow one are still missing). It opens no list while every one of those strokes is uniform, and only Uniform, which removes the profiles, while one has a profile. The Flip Along and Flip Across buttons beside it are off. The strokes are the ones `stroke.set` edits: the active Appearance stroke row in each selected object that has an equal row and the top stroke in the others, else a selected group's or compound shape's own stroke, else the objects' strokes. Images and symbol instances, which take no stroke from the list, do not count. A selection where some of them have no brush, or an object has no stroke, keeps the full list. The Width tool adds, edits and deletes no width points on a brushed stroke, and a press or a double-click on one says why in the status bar; without Shift it deselects the width points of other strokes, and the cursor over a brushed stroke offers no edit. A plain stroke under a selected brushed one stays reachable. Width points selected before their stroke took a brush show no handles, and Delete, Backspace and Escape act as if none were selected. Tests: `panels::tests_strokedepth::{dropdown_is_dimmed_while_the_brush_keeps_its_size, the_active_stroke_row_decides_whether_the_dropdown_is_dimmed, a_groups_own_brushed_stroke_dims_the_dropdown, selecting_another_object_without_an_edit_updates_the_dimming, flip_buttons_leave_a_brushed_strokes_profile_alone, mixed_selection_dims_the_dropdown_only_when_every_stroke_has_a_brush, the_hover_text_is_the_width_tools_status_message}`, `panels::properties::tests::the_width_profile_of_a_brushed_stroke_offers_only_uniform`, `tests::appearance::{brushed_strokes_profiled_reads_the_strokes_stroke_set_edits, brushed_strokes_profiled_reads_a_compound_shapes_own_stroke, brushed_strokes_profiled_reads_a_targeted_layers_active_stroke_row, brushed_strokes_profiled_leaves_out_symbol_instances, brushed_strokes_profiled_falls_back_to_the_top_stroke_where_the_active_row_has_no_match}`, `tests::widthtool::the_width_tool_says_why_it_leaves_a_brushed_compound_path_alone`, `distort::width::tests::{brushed_stroke_is_left_alone_with_a_reason, delete_leaves_the_width_points_of_a_brushed_stroke, a_press_on_a_brushed_stroke_deselects_and_its_cursor_offers_no_edit, shift_on_a_brushed_stroke_keeps_the_selected_width_points, a_plain_stroke_under_a_selected_brushed_one_stays_reachable, a_brush_applied_under_a_still_pointer_takes_away_the_hover, a_brush_added_to_the_library_is_seen_at_the_next_revision}`. - **Smooth widths between width points (#5714):** a variable-width stroke changes width along a smooth curve from one width point to the next, where it used to run in a straight line and turn a corner at each point. The public description is that the path "gradually gets wider or narrower from one point to the next" in "a flowing, continuous curve", and that stacked points make a sharp break ([Peachpit, Expressive Strokes](https://www.peachpit.com/articles/article.aspx?p=2979069)); the exact curve is not documented, so each side follows a monotone cubic (Fritsch–Carlson): no kink at a point, flat where a point is wider or narrower than both neighbours, never past the points either side, points on one line kept on it. The outline samples straight runs between width points closely enough to follow the curve to the drawing tolerance (at most 64 samples per span and 4,096 per piece). Presets with a middle point (Lens, Pinch, Teardrop, Wave) look softer; two-point tapers are unchanged. Tests: `appearance::profile::tests::{widths_run_smoothly_through_width_points, widths_never_pass_the_points_either_side, a_step_ends_the_curve_on_each_side, widest_covers_every_width_along_the_profile}`, `stroke::width::tests::{a_straight_run_follows_the_curve_between_width_points, samples_between_width_points_are_capped}`. - **Stroke gradients where a variable-width stroke meets itself (#5960):** with a gradient along or across a stroke that has a width profile, where the stroke crosses itself the later part paints over the earlier one only where the two overlap, and a narrow part running close beside a wide one leaves its edge alone. Each slice of the gradient reaches as far as the stroke is wide where it sits (for a dashed stroke, as wide as it gets within the reach of a cap or dot, found in one pass along the path, so a densely flattened path costs no more per point), where it used to reach as far as the stroke is wide anywhere and paint a square of its colour over the wider part. Strokes without a profile are unchanged. Tests: `stroke::tests_gradient::a_narrow_pass_over_a_wide_one_paints_only_where_they_overlap`, `a_narrow_pass_beside_a_wide_one_leaves_its_edge_alone`, `a_densely_flattened_dashed_pass_beside_a_wide_one_leaves_its_edge_alone` and `widest_ahead_is_the_widest_within_the_window`, with the existing coverage tests (joins, caps, arrowheads, profiles, dashes, aligned strokes). - **Width strokes zoomed out (#995):** a stroke with a width profile keeps its shape while the view zooms out. The canvas keeps a hairline visible (at least half a device pixel); for a profiled stroke it is the profile's widest point that gets that minimum, not the weight, so a 1 pt stroke with a 6x width point is no longer drawn twice as thick at 25% zoom than at 100%. Plain strokes are unchanged. Test: `render::tests::widthzoom`. From c0e462435806684d074ce3f76630fcbe8f0b4d76 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 17 Nov 2026 10:54:58 -0800 Subject: [PATCH 117/176] Links: frames that fetch nothing reuse the cached rows without copying them The Links panel kept its links.list rows and Link Info in panel state by value, so every frame copied the whole JSON list out of egui memory and wrote another copy back, even when nothing was fetched. The cache is now stored behind an Arc: a frame reads it without a copy and stores a new one only when the list is fetched again (document revision, Show, Sort, DCS option or the 2-second recheck) or Link Info changes. The flyout reads the same cache by reference. --- crates/ui-egui/src/panels/links.rs | 35 ++++++++++++++---------- crates/ui-egui/src/panels/tests_links.rs | 30 ++++++++++++++++++++ docs/target-app-parity.md | 1 + 3 files changed, 51 insertions(+), 15 deletions(-) diff --git a/crates/ui-egui/src/panels/links.rs b/crates/ui-egui/src/panels/links.rs index 611c9e472a..a020a6df14 100644 --- a/crates/ui-egui/src/panels/links.rs +++ b/crates/ui-egui/src/panels/links.rs @@ -54,7 +54,7 @@ impl Default for Options { /// `links.list` and the first selected image's `links.info`, with what they were fetched for. #[derive(Clone, Default)] -struct Cache { +pub(super) struct Cache { /// (document uid, revision, show, sort, Show DCS Transparency Interactions). key: Option<(u64, u64, &'static str, Option<&'static str>, bool)>, at: f64, @@ -83,23 +83,23 @@ fn set_options(ctx: &egui::Context, f: impl FnOnce(&mut Options)) { } /// The rows to show (cached per document revision, the files looked at again every [`RECHECK`] -/// seconds) and the Link Info of the first selected image when the section is open. -fn cached(app: &mut VectorcraftApp, ctx: &egui::Context, o: &Options) -> Option<Cache> { +/// seconds) and the Link Info of the first selected image when the section is open. A frame that +/// fetches nothing returns the stored cache without copying it and stores nothing. +fn cached(app: &mut VectorcraftApp, ctx: &egui::Context, o: &Options) -> Option<std::sync::Arc<Cache>> { let st = app.session.active()?; let key = Some((st.uid, st.revision, o.show, o.sort, o.dcs)); let first = selected_links(app, ctx).first().copied(); let now = ctx.input(|i| i.time); - let mut c: Cache = pstate(ctx, "links-cache"); + let mut c: std::sync::Arc<Cache> = pstate(ctx, "links-cache"); let stale = c.key != key || now - c.at > RECHECK; if stale { let same_doc = c.key == key; - c.list = app.session.execute("links.list", &json!({ "show": o.show, "sort": o.sort, "dcsTransparency": o.dcs })).ok()?; - (c.key, c.at) = (key, now); + let list = app.session.execute("links.list", &json!({ "show": o.show, "sort": o.sort, "dcsTransparency": o.dcs })).ok()?; // One pass over the stored art for the rows outside the layer tree and the objects whose // opacity masks hold them, not one per frame. An object in the layer tree is looked up by // its index when drawn. let doc = app.session.active().map(|st| &st.doc); - let want: std::collections::HashSet<u64> = c.list["links"] + let want: std::collections::HashSet<u64> = list["links"] .as_array() .into_iter() .flatten() @@ -110,18 +110,22 @@ fn cached(app: &mut VectorcraftApp, ctx: &egui::Context, o: &Options) -> Option< .collect(); // The same revision keeps the objects collected for it, so their thumbnails are not drawn // again each time the files are looked at. - if !(same_doc && want.iter().all(|id| c.nested_node(*id).is_some())) { - c.nested = match doc { + let nested = if same_doc && want.iter().all(|id| c.nested_node(*id).is_some()) { + c.nested.clone() + } else { + match doc { Some(d) if !want.is_empty() => stored_objects(d, want), _ => vec![], - }; - } + } + }; + c = std::sync::Arc::new(Cache { key, at: now, list, info: None, nested }); } let want = first.filter(|_| o.info); if stale || c.info.as_ref().map(|(id, _)| *id) != want { - c.info = want.and_then(|id| Some((id, app.session.execute("links.info", &json!({ "id": id })).ok()?))); + let info = want.and_then(|id| Some((id, app.session.execute("links.info", &json!({ "id": id })).ok()?))); + std::sync::Arc::make_mut(&mut c).info = info; + set_pstate(ctx, "links-cache", c.clone()); } - set_pstate(ctx, "links-cache", c.clone()); // Files change on disk without a frame of ours: look again later. ctx.request_repaint_after(std::time::Duration::from_secs_f64(RECHECK)); Some(c) @@ -788,9 +792,10 @@ fn link_info(ui: &mut Ui, info: Option<&Value>, units: vectorcraft_doc::Unit) { pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { let o = options(ui.ctx()); // The rows the panel shows (the menu opens from it). - let list = pstate::<Cache>(ui.ctx(), "links-cache").list; + let cache = pstate::<std::sync::Arc<Cache>>(ui.ctx(), "links-cache"); + let list = &cache.list; let selected = selected_links(app, ui.ctx()); - let sel = selected_rows(&list, &selected); + let sel = selected_rows(list, &selected); let linked = ids(&sel, |r| r["linked"] == true); let embedded: Vec<&Value> = sel.iter().copied().filter(|r| status_is(r, "embedded")).collect(); let any = !sel.is_empty(); diff --git a/crates/ui-egui/src/panels/tests_links.rs b/crates/ui-egui/src/panels/tests_links.rs index 781c4f5840..50e7bac498 100644 --- a/crates/ui-egui/src/panels/tests_links.rs +++ b/crates/ui-egui/src/panels/tests_links.rs @@ -136,6 +136,36 @@ fn the_panel_lists_the_images_with_link_info_for_the_selected_one() { } } +/// A frame that fetches nothing keeps the stored rows and Link Info as they are, without a copy; the +/// two-second recheck, another first selected image and an edit each store a new cache. +#[test] +fn frames_that_fetch_nothing_reuse_the_cached_rows() { + let dir = Folder::new("cache"); + let (mut app, linked, _) = app(&dir); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let frame = |app: &mut VectorcraftApp, time: f64| { + let raw = egui::RawInput { time: Some(time), ..Default::default() }; + let text: Vec<String> = super::tests_appearance::frame_raw(&ctx, app, raw, super::links::show).into_iter().map(|(t, _)| t).collect(); + (super::pstate::<std::sync::Arc<super::links::Cache>>(&ctx, "links-cache"), text) + }; + let (first, text) = frame(&mut app, 1.0); + assert!(text.iter().any(|t| t == "linked.png") && text.iter().any(|t| t == "40 × 20 px"), "{text:?}"); + let (same, text) = frame(&mut app, 1.5); + assert!(std::sync::Arc::ptr_eq(&first, &same), "a frame that fetches nothing stores no new cache"); + assert!(text.iter().any(|t| t == "linked.png") && text.iter().any(|t| t == "40 × 20 px"), "{text:?}"); + let (rechecked, _) = frame(&mut app, 3.6); + assert!(!std::sync::Arc::ptr_eq(&same, &rechecked), "the files are looked at again after two seconds"); + app.run("select.set", json!({"ids": [linked]})).unwrap(); + let (picked, text) = frame(&mut app, 3.7); + assert!(!std::sync::Arc::ptr_eq(&rechecked, &picked), "Link Info follows the first selected image"); + assert!(text.iter().any(|t| t == "300 × 200 px"), "{text:?}"); + app.run("edit.clear", json!({"ids": [linked]})).unwrap(); + let (edited, text) = frame(&mut app, 3.8); + assert!(!std::sync::Arc::ptr_eq(&picked, &edited), "an edit lists the rows again"); + assert!(!text.iter().any(|t| t == "linked.png") && text.iter().any(|t| t == "embedded.png"), "{text:?}"); +} + /// Copy Info copies the file names of the selected links, or of `ids` in the order given, one per /// line; it is off with nothing selected, and a bad `ids` leaves the clipboard as it was. #[test] diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index e9fc9a6820..118785606b 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2189,6 +2189,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur On the desktop, the Layers panel renders a row's thumbnail on its thumbnail thread when the row's paths, and the paths of its opacity masks that are not disabled, hold more than 2,000 anchors in all. It already did this for the first thumbnail of a row of more than 200 objects. Until its first thumbnail is ready, the row shows boxes at the bounds of up to 41 of its paths, each in its path's solid fill or stroke color or in gray, when its own paths, without its opacity masks, hold at most 2,000 anchors in all, and an empty white box otherwise. With one path of 200,000 anchors, the first frame after the panel opens takes 2.4 ms instead of 393 ms (release build, median of three runs). The same 2,000-anchor limit counts each glyph of type as 4 anchors, each point of a gradient mesh as 1 and every 100 pixels of an image as 1, and a symbol instance or a placed document counts the objects and anchors of the art it shows. A placed document whose file has not been read yet, or a symbol nested more than 8 deep (one that holds an instance of itself, for example), gets its first thumbnail on the thumbnail thread, and so does a row whose art takes more than 20,000 steps to count (each object, subpath, text run and symbol looked at is one step). The first frame after the panel opens takes 2.4 ms instead of 19.8 ms with 5,000 glyphs of point type, 1.8 ms instead of 343 ms with one instance of a symbol of a 200,000-anchor path, 2.0 ms instead of 11.0 ms with a 100 × 100 mesh, and 2.1 ms instead of 274 ms with a placed document of a 200,000-anchor path (release build, median of three runs). When the Layers or Links panel shows another document's rows, the thumbnail thread drops the row thumbnails it has not started for the documents not shown, and it drops all of them when the Layers or Links panel is open after the last document closes. Those rows ask for their thumbnails again when their document shows again, and the thumbnails already made are kept. With 150 rows of 20,000-anchor paths waiting for another document, the 8 rows of such paths of the document shown get their thumbnails in 153 ms instead of 3,265 ms (debug test build, median of three runs). + The Links panel keeps its `links.list` rows and Link Info in one shared cache, and a frame that fetches nothing new reads that cache without copying the rows. The cache is replaced when the document or its revision changes, the Show, Sort or Show DCS Transparency Interactions option changes, or the files are looked at again every 2 seconds, and, while an image is selected, when Link Info opens or closes or the first selected image changes. With 2,001 images a frame's cache step takes 0.2 µs instead of 1.79 ms, and with 10,001 images 0.2 µs instead of 12.2 ms (test build, median of 7 wall-clock runs of 1,000 frames, measured while other builds were running). In the web build, while a pan, zoom or rotation changes the view of a document whose last canvas render took more than 8 ms, the canvas draws the last frame moved with the view, and it renders the art again once the view has been still for 0.2 s. An Alt-drag with the Selection, Direct Selection, Group Selection, Rotate, Scale, Reflect or Shear tool copies the selection on its first move, and the moves after it transform those copies; the previews of the Move, Rotate, Scale, Reflect and Shear dialogs with Copy and Preview on copy the selection once in the same way (#1429). An Alt-drag of objects in perspective with the Perspective Selection tool, and an Alt-drag of a plane widget with that tool or the Perspective Grid tool, copy the objects on the first move, and the moves after it move those copies (#1429). From a533aec0feac0ad0154626d38f6cadd8a0347ab3 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 17 Nov 2026 11:18:57 -0800 Subject: [PATCH 118/176] Transform: a line length too small to move its ends records no undo step, and both Line fields send together object.setLiveShape reports no change when the rounded ends stay where they are. The Line Length and Line Angle fields send every edited value in one call, so a length committed in the same frame as an angle step is applied. --- crates/engine/src/cmd/object/shape.rs | 2 +- crates/engine/src/tests/livecorners.rs | 6 ++++++ crates/ui-egui/src/panels/transform.rs | 12 ++++++------ 3 files changed, 13 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/cmd/object/shape.rs b/crates/engine/src/cmd/object/shape.rs index 0c5a16b00c..053cc3b36d 100644 --- a/crates/engine/src/cmd/object/shape.rs +++ b/crates/engine/src/cmd/object/shape.rs @@ -120,7 +120,7 @@ fn line_edit(l: &LiveShape, len: Option<f64>, angle: Option<f64>) -> Option<Live new.set_line_angle(a); changed = true; } - changed.then_some(new) + (changed && new != *l).then_some(new) } pub(super) fn set_live_shape(s: &mut Session, p: &Value) -> Result<Value> { diff --git a/crates/engine/src/tests/livecorners.rs b/crates/engine/src/tests/livecorners.rs index f32d0c8257..2537748187 100644 --- a/crates/engine/src/tests/livecorners.rs +++ b/crates/engine/src/tests/livecorners.rs @@ -612,6 +612,12 @@ fn a_line_takes_its_length_and_angle() { run(&mut s, json!({"ids": [speck.0], "lineLength": 1e-12})); assert_eq!(steps(&s), n + 1, "a length of 1e-12 pt is a change"); assert!(ends(&s, speck).2 > 20.0, "{:?}", ends(&s, speck)); + // A length so short that the rounded ends do not move records no undo step. + let dust = line(&mut s, (20.0, 20.0), (20.0, 20.0)); + let n = steps(&s); + run(&mut s, json!({"ids": [dust.0], "lineLength": 1e-20})); + assert_eq!(steps(&s), n, "a length of 1e-20 pt changes nothing"); + near(ends(&s, dust), (20.0, 20.0, 20.0, 20.0)); // Other live shapes ignore the line params. let rect = NodeId(s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap()["id"].as_u64().unwrap()); let n = steps(&s); diff --git a/crates/ui-egui/src/panels/transform.rs b/crates/ui-egui/src/panels/transform.rs index 6145d34de3..f5ec0d18ea 100644 --- a/crates/ui-egui/src/panels/transform.rs +++ b/crates/ui-egui/src/panels/transform.rs @@ -462,22 +462,22 @@ pub(crate) fn line_rows(app: &mut VectorcraftApp, ui: &mut Ui, live: &LiveShape, } let (units, fw) = (app.session.general_unit(), super::field_width(ui)); widgets::subheader(ui, tl!("Line Properties:")); - // The `object.setLiveShape` param an edited field sets. - let mut set = None; + // The `object.setLiveShape` params the edited fields set, all sent in one call. + let mut set = serde_json::Map::new(); egui::Grid::new((id, "grid")).num_columns(2).spacing([6.0, 6.0]).show(ui, |ui| { widgets::dim_label(ui, tl!("Line Length:")); if let Some(l) = widgets::num_field_named(ui, (id, "length"), Some(tl!("Line Length:")), live.line_length(), units, fw) { - set = Some(("lineLength", json!(l))); + set.insert("lineLength".into(), json!(l)); } ui.end_row(); widgets::dim_label(ui, tl!("Line Angle:")); if let Some(a) = widgets::plain_field_named(ui, (id, "angle"), Some(tl!("Line Angle:")), live.line_angle().unwrap_or(0.0), "°", 1, fw) { - set = Some(("lineAngle", json!(a))); + set.insert("lineAngle".into(), json!(a)); } ui.end_row(); }); - if let Some((key, v)) = set - && let Err(e) = app.run("object.setLiveShape", json!({ key: v })) + if !set.is_empty() + && let Err(e) = app.run("object.setLiveShape", serde_json::Value::Object(set)) { app.status(e); } From 0b25050130d1b3b56266042b8425f8f0c0c93ad6 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 17 Nov 2026 11:34:31 -0800 Subject: [PATCH 119/176] Twist: compute exact directional derivatives --- crates/doc/src/live.rs | 3 +- crates/doc/src/live/warp.rs | 58 +++++++++++++++++++++++++---------- crates/effects/src/distort.rs | 20 ++++++++++-- crates/effects/src/tests.rs | 32 +++++++++++++++++++ crates/effects/src/util.rs | 2 +- 5 files changed, 93 insertions(+), 22 deletions(-) diff --git a/crates/doc/src/live.rs b/crates/doc/src/live.rs index 28fd1dc632..337634db2e 100644 --- a/crates/doc/src/live.rs +++ b/crates/doc/src/live.rs @@ -66,7 +66,8 @@ pub use expand::{ use mesh::grid_eval; pub use mesh::{Coons, GradientMesh, MeshAppearance, MeshPiece, MeshPoint, MeshQuad, default_fidelity, grid_points, nodes_bounds}; pub use warp::{ - WARP_NET, WarpNet, WarpStyle, fit_piece, map_nonlinear, map_nonlinear_within, map_smooth_within, pieces, uses_net, warp_point, warp_version, + WARP_NET, WarpNet, WarpStyle, fit_piece, map_handles_within, map_nonlinear, map_nonlinear_within, map_smooth_within, pieces, uses_net, + warp_point, warp_version, }; #[cfg(test)] diff --git a/crates/doc/src/live/warp.rs b/crates/doc/src/live/warp.rs index 3257b0fee6..64687e49fc 100644 --- a/crates/doc/src/live/warp.rs +++ b/crates/doc/src/live/warp.rs @@ -508,8 +508,19 @@ pub fn map_smooth_within(path: &PathData, max_piece: f64, max: usize, f: impl Fn map_pieces_within(path, max_piece, max, &f, |p, h| mapped_handle(&f, p, h)) } -/// The mapped handle uses `f`'s derivative at `p` toward `h`, computed with a second-order -/// one-sided difference. +/// [`map_nonlinear_within`] with `handle(point, handle)` supplying each mapped handle position. +pub fn map_handles_within( + path: &PathData, + max_piece: f64, + max: usize, + f: impl Fn(Point) -> Point, + handle: impl Fn(Point, Point) -> Point, +) -> PathData { + map_pieces_within(path, max_piece, max, &f, handle) +} + +/// Handle `h` of point `p` mapped through `f`: `f(p)` plus `f`'s derivative at `p` along `h - p` +/// (a central difference), so the image curve leaves `f(p)` the way `f` takes the curve. fn mapped_handle(f: &impl Fn(Point) -> Point, p: Point, h: Point) -> Point { let v = h - p; let len = v.hypot(); @@ -517,23 +528,13 @@ fn mapped_handle(f: &impl Fn(Point) -> Point, p: Point, h: Point) -> Point { if len.is_nan() || len <= 0.0 || len.is_infinite() { return f(p); } - // The step grows with the coordinates when a thousandth of the handle would round away. - // Both samples lie between the anchor and the handle. + // A thousandth of the handle, or more where the coordinates are so large that so short a + // step would round away (#7069): the samples stay a billionth of the coordinates apart, and + // at most at the handle's own end. let size = p.x.abs().max(p.y.abs()).max(1.0); let step = (1e-3f64).max(size * 1e-9 / len).min(1.0); - let at = f(p); - let midpoint = p + v * (step * 0.5); - let sample = p + v * step; - let far = f(sample) - at; - let near_offset = midpoint - p; - let far_offset = sample - p; - let uneven = (near_offset * 2.0 - far_offset).hypot() > far_offset.hypot() * 1e-6; - // The second-order formula requires evenly spaced samples. - if midpoint == p || midpoint == sample || uneven { - return at + far / step; - } - let near = f(midpoint) - at; - at + (near * 4.0 - far) / step + let d = (f(p + v * step) - f(p - v * step)) / (2.0 * step); + f(p) + d } /// [`map_nonlinear_within`]'s pieces, with `handle(point, handle)` giving each mapped handle. @@ -628,6 +629,29 @@ pub(super) fn resample(poly: &[Point], m: usize) -> Vec<Point> { mod handle_tests { use super::*; + #[test] + fn rounded_samples_preserve_a_smooth_interior_join() { + let center = Point::new(1e16, 0.0); + let path = PathData::new(vec![SubPath::new( + vec![ + Anchor::corner(center + vectorcraft_geom::kurbo::Vec2::new(-18.0, 0.0)), + Anchor::with_handles( + center, + center + vectorcraft_geom::kurbo::Vec2::new(-6.0, 0.0), + center + vectorcraft_geom::kurbo::Vec2::new(6.0, 0.0), + ), + Anchor::corner(center + vectorcraft_geom::kurbo::Vec2::new(18.0, 0.0)), + ], + false, + )]); + let mapped = map_smooth_within(&path, f64::INFINITY, 3, |p| Point::new(p.x, p.y + (p.x - center.x).powi(2) * 0.1)); + let join = &mapped.subpaths[0].anchors[1]; + let incoming = join.p - join.h_in; + let outgoing = join.h_out - join.p; + assert!(incoming.cross(outgoing).abs() < 1e-9, "{incoming:?} {outgoing:?}"); + assert!(incoming.dot(outgoing) > 0.0); + } + #[test] fn a_midpoint_rounded_to_an_endpoint_keeps_the_handle_direction() { for x in [1e16, 1e16 + 2.0, -1e16] { diff --git a/crates/effects/src/distort.rs b/crates/effects/src/distort.rs index 7a03a2f3aa..543b1a13cd 100644 --- a/crates/effects/src/distort.rs +++ b/crates/effects/src/distort.rs @@ -6,7 +6,7 @@ use vectorcraft_geom::{Affine, Anchor, ParamCurve, PathData, Point, Rect, SubPat use vectorcraft_pathops::addons::pathtools::insert_at; use crate::util::{ - catmull_rom, fit_piece, flag, map_nonlinear_within, map_smooth_within, mean_size, noise, normal_at, num, pieces, seed, seg_cubic, smooth_points, + catmull_rom, fit_piece, flag, map_handles_within, map_nonlinear_within, mean_size, noise, normal_at, num, pieces, seed, seg_cubic, smooth_points, }; fn diag(b: Rect) -> f64 { @@ -328,7 +328,7 @@ pub fn tweak(path: &PathData, b: Rect, p: &Value) -> PathData { /// Twist: rotation that is strongest at the centre and fades to zero at the bounding circle, /// clockwise on the page for a positive `angle`, making at most `max` anchors. Its handles follow -/// the rotation's derivative ([`map_smooth_within`]), so the pieces join without kinks (#7069). +/// the rotation's directional derivative, including each side of the outer circle. pub fn twist(path: &PathData, b: Rect, angle: f64, max: usize) -> PathData { let ang = angle.clamp(-3600.0, 3600.0).to_radians(); if ang == 0.0 { @@ -345,7 +345,21 @@ pub fn twist(path: &PathData, b: Rect, angle: f64, max: usize) -> PathData { c + Vec2::new(d.x * co - d.y * s, d.x * s + d.y * co) }; let piece = (r / 8.0).min(r / (1.0 + ang.abs() * 2.0)); - map_smooth_within(path, piece, max, f) + map_handles_within(path, piece, max, f, |p, h| { + let v = h - p; + if !v.hypot().is_finite() { + return f(p); + } + let d = p - c; + let length = d.hypot(); + let radial = if length > 0.0 { (d / length).dot(v) } else { 0.0 }; + // The clamped rotation has different inward and outward derivatives at the circle. + let gradient = if length < r || (length == r && radial < 0.0) { -ang / r * radial } else { 0.0 }; + let tangent = v + Vec2::new(-d.y, d.x) * gradient; + let a = ang * (1.0 - length / r).max(0.0); + let (s, co) = a.sin_cos(); + f(p) + Vec2::new(tangent.x * co - tangent.y * s, tangent.x * s + tangent.y * co) + }) } const ZIGZAG_ARCLEN_ACCURACY: f64 = 1e-4; diff --git a/crates/effects/src/tests.rs b/crates/effects/src/tests.rs index 994f69745c..2d0f70b0be 100644 --- a/crates/effects/src/tests.rs +++ b/crates/effects/src/tests.rs @@ -1730,6 +1730,38 @@ fn twist_boundary_handles_follow_the_inward_tangent() { } } +#[test] +fn twist_large_coordinate_joins_preserve_boundary_sides() { + use vectorcraft_geom::Anchor; + + let center = 1e16; + for offset in [32.0, 64.0] { + let p = Point::new(center + offset, 0.0); + let line = PathData::single(SubPath::new( + vec![ + Anchor::corner(Point::new(p.x - 18.0, 0.0)), + Anchor::with_handles(p, Point::new(p.x - 6.0, 0.0), Point::new(p.x + 6.0, 0.0)), + Anchor::corner(Point::new(p.x + 18.0, 0.0)), + ], + false, + )); + let out = crate::distort::twist(&line, Rect::new(center - 64.0, 0.0, center + 64.0, 0.0), 90.0, 3); + let join = &out.subpaths[0].anchors[1]; + if offset == 64.0 { + assert_eq!(join.h_out, Point::new(p.x + 6.0, 0.0)); + let actual = join.h_in - join.p; + let expected = vectorcraft_geom::Vec2::new(-1.0, std::f64::consts::FRAC_PI_2); + let error = actual.cross(expected).atan2(actual.dot(expected)).abs(); + assert!(error < 1e-9, "{actual:?}"); + } else { + let incoming = join.p - join.h_in; + let outgoing = join.h_out - join.p; + assert!(incoming.cross(outgoing).abs() < 1e-9, "{incoming:?} {outgoing:?}"); + assert!(incoming.dot(outgoing) > 0.0); + } + } +} + #[test] fn twist_fixes_the_outer_circle_and_rotates_inside() { let out = run("distort.twist", json!({"angle": 0}), &square()); diff --git a/crates/effects/src/util.rs b/crates/effects/src/util.rs index de203b4955..6b79d19999 100644 --- a/crates/effects/src/util.rs +++ b/crates/effects/src/util.rs @@ -71,7 +71,7 @@ pub fn seg_cubic(sp: &SubPath, i: usize) -> CubicBez { /// Non-linear path mapping (shared with live envelopes in `vectorcraft-doc`), and the split of /// segments into pieces within an anchor budget. -pub use vectorcraft_doc::live::{fit_piece, map_nonlinear_within, map_smooth_within, pieces}; +pub use vectorcraft_doc::live::{fit_piece, map_handles_within, map_nonlinear_within, pieces}; /// About how many lines the renderer flattens `path` into at 1 px/pt: one for a straight /// segment, and for a curve the count Wang's formula gives at vello's tolerance of 0.25 px, From a29478bcca982245c034e7a4f3172eb7046adce9 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 17 Nov 2026 11:39:25 -0800 Subject: [PATCH 120/176] Font menu: Enter on a size button no longer picks the highlighted font The size buttons are activated by Enter when focused. The key was still read as the list's Enter, which applied the highlighted font and closed the menu. The button now consumes the key when it handles it, and a test presses Enter on the focused Large button. --- crates/ui-egui/src/font_menu.rs | 2 + crates/ui-egui/src/font_menu/tests.rs | 58 +++++++++++++++++++++++++++ 2 files changed, 60 insertions(+) diff --git a/crates/ui-egui/src/font_menu.rs b/crates/ui-egui/src/font_menu.rs index 07d7e7a5d0..a8bf6fe498 100644 --- a/crates/ui-egui/src/font_menu.rs +++ b/crates/ui-egui/src/font_menu.rs @@ -1529,6 +1529,8 @@ fn filters(ui: &mut Ui, st: &mut MenuState, t: &Tokens, document: bool, row: Opt width += gap + resp.rect.width(); if resp.clicked() { ui.data_mut(|d| d.insert_temp(preview_size_id(), size)); + // A focused button is activated by Enter; the list must not read it as a pick. + ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Enter)); } } }); diff --git a/crates/ui-egui/src/font_menu/tests.rs b/crates/ui-egui/src/font_menu/tests.rs index 3ff86c5ace..7cf20d4210 100644 --- a/crates/ui-egui/src/font_menu/tests.rs +++ b/crates/ui-egui/src/font_menu/tests.rs @@ -1502,6 +1502,64 @@ fn the_preview_size_row_asks_for_the_size_clicked() { super::wait_for_samples(&ctx); } +/// Enter on a focused size button asks for that size and picks no font: the key is not also read as +/// the list's Enter, which would apply the highlighted font and close the menu. +#[test] +fn enter_on_a_focused_size_button_picks_no_font() { + let db = vectorcraft_text::FontDb::with_font_dirs(vec![]); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + // The Recently Added filter gives the list rows from the bundled fonts alone. + let mut st = super::MenuState { added_only: true, added: added_in(&db, &["Source Serif 4", "Inter"], None), ..Default::default() }; + let id = egui::Id::unique("size-enter"); + let look = super::MenuLook { row: super::preview_row("small"), clock: Some(clock()), ..Default::default() }; + let area = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 900.0)); + let frame = |st: &mut super::MenuState, events: Vec<egui::Event>| { + let mut pick = None; + let mut out = ctx.run_ui(egui::RawInput { events, screen_rect: Some(area), ..Default::default() }, |ui| { + pick = super::list_of(ui, &db, id, st, "Inter", None, look).inner; + }); + out.textures_delta.clear(); + (out.shapes, pick) + }; + frame(&mut st, vec![]); + let (shapes, _) = frame(&mut st, vec![]); + let at = text_at(&shapes, |t| t == "Large").expect("Large is drawn"); + let button = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + frame(&mut st, vec![egui::Event::PointerMoved(at), button(true)]); + frame(&mut st, vec![button(false)]); + ctx.data_mut(|d| d.remove_temp::<&'static str>(super::preview_size_id())); + let enter = |pressed| egui::Event::Key { + key: egui::Key::Enter, + physical_key: Some(egui::Key::Enter), + pressed, + repeat: false, + modifiers: Default::default(), + }; + let tab = + |pressed| egui::Event::Key { key: egui::Key::Tab, physical_key: Some(egui::Key::Tab), pressed, repeat: false, modifiers: Default::default() }; + assert!(!listed_families(&st).is_empty(), "the list has rows an Enter could pick"); + // Tab moves the focus along the controls until it is on the Large button, where Enter is pressed. + let mut found = None; + for _ in 0..60 { + frame(&mut st, vec![tab(true)]); + frame(&mut st, vec![tab(false)]); + let on_large = ctx.memory(|m| m.focused()).and_then(|f| ctx.read_response(f)).is_some_and(|r| r.rect.contains(at)); + if !on_large { + continue; + } + let (_, pick) = frame(&mut st, vec![enter(true)]); + frame(&mut st, vec![enter(false)]); + if ctx.data_mut(|d| d.remove_temp::<&'static str>(super::preview_size_id())) == Some("large") { + found = Some(pick); + break; + } + } + let pick = found.expect("Enter on the focused Large button asks for the size"); + assert!(pick.is_none(), "Enter on the size button picks no font: {pick:?}"); + super::wait_for_samples(&ctx); +} + /// The size a font menu's button asked for becomes Font Preview Size, which sizes every font /// menu's rows, and the host is asked to write the preferences file. The document is left as it /// was: a font previewed on the selected type stays previewed, and the change adds no undo step. From 0da5bf3a0bc64eded7d187c3dedc8ceb26d730b8 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 17 Nov 2026 11:44:23 -0800 Subject: [PATCH 121/176] Select: Select Behind in isolation looks up the objects it found in a set Each round of the repeated hit test that Select Behind uses in isolation mode and in Edit Contents skipped the objects already found by searching the found list, which made one Cmd/Ctrl-click cubic in the number of objects under the point. A set beside the ordered list answers the same lookups, so the objects and their order do not change. A test compares the set lookup with the list lookup on random documents for every object isolated in turn, and an ignored timing test measures both on 200 and 1,000 stacked objects. --- crates/doc/src/hit.rs | 8 +- crates/doc/src/hit/tests.rs | 210 ++++++++++++++++++++++++++++++++++++ 2 files changed, 215 insertions(+), 3 deletions(-) diff --git a/crates/doc/src/hit.rs b/crates/doc/src/hit.rs index 3b415ef1ed..a666e1d0bd 100644 --- a/crates/doc/src/hit.rs +++ b/crates/doc/src/hit.rs @@ -607,9 +607,11 @@ fn objects_at_repeated(doc: &Document, p: Point, opt: HitOptions, scope: Option< /// [`objects_at_repeated`] after `tops`, the topmost objects under `p` already found. fn objects_at_repeated_after(doc: &Document, p: Point, opt: HitOptions, scope: Option<NodeId>, mut tops: Vec<NodeId>) -> Vec<NodeId> { - // Each round leaves out the objects found so far (and everything inside them). - while let Some(top) = hit_test_skipping(doc, p, opt, &|id| tops.contains(&id), true).map(|h| h.top_object(scope)) { - if tops.contains(&top) { + // Each round leaves out the objects found so far (and everything inside them). `found` holds + // the same ids as `tops`, which keeps their order. + let mut found: HashSet<NodeId> = tops.iter().copied().collect(); + while let Some(top) = hit_test_skipping(doc, p, opt, &|id| found.contains(&id), true).map(|h| h.top_object(scope)) { + if !found.insert(top) { break; } tops.push(top); diff --git a/crates/doc/src/hit/tests.rs b/crates/doc/src/hit/tests.rs index 39efd78795..ae43485870 100644 --- a/crates/doc/src/hit/tests.rs +++ b/crates/doc/src/hit/tests.rs @@ -1823,6 +1823,216 @@ fn objects_at_matches_repeated_hits_on_random_documents() { } } +/// [`objects_at_repeated_after`] with each found object looked up in the ordered list itself: the +/// reference the tests below hold the set lookup to, and the base that `select_behind_isolation_timing` times. +fn objects_at_repeated_after_by_list(doc: &Document, p: Point, opt: HitOptions, scope: Option<NodeId>, mut tops: Vec<NodeId>) -> Vec<NodeId> { + while let Some(top) = hit_test_skipping(doc, p, opt, &|id| tops.contains(&id), true).map(|h| h.top_object(scope)) { + if tops.contains(&top) { + break; + } + tops.push(top); + } + tops +} + +/// A layer holding a group of `count` overlapping 50 × 50 squares, member `i` at x = 5 × (`i` mod +/// 10), with a square at x = 0 below the group and above it, and one at x = 100 above it: the +/// document, the group and its members, topmost first. +fn isolated_stack(count: u32) -> (Document, NodeId, Vec<NodeId>) { + let mut d = Document::new(200.0, 200.0); + let l = d.layers[0].id; + let square = |d: &mut Document, x: f64| Node::path(d.alloc_id(), shapes::rectangle(Rect::new(x, 0.0, x + 50.0, 50.0)), Appearance::default_art()); + let below = square(&mut d, 0.0); + d.insert(Some(l), usize::MAX, below).unwrap(); + let members: Vec<Node> = (0..count).map(|i| square(&mut d, f64::from(i % 10) * 5.0)).collect(); + let mut ids: Vec<NodeId> = members.iter().map(|n| n.id).collect(); + let g = d.alloc_id(); + d.insert(Some(l), usize::MAX, Node::group(g, members.into_iter().map(Arc::new).collect())).unwrap(); + for x in [0.0, 100.0] { + let above = square(&mut d, x); + d.insert(Some(l), usize::MAX, above).unwrap(); + } + ids.reverse(); + (d, g, ids) +} + +/// Select Behind in an isolated group of 40 overlapping squares, with art around the group above +/// and below them: each member once, front to back, over 41 rounds of hit tests, and nothing where +/// only the art around the group lies. +#[test] +fn select_behind_in_isolation_lists_a_large_stack_once() { + let (d, g, ids) = isolated_stack(40); + let at = |x: f64, scope| objects_at(&d, Point::new(x, 25.0), HitOptions::default(), scope); + assert_eq!(at(47.5, Some(g)), ids); + assert_eq!(at(47.5, Some(g)).iter().collect::<HashSet<_>>().len(), 40, "no object twice"); + assert_eq!(at(47.5, None).len(), 3, "not isolated: the square above, the group and the square below"); + // At x = 17.5 only the members at x = 0 to 20 are hit (the one at 20 on its stroke, within + // the tolerance): `ids[k]` is member 39 - k. + let left: Vec<NodeId> = ids.iter().enumerate().filter(|(k, _)| (39 - k) % 10 <= 4).map(|(_, id)| *id).collect(); + assert_eq!(left.len(), 20); + assert_eq!(at(17.5, Some(g)), left); + assert!(at(125.0, Some(g)).is_empty(), "only the square around the group"); + assert_eq!(at(125.0, None).len(), 1); + let isolated = HitOptions { scope: Some(g), ..HitOptions::default() }; + let p = Point::new(47.5, 25.0); + assert_eq!(objects_at_repeated_after(&d, p, isolated, Some(g), ids[..15].to_vec()), ids, "the objects passed in stay first"); + let (d, g, clip, art) = masked_square(false); + let isolated = HitOptions { scope: Some(g), ..SELECTING }; + for p in [Point::new(140.0, 90.0), Point::new(170.0, 90.0), Point::new(100.0, 90.0)] { + let want = objects_at_repeated_after_by_list(&d, p, isolated, Some(g), vec![]); + assert_eq!(objects_at(&d, p, SELECTING, Some(g)), want, "clip group isolated, {p:?}"); + } + assert_eq!(objects_at(&d, Point::new(170.0, 90.0), SELECTING, Some(g)), vec![art], "the art its mask hides"); + assert!(objects_at(&d, Point::new(140.0, 90.0), SELECTING, Some(g)).contains(&clip), "the mask on its outline"); +} + +/// Documents built at random (nested groups, clipping groups, envelopes in Edit Contents, hidden +/// and locked objects), each object in turn isolated, and each list started with some of the +/// objects already found: the set lookup returns what the ordered-list lookup returns, field for +/// field. +#[test] +fn select_behind_in_isolation_matches_the_list_lookup_on_random_documents() { + let mut seed = 0x2545_f491_u32; + let mut next = move |n: u32| { + seed ^= seed << 13; + seed ^= seed >> 17; + seed ^= seed << 5; + seed % n + }; + fn fill(d: &mut Document, parent: NodeId, depth: u32, next: &mut impl FnMut(u32) -> u32) { + for _ in 0..2 + next(5) { + let id = d.alloc_id(); + let rect = |next: &mut dyn FnMut(u32) -> u32| { + let (x, y) = (f64::from(next(60)), f64::from(next(60))); + Rect::new(x, y, x + 10.0 + f64::from(next(50)), y + 10.0 + f64::from(next(50))) + }; + let mut n = match next(if depth < 3 { 9 } else { 4 }) { + 4 | 5 => Node::group(id, Vec::new()), + 6 => { + let mut g = Node::group(id, Vec::new()); + g.set_clips(true); + g + } + 7 => { + let content = + (0..2).map(|_| Arc::new(Node::path(d.alloc_id(), shapes::rectangle(rect(next)), Appearance::default_art()))).collect(); + Node::new( + id, + NodeKind::Envelope { + content, + kind: Box::new(crate::live::EnvelopeKind::Warp { + style: "arc".to_string(), + bend: 0.0, + h: 0.0, + v: 0.0, + horizontal: true, + version: 0, + }), + fidelity: 100.0, + editing: next(2) == 0, + options: Default::default(), + frame: Box::new(vectorcraft_geom::Affine::IDENTITY), + }, + ) + } + _ => Node::path(id, shapes::rectangle(rect(next)), if next(4) == 0 { Appearance::default() } else { Appearance::default_art() }), + }; + n.visible = next(8) != 0; + n.locked = next(8) == 0; + let group = matches!(n.kind, NodeKind::Group { .. }); + d.insert(Some(parent), usize::MAX, n).unwrap(); + if group { + fill(d, id, depth + 1, next); + } + } + } + let mut compared = 0; + for round in 0..60 { + let mut d = Document::new(120.0, 120.0); + let layer = d.layers[0].id; + fill(&mut d, layer, 0, &mut next); + let mut scopes = vec![None]; + d.walk(|n| { + if n.id != layer { + scopes.push(Some(n.id)); + } + }); + for _ in 0..6 { + let p = Point::new(f64::from(next(120)), f64::from(next(120))); + let opt = HitOptions { outline: next(5) == 0, path_only: next(5) == 0, clip_outlines: next(2) == 0, ..Default::default() }; + for &scope in &scopes { + let opt = HitOptions { scope, ..opt }; + let want = objects_at_repeated_after_by_list(&d, p, opt, scope, vec![]); + let context = format!("round {round}, {p:?}, {opt:?}"); + assert_eq!(objects_at_repeated_after(&d, p, opt, scope, vec![]), want, "{context}"); + if scope.is_some() { + assert_eq!(objects_at(&d, p, opt, scope), want, "{context}"); + } + for found in 1..want.len() { + let start = want[..found].to_vec(); + assert_eq!(objects_at_repeated_after(&d, p, opt, scope, start.clone()), want, "{context}, {found} found"); + assert_eq!(objects_at_repeated_after_by_list(&d, p, opt, scope, start), want, "{context}, {found} found"); + } + compared += usize::from(!want.is_empty()); + } + } + } + assert!(compared > 500, "only {compared} non-empty lists compared"); +} + +/// Times Select Behind in an isolated group of 200 and of 1,000 overlapping squares, the set lookup +/// against the ordered-list lookup, alternating the two in one process: +/// `cargo test --release -p vectorcraft-doc --lib -- --ignored --nocapture select_behind_isolation_timing`. +#[test] +#[ignore = "a timing, not a check"] +fn select_behind_isolation_timing() { + /// This thread's CPU time in nanoseconds on Linux; the elapsed time since `start` elsewhere. + fn clock(start: std::time::Instant) -> u128 { + let cpu = std::fs::read_to_string("/proc/thread-self/schedstat").ok(); + cpu.and_then(|s| s.split_whitespace().next()?.parse().ok()).unwrap_or_else(|| start.elapsed().as_nanos()) + } + type Lookup = fn(&Document, Point, HitOptions, Option<NodeId>, Vec<NodeId>) -> Vec<NodeId>; + let start = std::time::Instant::now(); + println!("clock: {}", if std::fs::metadata("/proc/thread-self/schedstat").is_ok() { "thread CPU time" } else { "wall clock" }); + let p = Point::new(47.5, 25.0); + for count in [200, 1_000] { + let (d, g, ids) = isolated_stack(count); + let opt = HitOptions { scope: Some(g), ..HitOptions::default() }; + assert_eq!(objects_at_repeated_after(&d, p, opt, Some(g), vec![]), ids); + assert_eq!(objects_at_repeated_after_by_list(&d, p, opt, Some(g), vec![]), ids); + // The time per call of `f`: batches of calls double until one takes at least 100 ms. + let per_call = |f: Lookup| { + let mut calls = 1u32; + loop { + let t = clock(start); + for _ in 0..calls { + std::hint::black_box(f(&d, std::hint::black_box(p), opt, Some(g), vec![])); + } + let spent = clock(start) - t; + if spent >= 100_000_000 || calls >= 1 << 20 { + return (spent as f64 / f64::from(calls), calls); + } + calls *= 2; + } + }; + let (mut old, mut new) = (vec![], vec![]); + for _ in 0..7 { + old.push(per_call(objects_at_repeated_after_by_list)); + new.push(per_call(objects_at_repeated_after)); + } + old.sort_by(|a, b| a.0.total_cmp(&b.0)); + new.sort_by(|a, b| a.0.total_cmp(&b.0)); + let (o, n) = (old[3], new[3]); + println!( + "{count} objects: list lookup {:.2} ms per call ({} calls), set lookup {:.2} ms per call ({} calls), median of 7 runs", + o.0 / 1e6, + o.1, + n.0 / 1e6, + n.1 + ); + } +} + /// Select Behind finds a symbol instance by its symbol's art, as a click does: art from /// (100, 60) to (140, 80), outside the 20 × 20 square around the origin, drawn where it lies by /// one instance and 100 pt lower by an instance in a group. From 0febd204d7e797c7228a855d96ea87a90d6a7688 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 17 Nov 2026 11:51:45 -0800 Subject: [PATCH 122/176] EMF/WMF: Use Artboards applies live effects once for all artboards An EMF or WMF export with Use Artboards applied the document's live effects (geometry effects, and symbol art with effects) once for each chosen artboard. vectorcraft_metafile::export_regions now checks every region, applies the effects once and writes one metafile per region. export is its one-region case, and the engine's encode calls export_regions once for all chosen artboards. Each file's bytes and warnings are unchanged. --- crates/engine/src/cmd/fileio/metafile.rs | 9 +- crates/metafile/src/lib.rs | 35 +++-- crates/metafile/src/tests.rs | 171 +++++++++++++++++++++++ docs/target-app-parity.md | 1 + 4 files changed, 204 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/cmd/fileio/metafile.rs b/crates/engine/src/cmd/fileio/metafile.rs index d987d82757..e9e1e882a7 100644 --- a/crates/engine/src/cmd/fileio/metafile.rs +++ b/crates/engine/src/cmd/fileio/metafile.rs @@ -26,13 +26,16 @@ pub(super) fn encode(doc: &Document, p: &Value, use_artboards: Option<bool>, kin Some(true) => pick.resolve(n).map_err(|e| bad(C, e))?.unwrap_or_else(|| (0..n).collect()), _ => vec![pick.one(n).map_err(|e| bad(C, e))?], }; + let rects = boards + .iter() + .map(|&b| doc.artboards.get(b).map(|a| a.rect).ok_or_else(|| bad(C, format!("no artboard {}", b + 1)))) + .collect::<Result<Vec<_>>>()?; // Raster effects (shadows, glows, blurs) as images, as PDF export does. let flat = crate::flatten_raster_effects(doc); let src = flat.as_ref().unwrap_or(doc); + let outs = vectorcraft_metafile::export_regions(src, &rects, kind).map_err(|e| bad(C, e))?; let mut enc = Encoded::default(); - for b in boards { - let region = doc.artboards.get(b).ok_or_else(|| bad(C, format!("no artboard {}", b + 1)))?.rect; - let out = vectorcraft_metafile::export(src, region, kind).map_err(|e| bad(C, e))?; + for (b, out) in boards.into_iter().zip(outs) { enc.files.push((Some(b), out.bytes)); for w in out.warnings { if !enc.warnings.contains(&w) { diff --git a/crates/metafile/src/lib.rs b/crates/metafile/src/lib.rs index 61126ef228..c4a84aa8e6 100644 --- a/crates/metafile/src/lib.rs +++ b/crates/metafile/src/lib.rs @@ -1,6 +1,7 @@ //! Windows metafiles: hand-written EMF and WMF writers and readers. //! -//! [`export`] writes the visible art over one region of a document (an artboard) as a metafile: +//! [`export`] writes the visible art over one region of a document (an artboard) as a metafile, +//! and [`export_regions`] one metafile per region: //! //! - **EMF**: paths keep their Bézier curves, fills are solid brushes, strokes geometric pens with //! their width, caps, joins, miter limit and dashes; strokes a pen can't draw (aligned inside or @@ -79,20 +80,36 @@ pub struct Output { /// not); template layers, hidden objects and guides are left out. Raster effects should be turned /// into images before (the engine does); the ones left are reported and left out. pub fn export(doc: &Document, region: Rect, kind: Kind) -> Result<Output, String> { - let r = region.abs(); - if ![r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite()) || r.width() <= 0.0 || r.height() <= 0.0 { + Ok(export_regions(doc, &[region], kind)?.pop().unwrap_or_default()) +} + +/// Write the visible art of `doc` over each of `regions` as `kind`, one metafile per region in the +/// same order, each as [`export`] writes it over that region. The live effects are applied once +/// for all of them. When any region is empty, nothing is written and the result is an error. +pub fn export_regions(doc: &Document, regions: &[Rect], kind: Kind) -> Result<Vec<Output>, String> { + let regions: Vec<Rect> = regions.iter().map(|r| r.abs()).collect(); + if regions.iter().any(|r| ![r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite()) || r.width() <= 0.0 || r.height() <= 0.0) { return Err("the export region is empty".into()); } + if regions.is_empty() { + return Ok(Vec::new()); + } // The scene writes layers that do not print and leaves hidden layers and objects out. let layers = vectorcraft_effects::WrittenLayers { hidden: false, non_printing: true, hidden_objects: false }; let baked = vectorcraft_effects::bake_document_placing_symbols(doc, kind == Kind::Emf, layers); let doc = baked.as_ref().unwrap_or(doc); - let (ops, mut warnings) = scene::Scene::new(doc, r, kind == Kind::Emf).run(); - let bytes = match kind { - Kind::Emf => emf::write(&ops, r, doc.info_title()), - Kind::Wmf => wmf::write(&ops, r, &mut warnings), - }; - Ok(Output { bytes, warnings }) + let outputs = regions + .into_iter() + .map(|r| { + let (ops, mut warnings) = scene::Scene::new(doc, r, kind == Kind::Emf).run(); + let bytes = match kind { + Kind::Emf => emf::write(&ops, r, doc.info_title()), + Kind::Wmf => wmf::write(&ops, r, &mut warnings), + }; + Output { bytes, warnings } + }) + .collect(); + Ok(outputs) } /// A metafile read into a document. diff --git a/crates/metafile/src/tests.rs b/crates/metafile/src/tests.rs index 2314ccb637..658628f107 100644 --- a/crates/metafile/src/tests.rs +++ b/crates/metafile/src/tests.rs @@ -396,6 +396,177 @@ fn hidden_and_offboard_art_is_left_out() { assert!(export(&d, Rect::new(0.0, 0.0, 0.0, 10.0), Kind::Emf).is_err(), "an empty region"); } +/// One metafile of `doc` over `region`, applying the live effects for this region alone: what +/// [`export`] did for each region before [`export_regions`] applied them once for all regions. +fn export_baking_each_region(doc: &Document, region: Rect, kind: Kind) -> Result<Output, String> { + let r = region.abs(); + if ![r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite()) || r.width() <= 0.0 || r.height() <= 0.0 { + return Err("the export region is empty".into()); + } + let layers = vectorcraft_effects::WrittenLayers { hidden: false, non_printing: true, hidden_objects: false }; + let baked = vectorcraft_effects::bake_document_placing_symbols(doc, kind == Kind::Emf, layers); + let doc = baked.as_ref().unwrap_or(doc); + let (ops, mut warnings) = crate::scene::Scene::new(doc, r, kind == Kind::Emf).run(); + let bytes = match kind { + Kind::Emf => crate::emf::write(&ops, r, doc.info_title()), + Kind::Wmf => crate::wmf::write(&ops, r, &mut warnings), + }; + Ok(Output { bytes, warnings }) +} + +/// A Zig Zag effect with its default settings. +fn zig_zag() -> vectorcraft_doc::Effect { + vectorcraft_doc::Effect { id: "distort.zigZag".into(), params: Default::default(), visible: true } +} + +/// `boards` 100 pt squares side by side, each holding `paths` rectangles with a live Zig Zag +/// and a gradient-filled one, and every second one an instance of a symbol whose art has a Zig +/// Zag too; `boards` regions, one over each square. +fn zig_zag_boards(boards: usize, paths: usize) -> (Document, Vec<Rect>) { + let mut d = Document::new(100.0 * boards as f64, 100.0); + let mut art = path(shapes::rectangle(Rect::new(0.0, 0.0, 30.0, 20.0)), blue(), red(), 1.0); + art.appearance.effects.push(zig_zag()); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Zig".into(), art: Arc::new(art) }); + let g = Paint::Gradient(Box::new(GradientPaint::new(Gradient::default()))); + for b in 0..boards { + let x = 100.0 * b as f64; + for i in 0..paths { + let at = (i % 9) as f64 * 9.0; + let mut n = path(shapes::rectangle(Rect::new(x + at + 2.0, at + 2.0, x + at + 20.0, at + 15.0)), red(), blue(), 0.5); + n.appearance.effects.push(zig_zag()); + add(&mut d, n); + } + add(&mut d, path(shapes::rectangle(Rect::new(x + 60.0, 60.0, x + 90.0, 90.0)), g.clone(), Paint::None, 0.0)); + if b % 2 == 1 { + let inst = Node::new(NodeId(0), NodeKind::SymbolInstance { symbol: "Zig".into(), xf: Affine::translate((x + 50.0, 10.0)) }); + add(&mut d, inst); + } + } + let regions = (0..boards).map(|b| Rect::new(100.0 * b as f64, 0.0, 100.0 * (b + 1) as f64, 100.0)).collect(); + (d, regions) +} + +/// Each region's metafile is byte for byte, and warning for warning, what a separate export of +/// that region writes, in EMF and WMF, in the regions' order and in reverse. +#[test] +fn export_regions_writes_what_each_region_writes_alone() { + let (d, mut regions) = zig_zag_boards(3, 2); + let layers = vectorcraft_effects::WrittenLayers { hidden: false, non_printing: true, hidden_objects: false }; + assert!(vectorcraft_effects::bake_document_placing_symbols(&d, true, layers).is_some(), "the document has live effects to apply"); + for _ in 0..2 { + for kind in [Kind::Emf, Kind::Wmf] { + let outs = export_regions(&d, ®ions, kind).unwrap(); + assert_eq!(outs.len(), regions.len()); + for (r, out) in regions.iter().zip(&outs) { + let alone = export_baking_each_region(&d, *r, kind).unwrap(); + assert!(out.bytes == alone.bytes, "{kind:?} over {r:?}: the bytes differ"); + assert_eq!(out.warnings, alone.warnings, "{kind:?} over {r:?}"); + let one = export(&d, *r, kind).unwrap(); + assert!(one.bytes == alone.bytes, "{kind:?} over {r:?}: export's bytes differ"); + assert_eq!(one.warnings, alone.warnings, "{kind:?} over {r:?}"); + } + if kind == Kind::Wmf { + assert!(outs.iter().all(|o| o.warnings.iter().any(|w| w.contains("gradients"))), "{:?}", outs[0].warnings); + } + } + regions.reverse(); + } +} + +/// An empty region among valid ones writes nothing and is the one error; no region writes no +/// metafile. +#[test] +fn export_regions_with_an_empty_region_writes_nothing() { + let (d, regions) = zig_zag_boards(2, 1); + for kind in [Kind::Emf, Kind::Wmf] { + for empty in [Rect::new(10.0, 10.0, 10.0, 50.0), Rect::new(0.0, 0.0, f64::NAN, 10.0), Rect::new(0.0, 0.0, f64::INFINITY, 10.0)] { + let with_empty = [regions[0], empty, regions[1]]; + assert_eq!(export_regions(&d, &with_empty, kind).map(|o| o.len()), Err("the export region is empty".to_string()), "{kind:?}"); + } + assert!(export_regions(&d, &[], kind).unwrap().is_empty(), "{kind:?}"); + // A region given right to left or bottom to top is the same region. + let flipped = Rect::new(regions[1].x1, regions[1].y1, regions[1].x0, regions[1].y0); + let outs = export_regions(&d, &[flipped], kind).unwrap(); + assert!(outs[0].bytes == export(&d, regions[1], kind).unwrap().bytes, "{kind:?}"); + } +} + +/// The CPU time all of this process's threads have used, from Linux's scheduler statistics; `None` +/// elsewhere. +fn process_cpu() -> Option<std::time::Duration> { + let mut ns = 0u64; + for task in std::fs::read_dir("/proc/self/task").ok()? { + let stat = std::fs::read_to_string(task.ok()?.path().join("schedstat")).ok()?; + ns += stat.split_whitespace().next()?.parse::<u64>().ok()?; + } + Some(std::time::Duration::from_nanos(ns)) +} + +/// The time `f` takes: this process's CPU time where Linux reports it, otherwise the wall clock. +fn time<T>(f: impl FnOnce() -> T) -> (std::time::Duration, T) { + match process_cpu() { + Some(before) => { + let t = f(); + (process_cpu().map_or(std::time::Duration::ZERO, |after| after.saturating_sub(before)), t) + } + None => { + let start = std::time::Instant::now(); + let t = f(); + (start.elapsed(), t) + } + } +} + +/// Timings of an export of 1, 2 and 8 artboards that applies the live effects once for each +/// artboard and of [`export_regions`], which applies them once, in EMF and WMF: 500 rectangles with +/// a live Zig Zag on each artboard. The two take turns going first, 7 runs each, and every run's +/// files are compared. Ignored by default; it prints the median, fastest and slowest run and sets +/// no bound on them: +/// `cargo test --release -p vectorcraft-metafile --lib export_regions_perf -- --ignored --nocapture`. +#[test] +#[ignore = "a benchmark: run with --ignored --nocapture"] +fn export_regions_perf() { + const RUNS: usize = 7; + let ms = |d: std::time::Duration| d.as_secs_f64() * 1000.0; + eprintln!("export_regions_perf: {}", if process_cpu().is_some() { "process CPU time" } else { "wall clock" }); + eprintln!("export_regions_perf: {:>6} {:<4} {:>32} {:>32}", "boards", "kind", "bake per board ms (min-max)", "bake once ms (min-max)"); + for boards in [1, 2, 8] { + let (d, regions) = zig_zag_boards(boards, 500); + for kind in [Kind::Emf, Kind::Wmf] { + let each = || regions.iter().map(|r| export_baking_each_region(&d, *r, kind).unwrap()).collect::<Vec<_>>(); + let once = || export_regions(&d, ®ions, kind).unwrap(); + let (mut old, mut new) = (Vec::new(), Vec::new()); + for run in 0..RUNS { + let ((to, a), (tn, b)) = if run % 2 == 0 { + let o = time(each); + (o, time(once)) + } else { + let n = time(once); + (time(each), n) + }; + old.push(to); + new.push(tn); + assert_eq!(a.len(), b.len()); + for (a, b) in a.iter().zip(&b) { + assert!(a.bytes == b.bytes && a.warnings == b.warnings, "{boards} boards, {kind:?}"); + } + } + old.sort(); + new.sort(); + eprintln!( + "export_regions_perf: {boards:>6} {:<4} {:>12.1} ({:>8.1}-{:>8.1}) {:>12.1} ({:>8.1}-{:>8.1})", + kind.id(), + ms(old[RUNS / 2]), + ms(old[0]), + ms(old[RUNS - 1]), + ms(new[RUNS / 2]), + ms(new[0]), + ms(new[RUNS - 1]), + ); + } + } +} + #[test] fn an_instance_whose_art_reaches_the_artboard_is_written() { // The symbol's red rectangle, (100, 100) to (140, 140), drawn from (-50, -50): on the artboard, diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index e9fc9a6820..473b1c815f 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1823,6 +1823,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur A geometry effect on a symbol instance's fill reshapes the filled shapes of the symbol's art and leaves their strokes as they are; one on the instance's stroke reshapes the stroked shapes and leaves their fills as they are. The shapes keep their colors. Only the instance's topmost fill and topmost stroke count, and only while they are visible with an opacity above 0. The canvas and Object › Expand Appearance use the same art, SVG and PDF export bake the same shapes, and Expand Appearance turns the instance into an editable group in one undo step. A group's own fills and strokes in the art take the effects too. An instance inside the art passes the effects on to its own art, and a dynamic symbol's instance reshapes the fills and strokes it paints on the art. How the effects map onto the symbol's art is VectorCraft's own rule. The help page <https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-filter-effects/apply-and-modify-effects.html> describes effects on one fill or stroke, and the help page <https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/expand-objects.html> describes Expand Appearance (engine `expand::a_symbol_instance_fill_effect_reshapes_its_filled_art_and_expands`, `a_symbol_instance_stroke_effect_reshapes_its_stroked_art_and_expands`, `a_stroke_effect_reshapes_a_stroke_a_dynamic_instance_adds`, `a_fill_effect_reshapes_the_fill_of_a_group_in_the_art`, `only_the_topmost_visible_instance_fill_reshapes_the_art`, `a_nested_symbol_instance_takes_the_outer_fill_effect`, `export_bakes_a_symbol_instance_fill_effect`, `a_fill_effect_on_an_instance_of_a_symbol_that_holds_itself_ends`). Existing documents with a geometry effect on a symbol instance's fill or stroke draw differently: before, the effect drew nothing. Live effects inside a symbol's art (geometry effects, color adjustments and the rest that export bakes) are written where each instance places the art in PDF, print, EPS and DXF, as the canvas draws them: the art is placed first and its effects are applied after, so an instance that scales its art does not scale the distance a Transform effect moves it. Symbols nested in the art, a dynamic symbol instance's own paint changes and the stain an instance's fill gives its art are kept, and the art is stained before its effects apply. A linked instance's PDF link covers its art where the effects draw it. A symbol whose art holds itself stops at the nesting limit, and the symbols' own art keeps its effects. An instance stays an instance in these exports when the objects its art makes once baked (the copies a Transform effect makes included) would take the export's placed symbol art past 16,000,000 objects, or when its baked art would draw deeper than the 128 levels a document may draw; these are VectorCraft's own limits. Art baked for an instance that then stays an instance still counts toward that limit, and while an instance's art bakes, the art's own objects are held in the limit for the instances nested in it. Instances the export leaves out (hidden ones, those in hidden groups, on template layers, and on hidden layers or layers that do not print when the export leaves those out) are not placed and do not count toward that limit. Before, these exports wrote the art without its effects (effects `bake::placing_symbols_bakes_their_art_where_each_instance_places_it`, `placing_symbols_reaches_the_art_of_nested_instances`, `placing_a_symbol_that_holds_itself_stops`, `placing_symbols_keeps_dynamic_instances_changes`, `placing_symbols_keeps_the_instances_stain`, `placing_symbols_counts_the_baked_art`, `placing_symbols_counts_nested_art_once`, `placing_symbols_holds_the_outer_art_while_it_bakes`, `placing_symbols_counts_the_art_it_drops`, `placing_symbols_counts_art_dropped_for_depth_against_later_baked_art`, `placing_symbols_keeps_the_baked_art_within_the_drawn_depth`, `placing_symbols_skips_instances_the_export_leaves_out`; doc `depth::tests::drawn_heights_measure_objects_outside_the_layers`; PDF, print, EPS and DXF `symbol_art_effects_are_written_where_they_draw`, `symbol_art_effects_print_where_they_draw`; PDF `a_stained_instance_keeps_its_stain_when_its_art_has_effects`, `a_linked_instance_keeps_its_link_when_its_art_has_effects`). EMF, WMF and SVG export write the same symbol art the same way: an instance of a symbol whose art, or the art of a symbol nested in it, has such effects is written as that art placed by the instance and then baked, so a square that a Transform effect moves 100 pt right draws 100 pt right of where the instance places it at any scale or rotation, and art the effect moves onto the artboard is written. EMF and SVG clip 9-slice cells and WMF does not, as each places other instances. In SVG those instances use no `<symbol>`, and instances of symbols without such effects still share one; named objects in a symbol's art take no ids there, as in an instance with its own copy of the art, so two instances do not write the same id; with Hidden Layers on, hidden instances are placed too and written hidden. An SVG instance nested in another instance's art is shared through `<use>` only when the transform it is drawn with, the outer instances' included, keeps the shared art as the canvas draws it, so a nested stroke keeps its weight in a scaled instance. Preserve Editing still embeds the document with its live effects. Before, these exports wrote the art without its effects (metafile `tests::import::symbol_art_effects_are_written_where_they_draw`; SVG `symbols_layers::symbol_art_effects_are_written_where_the_canvas_draws_them`, `a_kept_hidden_instance_is_written_with_its_symbols_effects`, `instances_written_as_their_art_give_its_names_no_id`, `a_nested_instance_is_shared_only_under_the_transform_it_is_drawn_with`; effects `bake::placing_symbols_skips_instances_the_export_leaves_out`). + EMF and WMF export with Use Artboards applies the document's live effects once for all the chosen artboards instead of once for each, and writes the same files byte for byte (metafile `tests::export_regions_writes_what_each_region_writes_alone`; `export_regions_perf` times it). When an export bakes a symbol instance with geometry effects inside the art of another such instance, it counts the art the inner instance bakes to, the copies its symbol's effects make included, against the 262,144 objects of symbol art one export bakes that way; it counted only the symbol's art before its effects. An instance whose baked art would pass that count stays an instance with its effects, and the art baked for it still counts against the instances after it. These are VectorCraft's own limits (effects `bake::nested_reshape_counts_baked_art`, `nested_reshape_refusal_keeps_its_work_counted`, `nested_reshape_refused_siblings_bake_once`, `nested_reshape_counts_successful_descendants_once`). A raster effect (Drop Shadow, Outer Glow, Gaussian Blur and the other effects that paint pixels) on a symbol instance's topmost fill draws on each filled shape of the symbol's art, and one on its topmost stroke draws on each stroked shape, after any geometry effects listed before it, under the same rules as geometry effects: only a visible fill or stroke with an opacity above 0 counts, a group's own fills and strokes in the art take the effect, and an instance inside the art passes it on. Each shape gets its own shadow or glow, which is VectorCraft's own rule. The canvas, Use Preview Bounds and the drawn bounds, SVG and PDF export draw it, and Object › Expand Appearance is enabled for such an instance and makes the effect an image at the document's raster effects resolution, in one undo step (engine `expand::a_symbol_instance_fill_shadow_shadows_its_filled_art`, `a_symbol_instance_stroke_shadow_shadows_only_its_stroked_art`, `a_symbol_instance_fill_shadow_follows_the_fill_offset_before_it`, `a_nested_symbol_instance_takes_the_outer_fill_shadow`, `export_draws_a_symbol_instance_fill_shadow`). Existing documents with a raster effect on a symbol instance's fill or stroke draw differently: before, the effect drew nothing. Object › Expand Appearance turns a symbol instance whose topmost fill or stroke has only raster effects into its art as well, with the effect's image under the art (a shadow or glow) or in its place (a blur, feather or inner glow). A symbol instance inside the art whose topmost fill or stroke has a geometry or raster effect, its own or one the outer instance passes on, becomes its art and image the same way, and so do the instances in that art, within the nesting and symbol art limits; an instance of a missing symbol stays an instance. One Expand Appearance makes at most 1,024 images of raster effects, holding 256 megapixels in all (VectorCraft's own limits); an object or instance whose image would go past them stays as it is, with its raster effects, and the result reports how many with `rasterLeft` and a warning. Within those limits no live instance or raster effect is left from those effects, so the result no longer changes with the symbols; an instance left by the image limits still follows its symbol. The help page <https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/expand-objects.html> describes Expand Appearance turning appearance attributes into objects, and the help page <https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-filter-effects/vector-and-raster-effects.html> describes expanding an effect into permanent raster data; expanding nested instances this way is VectorCraft's own rule (engine `expand::a_nested_instance_fill_shadow_becomes_an_image_when_the_outer_art_expands`, `an_outer_fill_shadow_expands_the_instance_and_reaches_the_nested_art`, `a_nested_instance_fill_blur_becomes_an_image_when_the_outer_art_expands`, `a_hidden_nested_instance_fill_shadow_makes_no_image`, `a_nested_instance_of_a_missing_symbol_stays_an_instance`, `nested_instance_raster_effects_stop_at_the_image_limit`). Before, an instance whose fill or stroke had only a shadow or glow stayed an instance over the image, and a raster effect on an instance in the art stayed live. From 6252d4b29e4c9410401d9366d04885eeec4d7e95 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 17 Nov 2026 11:56:49 -0800 Subject: [PATCH 123/176] Pencil: path.freehand refuses connect without extend path.freehand ignored a connect given without extend and drew a new path. It now refuses it with "connect needs extend". A connect given with extend is checked (its id, a path other than the one extended with an open end, and an end of "start" or "end") before a stroke of one point returns, so a bad connect is refused there too, and brush.freehand no longer changes the path's brush or the selection before refusing it. A null connect is still a key left out. Docs: params text, docs/mcp.md, docs/target-app-parity.md. i18n: the new message in the catalogs that carry the other connect messages. --- crates/engine/src/cmd/draw2/commands.rs | 2 +- crates/engine/src/cmd/draw2/freehand.rs | 43 ++++++++++--------- crates/engine/src/tests/brushsym.rs | 23 +++++++++++ crates/engine/src/tests/draw2.rs | 55 +++++++++++++++++++++++++ crates/ui-egui/src/i18n/cs.tsv | 1 + crates/ui-egui/src/i18n/da.tsv | 1 + crates/ui-egui/src/i18n/de.tsv | 1 + crates/ui-egui/src/i18n/fr.tsv | 1 + crates/ui-egui/src/i18n/hi.tsv | 1 + crates/ui-egui/src/i18n/hu.tsv | 1 + crates/ui-egui/src/i18n/it.tsv | 1 + crates/ui-egui/src/i18n/ja.tsv | 1 + crates/ui-egui/src/i18n/ka.tsv | 1 + crates/ui-egui/src/i18n/ko.tsv | 1 + crates/ui-egui/src/i18n/nl.tsv | 1 + crates/ui-egui/src/i18n/pl.tsv | 1 + crates/ui-egui/src/i18n/pt-br.tsv | 1 + crates/ui-egui/src/i18n/ru.tsv | 1 + crates/ui-egui/src/i18n/sv.tsv | 1 + crates/ui-egui/src/i18n/tr.tsv | 1 + crates/ui-egui/src/i18n/uk.tsv | 1 + crates/ui-egui/src/i18n/zh-hans.tsv | 1 + crates/ui-egui/src/i18n/zh-hant.tsv | 1 + docs/mcp.md | 5 ++- docs/target-app-parity.md | 1 + 25 files changed, 127 insertions(+), 21 deletions(-) diff --git a/crates/engine/src/cmd/draw2/commands.rs b/crates/engine/src/cmd/draw2/commands.rs index 05dae578ce..e13024660d 100644 --- a/crates/engine/src/cmd/draw2/commands.rs +++ b/crates/engine/src/cmd/draw2/commands.rs @@ -11,7 +11,7 @@ pub fn specs() -> Vec<CommandSpec> { "Pencil", [], None, - "{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1: the stroke keeps it, for Calligraphic and Scatter brushes with Pressure variation; a point without one presses fully. Pen tilt in degrees, each −90..90, x positive leaning right and y leaning down the page, and barrel rotation in degrees clockwise, 0..360: the stroke keeps how far the pen leaned, which way and how far its barrel turned, for brushes with Tilt, Bearing and Rotation variation; null for what a point lacks. A pressure, tilt or rotation outside its range, or a point array of more than six numbers, is an error), fidelity?: pt (1.5; from 0.000015625 (0.01 / 640) to 100 / 0.0313 (about 3194.89), the Pencil's and the Paintbrush's 0.01 to 100 px Fidelity at the highest and the lowest zoom; a value outside that range is an error. The tools send their Fidelity in pixels divided by the zoom, kept within the range), fit?: bool (true; false: the points are joined by straight segments, as the Pencil previews a stroke with Live curve fitting off), closed?, style?: \"pencil\" (default) | \"brush\", fill?: bool, keepSelected?: bool (true: the drawn or continued path is selected; false: a new path leaves nothing selected, and a continued or redrawn one is deselected while the rest of the selection stays), extend?: {id, end?: \"end\" (default) | \"start\"}, connect?: {id, end: \"start\"|\"end\"}, redraw?: {id, within?: pt (12)}} fit a freehand stroke → {id}. extend continues the path from that end, and closes it when `closed` is true (left out, when the stroke ends within four Fidelities of the path's other end, 6 to 400 pt); with connect, the stroke ends on that end of another path's last open subpath and joins it on, in one path with the extended path's appearance (the other path is removed when nothing of it is left); redraw (Edit Selected Paths) replaces the section of the path between where the stroke starts and ends, each within `within` of one subpath (the shorter way round a closed one), and draws a new path when the stroke doesn't end on it. Any other style, extend end or connect end is an error, and nothing changes", + "{points: [[x,y]…] or [[x,y,pressure]…] or [[x,y,pressure,tiltX,tiltY,rotation]…] (pen pressure 0..1: the stroke keeps it, for Calligraphic and Scatter brushes with Pressure variation; a point without one presses fully. Pen tilt in degrees, each −90..90, x positive leaning right and y leaning down the page, and barrel rotation in degrees clockwise, 0..360: the stroke keeps how far the pen leaned, which way and how far its barrel turned, for brushes with Tilt, Bearing and Rotation variation; null for what a point lacks. A pressure, tilt or rotation outside its range, or a point array of more than six numbers, is an error), fidelity?: pt (1.5; from 0.000015625 (0.01 / 640) to 100 / 0.0313 (about 3194.89), the Pencil's and the Paintbrush's 0.01 to 100 px Fidelity at the highest and the lowest zoom; a value outside that range is an error. The tools send their Fidelity in pixels divided by the zoom, kept within the range), fit?: bool (true; false: the points are joined by straight segments, as the Pencil previews a stroke with Live curve fitting off), closed?, style?: \"pencil\" (default) | \"brush\", fill?: bool, keepSelected?: bool (true: the drawn or continued path is selected; false: a new path leaves nothing selected, and a continued or redrawn one is deselected while the rest of the selection stays), extend?: {id, end?: \"end\" (default) | \"start\"}, connect?: {id, end: \"start\"|\"end\"} (only with extend), redraw?: {id, within?: pt (12)}} fit a freehand stroke → {id}. extend continues the path from that end, and closes it when `closed` is true (left out, when the stroke ends within four Fidelities of the path's other end, 6 to 400 pt); with connect, the stroke ends on that end of another path's last open subpath and joins it on, in one path with the extended path's appearance (the other path is removed when nothing of it is left); redraw (Edit Selected Paths) replaces the section of the path between where the stroke starts and ends, each within `within` of one subpath (the shorter way round a closed one), and draws a new path when the stroke doesn't end on it. Any other style, extend end or connect end, connect without extend, and a connect that names no other path with an open end are errors, a stroke of one point included, and nothing changes", has_doc, freehand ), diff --git a/crates/engine/src/cmd/draw2/freehand.rs b/crates/engine/src/cmd/draw2/freehand.rs index 241d252816..1557f93d8b 100644 --- a/crates/engine/src/cmd/draw2/freehand.rs +++ b/crates/engine/src/cmd/draw2/freehand.rs @@ -209,7 +209,11 @@ pub(crate) fn freehand_brushed(s: &mut Session, p: &Value, brush_name: Option<&s let label = if brush || brush_name.is_some() { "Paintbrush" } else { "Pencil" }; let keep_selected = switch_or(p, "keepSelected", true, C)?; let filled = switch_or(p, "fill", false, C)?; - if let Some(ext) = p.get("extend").filter(|v| !v.is_null()) { + let extend = p.get("extend").filter(|v| !v.is_null()); + if extend.is_none() && p.get("connect").is_some_and(|v| !v.is_null()) { + return Err(bad(C, "connect needs extend")); + } + if let Some(ext) = extend { let id = object_param(ext, "id", C)?.ok_or_else(|| bad(C, "extend needs id"))?; let at_start = match ext.get("end").filter(|v| !v.is_null()).map(Value::as_str) { None | Some(Some("end")) => false, @@ -234,26 +238,9 @@ pub(crate) fn freehand_brushed(s: &mut Session, p: &Value, brush_name: Option<&s }; let Some(p0) = pts.first_mut() else { return Err(bad(C, "needs points")) }; *p0 = end; - if pts.len() < 2 { - // No stroke to add: the brush alone changes, when it is not the path's already, and the - // path is selected or deselected as a longer continuation leaves it. - if let Some(name) = brush_name - && s.doc()?.doc.node(target).and_then(|n| n.appearance.stroke()).is_some_and(|st| st.brush.as_deref() != Some(name)) - { - s.edit("Paintbrush", |d, sel| { - set_brush(d, target, name); - if keep_selected { - sel.set([id]); - } else { - sel.remove(id); - } - Ok(()) - })?; - } - return Ok(json!({ "id": id.0 })); - } // A stroke that ends on an open end of another path connects the two: (that path, its last // open subpath, that subpath starting at the end the stroke ends on, it ends at its end). + // It is checked before a stroke of one point returns, so a bad `connect` is refused there too. let connect = match p.get("connect").filter(|v| !v.is_null()) { Some(cn) => { let other = object_param(cn, "id", C)?.ok_or_else(|| bad(C, "connect needs id"))?; @@ -276,6 +263,24 @@ pub(crate) fn freehand_brushed(s: &mut Session, p: &Value, brush_name: Option<&s } None => None, }; + if pts.len() < 2 { + // No stroke to add: the brush alone changes, when it is not the path's already, and the + // path is selected or deselected as a longer continuation leaves it. + if let Some(name) = brush_name + && s.doc()?.doc.node(target).and_then(|n| n.appearance.stroke()).is_some_and(|st| st.brush.as_deref() != Some(name)) + { + s.edit("Paintbrush", |d, sel| { + set_brush(d, target, name); + if keep_selected { + sel.set([id]); + } else { + sel.remove(id); + } + Ok(()) + })?; + } + return Ok(json!({ "id": id.0 })); + } // `closed`, when given, says whether the stroke closes the path: the Pencil and the // Paintbrush send it, by their Close Paths When Ends Are Within and Alt at the release. // Left out, an extending stroke that ends within four Fidelities of the path's other end diff --git a/crates/engine/src/tests/brushsym.rs b/crates/engine/src/tests/brushsym.rs index 77258b7eb7..9b72297a6b 100644 --- a/crates/engine/src/tests/brushsym.rs +++ b/crates/engine/src/tests/brushsym.rs @@ -1071,6 +1071,29 @@ fn brush_freehand_continued_by_one_point_follows_keep_selected() { assert_eq!(s.doc().unwrap().history.undo.len(), undo, "the same brush again: no undo step"); } +/// A `brush.freehand` call that continues a path by one point with a bad `connect` is refused +/// before the path's brush changes: the brush, the selection and the undo history stay as they were. +#[test] +fn brush_freehand_continued_by_one_point_refuses_a_bad_connect() { + let mut s = session(); + let r = s.execute("brush.freehand", &json!({"points": [[10, 10], [60, 40], [120, 10]], "style": "brush", "brush": "Charcoal"})).unwrap(); + let p = NodeId(r["id"].as_u64().unwrap()); + let a = rect(&mut s, 200.0, 200.0, 10.0, 10.0); + select(&mut s, &[a]); + let undo = undo_steps(&s); + let one = json!({"points": [[120, 10]], "extend": {"id": p.0, "end": "end"}, "brush": "Dots"}); + for connect in + [json!({"id": p.0, "end": "end"}), json!({"id": a.0, "end": "middle"}), json!({"end": "end"}), json!({"id": 999_999, "end": "end"})] + { + let mut params = one.clone(); + params["connect"] = connect; + assert!(s.execute("brush.freehand", ¶ms).is_err(), "{params}"); + assert_eq!(brush_of(&s, p).as_deref(), Some("Charcoal"), "{params}: the brush stays"); + assert_eq!(selected(&s), [a], "{params}: the selection stays"); + assert_eq!(undo_steps(&s), undo, "{params}: no undo step"); + } +} + /// `brush.freehand` refuses a brush for a path with no stroke (a continued path, a redrawn one /// and a new filled pencil path while the stroke is None) instead of reporting it painted: the /// document, the selection and the undo history stay as they were. Without a brush the path is diff --git a/crates/engine/src/tests/draw2.rs b/crates/engine/src/tests/draw2.rs index f4af510230..3be78e65bd 100644 --- a/crates/engine/src/tests/draw2.rs +++ b/crates/engine/src/tests/draw2.rs @@ -414,6 +414,61 @@ fn pencil_refuses_an_unknown_style_or_extend_end() { assert!(ends.contains(&Point::new(0.0, 100.0)) && ends.contains(&Point::new(200.0, 100.0)), "continued from its start: {ends:?}"); } +/// `path.freehand` refuses a `connect` without `extend`, and checks a `connect` given with `extend` +/// before a stroke of one point returns, so a bad one is refused there too; a refused call changes +/// neither the document nor the undo history. A `connect` of null is a key left out. +#[test] +fn pencil_refuses_connect_without_extend_and_a_bad_connect_for_one_point() { + let mut s = session(); + let a = line(&mut s, 100.0, 100.0, 200.0, 100.0); + let b = line(&mut s, 300.0, 200.0, 400.0, 200.0); + let closed = NodeId(s.execute("path.create", &json!({"d": "M0 500 L50 500 L50 550 Z"})).unwrap()["id"].as_u64().unwrap()); + let inner = NodeId(s.execute("path.create", &json!({"d": "M600 500 L650 500"})).unwrap()["id"].as_u64().unwrap()); + s.execute("select.set", &json!({"ids": [inner.0]})).unwrap(); + let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap()); + let stroke = json!({"points": [[200, 100], [250, 150], [300, 200]]}); + for connect in [json!({"id": b.0, "end": "start"}), json!({"id": b.0, "end": "middle"}), json!({"id": b.0}), json!({})] { + refuses_with(&mut s, "path.freehand", &with(&stroke, json!({ "connect": connect })), "connect needs extend"); + refuses_with(&mut s, "path.freehand", &with(&stroke, json!({"extend": null, "connect": connect})), "connect needs extend"); + } + let refused = |s: &mut Session, p: &serde_json::Value| { + let before = s.doc().unwrap().doc.clone(); + let undo = undo_steps(s); + assert!(s.execute("path.freehand", p).is_err(), "{p}"); + assert!(s.doc().unwrap().doc == before, "{p} changed the document"); + assert_eq!(undo_steps(s), undo, "{p} left an undo step"); + }; + refused(&mut s, &with(&stroke, json!({"connect": "b"}))); + let one = json!({"points": [[200, 100]], "extend": {"id": a.0, "end": "end"}}); + let end = "connect end must be \"start\" or \"end\""; + for e in [json!("middle"), json!(1), json!(null)] { + refuses_with(&mut s, "path.freehand", &with(&one, json!({"connect": {"id": b.0, "end": e}})), end); + } + refuses_with(&mut s, "path.freehand", &with(&one, json!({"connect": {"id": b.0}})), end); + refuses_with(&mut s, "path.freehand", &with(&one, json!({"connect": {"end": "end"}})), "connect needs id"); + refuses_with(&mut s, "path.freehand", &with(&one, json!({"connect": {"id": "b", "end": "end"}})), "`id` must be a whole number"); + let other = "connect needs a path other than the one extended"; + refuses_with(&mut s, "path.freehand", &with(&one, json!({"connect": {"id": a.0, "end": "end"}})), other); + refuses_with(&mut s, "path.freehand", &with(&one, json!({"connect": {"id": closed.0, "end": "end"}})), "connect path has no open end"); + for p in [ + with(&one, json!({"connect": "b"})), + with(&one, json!({"connect": {"id": 999_999, "end": "end"}})), + with(&one, json!({"connect": {"id": group.0, "end": "end"}})), + ] { + refused(&mut s, &p); + } + assert_eq!((paths(&s).len(), path(&s, a).anchor_count(), path(&s, b).anchor_count()), (4, 2, 2), "refused: nothing changed"); + // A good `connect`, or a null one, on a stroke of one point leaves the path as it was. + let undo = undo_steps(&s); + for connect in [json!({"id": b.0, "end": "start"}), json!(null)] { + assert_eq!(s.execute("path.freehand", &with(&one, json!({ "connect": connect }))).unwrap()["id"], json!(a.0)); + } + assert_eq!((path(&s, a).anchor_count(), undo_steps(&s)), (2, undo)); + // Null without `extend`, `connect` is left out, and the stroke draws a new path. + s.execute("path.freehand", &with(&stroke, json!({"connect": null}))).unwrap(); + assert_eq!(paths(&s).len(), 5); +} + /// With Keep selected off, a compound path whose direct-selected anchors all lie on the subpath /// that connect joins on is no longer selected, and Delete then has nothing to delete. #[test] diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index a5d7bb948a..794c29ee99 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -8689,6 +8689,7 @@ breakText Glyphs Glyfy @msg compound shapes take paths, compound paths, groups, compound shapes, type, blends and envelopes složené tvary přijímají cesty, složené cesty, skupiny, složené tvary, text, prolnutí a obálky @msg compound {_1} must contain exactly one open path to join složený objekt {_1} musí ke spojení obsahovat právě jednu otevřenou cestu @msg connect needs a path other than the one extended connect vyžaduje jinou cestu než tu prodlužovanou +@msg connect needs extend connect vyžaduje extend @msg connect needs id connect vyžaduje id @msg connect path has no open end cesta v connect nemá žádný otevřený konec @msg continuation must be an array of path chunks continuation musí být pole úseků cesty diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 08100f593f..df5c32d9c8 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -1610,6 +1610,7 @@ liquify-list-end {0}, {1} {0} og {1} @msg compound shapes take paths, compound paths, groups, compound shapes, type, blends and envelopes sammensatte figurer tager kurver, sammensatte kurver, grupper, sammensatte figurer, tekst, blandinger og konvolutter @msg compound {_1} must contain exactly one open path to join sammensat {_1} skal indeholde præcis én åben kurve at sammenføje @msg connect needs a path other than the one extended connect kræver en anden kurve end den, der forlænges +@msg connect needs extend connect kræver extend @msg connect needs id connect kræver id @msg connect path has no open end connect-kurven har ingen åben ende @msg continuation must be an array of path chunks continuation skal være et array af kurvestykker diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 10147b2d45..129529c2bd 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -8369,6 +8369,7 @@ breakText Glyphs Glyphen @msg compound {_1} must contain exactly one open path to join zusammengesetzter Pfad {_1} muss genau einen offenen Pfad zum Zusammenfügen enthalten @msg connect end must be "start" or "end" connect end muss „start“ oder „end“ sein @msg connect needs a path other than the one extended connect braucht einen anderen Pfad als den verlängerten +@msg connect needs extend connect braucht extend @msg connect needs id connect braucht id @msg connect path has no open end der connect-Pfad hat kein offenes Ende @msg copy needs path: the file to copy into the document's folder copy braucht path: die Datei, die in den Ordner des Dokuments kopiert werden soll diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 3be3497f97..40cdc646f2 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -8549,6 +8549,7 @@ breakText Glyphs Glyphes @msg compound {_1} must contain exactly one open path to join le tracé transparent {_1} doit contenir exactement un tracé ouvert à joindre @msg connect end must be "start" or "end" l’extrémité de connect doit valoir "start" ou "end" @msg connect needs a path other than the one extended connect nécessite un tracé autre que celui qui est prolongé +@msg connect needs extend connect nécessite extend @msg connect needs id connect nécessite id @msg connect path has no open end le tracé de connect n’a pas d’extrémité ouverte @msg continuation must be an array of path chunks continuation doit être une liste de fragments de tracé diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index cbfb4f51d1..fe132bdac7 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -6883,6 +6883,7 @@ antiAlias Sharp शार्प @msg compressed (RLE) bitmaps can't be read yet संकुचित (RLE) bitmaps अभी तक पढ़ा नहीं जा सकता है @msg connect end must be "start" or "end" कनेक्ट अंत "start" या "end" होना चाहिए @msg connect needs a path other than the one extended connect के लिए बढ़ाए गए पाथ के अलावा कोई दूसरा पाथ चाहिए +@msg connect needs extend connect के लिए extend चाहिए @msg connect needs id connect के लिए id चाहिए @msg connect path has no open end कनेक्ट पाथ का कोई खुला अंत नहीं है @msg Contour: select paths or shapes कंटूर: पाथ या आकृतियों सिलेक्ट करें diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 0f81a72036..f8d97306ea 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -8559,6 +8559,7 @@ breakText Glyphs Glifák @msg compound shapes take paths, compound paths, groups, compound shapes, type, blends and envelopes összetett alakzatba útvonalak, összetett útvonalak, csoportok, összetett alakzatok, szöveg, összemosások és burkolók kerülhetnek @msg compound {_1} must contain exactly one open path to join az összetett objektumnak ({_1}) pontosan egy összekapcsolható nyitott útvonalat kell tartalmaznia @msg connect needs a path other than the one extended connect: a meghosszabbított útvonaltól különböző útvonal kell +@msg connect needs extend connect: extend is kell hozzá @msg connect needs id connect: id is kell hozzá @msg connect path has no open end connect: az útvonalnak nincs nyitott vége @msg continuation must be an array of path chunks continuation: útvonaldarabok tömbje kell diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 8f2ed3216c..80c67ac28d 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -8420,6 +8420,7 @@ breakText Glyphs Glifi @msg compound {_1} must contain exactly one open path to join il composto {_1} deve contenere esattamente un tracciato aperto da unire @msg connect end must be "start" or "end" end di connect deve essere "start" o "end" @msg connect needs a path other than the one extended connect richiede un tracciato diverso da quello esteso +@msg connect needs extend connect richiede extend @msg connect needs id connect richiede id @msg connect path has no open end il tracciato di connect non ha un'estremità aperta @msg copy needs path: the file to copy into the document's folder copy richiede path: il file da copiare nella cartella del documento diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index c429f204a1..a9f1f8e2b4 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -7574,6 +7574,7 @@ axis Y Axis Y 軸 @msg compound {_1} must contain exactly one open path to join 連結するには、複合パス {_1} にオープンパスがちょうど 1 つ含まれている必要があります @msg connect end must be "start" or "end" connect の end には "start" または "end" を指定してください @msg connect needs a path other than the one extended connect には、延長したパスとは別のパスが必要です +@msg connect needs extend connect には extend が必要です @msg connect needs id connect には id が必要です @msg connect path has no open end connect のパスに開いた端点がありません @msg copy needs path: the file to copy into the document's folder copy には path が必要です: ドキュメントのフォルダーにコピーするファイルを指定してください diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 414f45171c..8024e14cbe 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -731,6 +731,7 @@ @msg compound {_1} must contain exactly one open path to join შედგენილი {_1} შესაერთებლად ზუსტად ერთ ღია ტრაექტორიას უნდა შეიცავდეს @msg connect end must be "start" or "end" connect-ის end უნდა იყოს "start" ან "end" @msg connect needs a path other than the one extended connect-ს სჭირდება ტრაექტორია, რომელიც გაგრძელებულისგან განსხვავდება +@msg connect needs extend connect-ს სჭირდება extend @msg connect needs id connect-ს სჭირდება id @msg connect path has no open end connect-ის ტრაექტორიას ღია ბოლო არ აქვს @msg continuation must be an array of path chunks continuation უნდა იყოს ტრაექტორიის ნაწილების მასივი diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index dbda53243f..17de5af74e 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -8287,6 +8287,7 @@ breakText Glyphs 글리프 @msg compound shapes take paths, compound paths, groups, compound shapes, type, blends and envelopes 컴파운드 모양에는 패스, 컴파운드 패스, 그룹, 컴파운드 모양, 문자, 블렌드, 엔벨로프를 넣을 수 있습니다 @msg compound {_1} must contain exactly one open path to join 컴파운드 {_1}에는 연결할 열린 패스가 정확히 하나 있어야 합니다 @msg connect needs a path other than the one extended connect에는 연장한 패스가 아닌 다른 패스가 필요합니다 +@msg connect needs extend connect에는 extend가 필요합니다 @msg connect needs id connect에는 id가 필요합니다 @msg connect path has no open end connect 패스에 열린 끝이 없습니다 @msg continuation must be an array of path chunks continuation은 패스 조각의 배열이어야 합니다 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 69aef91cfc..61f9cb6ddf 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -6533,6 +6533,7 @@ imageTrace Outline Contour @msg compound shapes take paths, compound paths, groups, compound shapes, type, blends and envelopes samengestelde vormen accepteren paden, samengestelde paden, groepen, samengestelde vormen, tekst, mengsels en omvormingen @msg compound {_1} must contain exactly one open path to join samengesteld object {_1} moet precies één open pad bevatten om te verbinden @msg connect needs a path other than the one extended connect heeft een ander pad nodig dan het pad dat wordt verlengd +@msg connect needs extend connect heeft extend nodig @msg connect needs id connect heeft id nodig @msg connect path has no open end het pad van connect heeft geen open uiteinde @msg continuation must be an array of path chunks continuation moet een array van padstukken zijn diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 0147515ffe..72284db352 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -8658,6 +8658,7 @@ breakText Glyphs Glify @msg compound shapes take paths, compound paths, groups, compound shapes, type, blends and envelopes kształty złożone przyjmują ścieżki, ścieżki złożone, grupy, kształty złożone, tekst, przejścia i koperty @msg compound {_1} must contain exactly one open path to join obiekt złożony {_1} musi zawierać dokładnie jedną otwartą ścieżkę do połączenia @msg connect needs a path other than the one extended connect wymaga ścieżki innej niż przedłużana +@msg connect needs extend connect wymaga extend @msg connect needs id connect wymaga id @msg connect path has no open end ścieżka w connect nie ma otwartego końca @msg copy needs path: the file to copy into the document's folder copy wymaga path: pliku do skopiowania do folderu dokumentu diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 8201db7ab6..41c1df9d5f 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -8751,6 +8751,7 @@ swatch Yellow Green Verde-amarelado @msg compound shapes take paths, compound paths, groups, compound shapes, type, blends and envelopes formas compostas aceitam caminhos, caminhos compostos, grupos, formas compostas, texto, mesclagens e envelopes @msg compound {_1} must contain exactly one open path to join o composto {_1} deve conter exatamente um caminho aberto para unir @msg connect needs a path other than the one extended connect precisa de um caminho diferente do que foi estendido +@msg connect needs extend connect precisa de extend @msg connect needs id connect precisa de id @msg connect path has no open end o caminho de connect não tem extremidade aberta @msg continuation must be an array of path chunks continuation deve ser uma matriz de trechos de caminho diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index d1593508d3..c73261d370 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -8676,6 +8676,7 @@ shape Open Открытый @msg compound {_1} must contain exactly one open path to join составной объект {_1} должен содержать ровно один открытый контур для соединения @msg connect end must be "start" or "end" end для connect должно быть "start" или "end" @msg connect needs a path other than the one extended для connect нужен контур, отличный от продлеваемого +@msg connect needs extend для connect нужен extend @msg connect needs id для connect нужен id @msg connect path has no open end у контура для connect нет открытого конца @msg continuation must be an array of path chunks continuation должно быть массивом фрагментов контура diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 5c0420fcd3..ff80e28181 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -8331,6 +8331,7 @@ digits Hindi Hindi @msg compound shapes take paths, compound paths, groups, compound shapes, type, blends and envelopes sammansatta former tar banor, sammansatta banor, grupper, sammansatta former, text, övergångar och kuvert @msg connect end must be "start" or "end" connect end måste vara "start" eller "end" @msg connect needs a path other than the one extended connect behöver en annan bana än den som förlängs +@msg connect needs extend connect behöver extend @msg connect needs id connect behöver id @msg connect path has no open end connect-banan har ingen öppen ände @msg Contour: select paths or shapes Kontur: markera banor eller former diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 910a7fc5b1..c224c38665 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -7958,6 +7958,7 @@ axis Y Axis Y ekseni @msg compound shapes take paths, compound paths, groups, compound shapes, type, blends and envelopes bileşik şekiller yolları, bileşik yolları, grupları, bileşik şekilleri, metni, karışımları ve zarfları alır @msg compound {_1} must contain exactly one open path to join bileşik {_1}, birleştirilecek tam olarak bir açık yol içermelidir @msg connect needs a path other than the one extended connect için uzatılan yoldan başka bir yol gerekir +@msg connect needs extend connect için extend gerekir @msg connect needs id connect için id gerekir @msg connect path has no open end connect yolunun açık ucu yok @msg copy needs path: the file to copy into the document's folder copy için path gerekir: belgenin klasörüne kopyalanacak dosya diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index dbd6d2609e..e3359fba2a 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -8289,6 +8289,7 @@ breakText Glyphs Гліфи @msg compound shapes take paths, compound paths, groups, compound shapes, type, blends and envelopes складені фігури приймають контури, складені контури, групи, складені фігури, текст, переходи й оболонки @msg compound {_1} must contain exactly one open path to join складений об’єкт {_1} має містити рівно один відкритий контур для з’єднання @msg connect needs a path other than the one extended для connect потрібен контур, відмінний від того, що продовжується +@msg connect needs extend для connect потрібен extend @msg connect needs id для connect потрібен id @msg connect path has no open end контур для connect не має відкритого кінця @msg continuation must be an array of path chunks continuation має бути масивом частин контуру diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index c6696a9ec6..105ed8f917 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -8646,6 +8646,7 @@ breakText Glyphs 字形 @msg compound shapes take paths, compound paths, groups, compound shapes, type, blends and envelopes 复合形状接受路径、复合路径、编组、复合形状、文字、混合和封套 @msg compound {_1} must contain exactly one open path to join 复合对象 {_1} 必须恰好包含一条要连接的开放路径 @msg connect needs a path other than the one extended connect 需要一条不同于被延伸路径的路径 +@msg connect needs extend connect 需要 extend @msg connect needs id connect 需要 id @msg connect path has no open end connect 的路径没有开放的端点 @msg copy needs path: the file to copy into the document's folder copy 需要 path:即要复制到文档所在文件夹的文件 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 1480422931..304b890881 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -8575,6 +8575,7 @@ breakText Glyphs 字符 @msg compound shapes take paths, compound paths, groups, compound shapes, type, blends and envelopes 複合形狀接受路徑、複合路徑、群組、複合形狀、文字、漸變物件和封套 @msg compound {_1} must contain exactly one open path to join 複合路徑 {_1} 必須剛好包含一條可連接的開放路徑 @msg connect needs a path other than the one extended connect 需要延伸路徑以外的另一條路徑 +@msg connect needs extend connect 需要 extend @msg connect needs id connect 需要 id @msg connect path has no open end connect 的路徑沒有開放的端點 @msg copy needs path: the file to copy into the document's folder copy 需要 path:要複製到文件資料夾的檔案 diff --git a/docs/mcp.md b/docs/mcp.md index 092faabc4c..9816040ba7 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -6063,7 +6063,10 @@ in `path.curvatureEdit`; `perpendicular` in `path.reshapeSegment`; and `keepSele `path.freehand` (and `brush.freehand`, which runs it) refuses a `style` other than "pencil" or "brush" with `style must be "pencil" or "brush"`, and an `end` of `extend` other than "start" or "end" with `extend end must be "start" or "end"`; the document does not change and no undo step is recorded. Left out or null, -`style` is "pencil" and the `end` of `extend` is "end". +`style` is "pencil" and the `end` of `extend` is "end". It refuses a `connect` without `extend` with +`connect needs extend`, and checks a `connect` given with `extend` (its `id`, a path other than the one extended with +an open end, and an `end` of "start" or "end") before a stroke of one point returns, so a bad `connect` is refused +there too and a `brush.freehand` call does not change the path's brush or the selection. A `pointer_gesture` with `mods: {cmd: true}` held at the press, with any tool but the selection tools (Command on macOS, Ctrl elsewhere), drags with the selection tool chosen last (`select_tool`), or Direct Selection with the Pen, diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index e9fc9a6820..ba709df4f5 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1349,6 +1349,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Before a press that draws a new path, the Pencil cursor shows a small star, as [Draw freeform paths with the Pencil tool](https://web.archive.org/web/20260926095638/https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/draw-freeform-paths-with-the-pencil-tool.html) describes; over a selected path within Edit selected paths' distance, which the press continues from an end or redraws, the star is not shown ([Reshape paths with the Pencil tool](https://web.archive.org/web/20260106004407/https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/reshape-paths-with-the-pencil-tool.html)). Keep selected in the Pencil and Paintbrush Tool Options is on by default: while it is on, a stroke selects the path it draws or continues and replaces the earlier selection. While it is off, a new stroke leaves nothing selected, the earlier selection included, as the reference application starts the stroke by dropping it (#5752); a continued or redrawn path is deselected while the rest of the selection stays (`path.freehand` `keepSelected`). With two open paths selected, a Pencil stroke from an end of one that ends within Edit selected paths' distance of an end of the other connects them into one path with the first path's appearance, in one undo step, as [Connect two paths with the Pencil tool](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/connect-two-paths-with-the-pencil-tool.html) describes (`path.freehand` `connect`). + `path.freehand` and `brush.freehand` refuse a `connect` without `extend` with an error, and check a `connect` given with `extend` before a stroke of one point returns, so a bad one changes neither the path's brush nor the selection. Double-clicking the Shape Builder tool opens Shape Builder Tool Options ([Shape Builder tool options](https://web.archive.org/web/20260105172244/https://helpx.adobe.com/illustrator/using/building-new-shapes-using-shape.html)): with Consider Open Filled Paths as Closed off, a filled open path cuts regions as an unfilled one does; Pick Color From Color Swatches fills merged shapes with the current fill, the Left and Right arrow keys step it through the document's color swatches, and Cursor Swatch Preview shows the current fill and the swatches before and after it above the pointer; Selection Straight Line merges what the line from a drag's first point to its last crosses ([Setting Illustrator's Shape Builder Options](https://web.archive.org/web/20260615204453/https://creativepro.com/setting-illustrators-shape-builder-options/)); with Highlight Fill off, merge mode shades no regions (`shapeBuilder.merge` `openFilledAsClosed` and `pickColorFrom`). As VectorCraft's own rule, Consider Open Filled Paths as Closed counts an open path as filled when any of its fill rows draws (shown, painted and above 0% opacity), whichever row is on top, as the canvas paints it: a painted fill under an unpainted top fill closes the path, and a painted fill that is hidden or at 0% opacity does not. The region map, merges, erasing and Clicking Stroke Splits the Path follow that rule, and the Shape Builder takes the faces and edges of a Live Paint group that one of their fill or stroke rows draws and whose own opacity is above 0. Regression tests: `tests::build::shape_builder_closes_open_paths_by_the_fill_rows_that_draw`, `tests::build::shape_builder_stroke_split_closes_open_paths_by_the_fill_rows_that_draw` and `tests::build::shape_builder_takes_the_live_paint_faces_and_edges_that_draw`. With In Merge Mode, Clicking Stroke Splits the Path on in the same dialog, a click on a stroke in merge mode splits its path into the run of stroke under the pointer and the rest of the path, as the [Shape Builder tool options](https://web.archive.org/web/20260105172244/https://helpx.adobe.com/illustrator/using/building-new-shapes-using-shape.html) page describes; the run goes from the anchor or crossing point before the pointer to the one after it, and the pointer shows scissors over it. Highlight Stroke When Editable draws that run in the color chosen in its Color list (Red by default), and with Pick Color From Color Swatches the run takes the current fill as its stroke (`shapeBuilder.merge` `splitStroke`). From 4a60b78b5ccde4284bbe110c2c341814a89d349a Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 17 Nov 2026 11:59:28 -0800 Subject: [PATCH 124/176] Actions: action.batch errors count steps from 1 and name the member they reject action.batch refused a bad step before any file opened as `commands[i]`, counted from 0, while a step that failed as it ran was named `action step N (`id`)`, counted from 1. A step whose params its command refused gave only the command's own error, without saying which step it was. - The checks before the batch (no command, an unknown command, a nested batch, prefs.import) now name the step as `action step N (`id`) failed:`, from 1, as the runtime errors do. A long unknown id is cut short in the message, as an unknown key is. - The parameter check names the action.batch step whose params it refuses the same way. command.batch keeps passing the step's error on as it is. - Override Open matches only document.open, and Override Save only document.save and file.saveAs: file.open, file.save and document.close are not engine commands, and a step with one is refused as unknown. The params text no longer lists them, and docs/mcp.md says a step with file.open or file.save is refused as an unknown command. --- crates/engine/src/cmd/fileio.rs | 1 + crates/engine/src/cmd/fileio/action_batch.rs | 149 +++++++++++++++---- crates/engine/src/cmd/fileio/commands.rs | 2 +- crates/engine/src/cmd/params.rs | 9 +- crates/engine/src/tests.rs | 7 +- docs/mcp.md | 15 +- docs/target-app-parity.md | 1 + 7 files changed, 145 insertions(+), 39 deletions(-) diff --git a/crates/engine/src/cmd/fileio.rs b/crates/engine/src/cmd/fileio.rs index 6817f28b35..90a494f069 100644 --- a/crates/engine/src/cmd/fileio.rs +++ b/crates/engine/src/cmd/fileio.rs @@ -65,6 +65,7 @@ pub mod zip; use serde_json::{Value, json}; +pub(crate) use action_batch::action_step; pub use action_batch::batch_overwrites_one_file; pub use dxf::{UNSUPPORTED, Unsupported, unsupported}; pub use encode::{ diff --git a/crates/engine/src/cmd/fileio/action_batch.rs b/crates/engine/src/cmd/fileio/action_batch.rs index 4e99f4ee3e..aa3be78e2a 100644 --- a/crates/engine/src/cmd/fileio/action_batch.rs +++ b/crates/engine/src/cmd/fileio/action_batch.rs @@ -54,24 +54,19 @@ pub(super) fn action_batch(s: &mut Session, p: &Value) -> Result<Value> { } for (i, c) in cmds.iter().enumerate() { let id = c.get("command").and_then(Value::as_str).unwrap_or(""); + let refuse = |reason: &str| bad(C, action_step(i, id, reason)); if id.is_empty() { - return Err(bad(C, format!("commands[{i}]: missing `command`"))); + return Err(refuse("missing `command`")); } if id == "command.batch" || id == "action.batch" { - return Err(bad(C, "batches cannot nest")); + return Err(refuse("batches cannot nest")); } // `command.batch` refuses the batch when it reaches this step, which would fail every file or data set it plays. if id == "prefs.import" { - return Err(bad(C, format!("commands[{i}]: `prefs.import` runs on its own, not as a batch step"))); + return Err(refuse("`prefs.import` runs on its own, not as a batch step")); } if find_command(id).is_none() { - return Err(bad( - C, - match super::super::params::nearest_command(id) { - Some(near) => format!("commands[{i}]: unknown command `{id}`; did you mean `{near}`?"), - None => format!("commands[{i}]: unknown command `{id}`"), - }, - )); + return Err(refuse(&super::super::params::unknown_command(id).to_string())); } } // Every option is checked before the destination folder is made. @@ -160,7 +155,7 @@ pub fn batch_overwrites_one_file(s: &Session, p: &Value) -> bool { Some(f) => own_format.is_some_and(|own| super::format(f).is_some_and(|f| f.id == own)), }; match c.get("command").and_then(Value::as_str).unwrap_or("") { - "document.save" | "file.save" => !save && (path || own_file()), + "document.save" => !save && (path || own_file()), "file.saveAs" => !save && path, "file.saveCopy" | "file.saveAsTemplate" => path, "document.export" | "document.exportSelection" => !export && path, @@ -184,7 +179,7 @@ fn saves_move_to_each_file(steps: &[Value], redirected: bool) -> bool { /// in the destination folder when `redirected`) and makes that file the document's own: a save in /// the native template format writes a copy and leaves the document's file as it was. fn retargeting_save(c: &Value, redirected: bool) -> bool { - if !matches!(c.get("command").and_then(Value::as_str), Some("document.save" | "file.save" | "file.saveAs")) { + if !matches!(c.get("command").and_then(Value::as_str), Some("document.save" | "file.saveAs")) { return false; } let params = c.get("params"); @@ -219,7 +214,7 @@ fn batch_folder(s: &mut Session, cmd: &str, p: &Value, override_open: bool, run: // open, so its artboard files count ([`dataset_output_paths`]). No output takes the name of a // source file in the destination folder, other than that file's own output, or of a subfolder // of the destination folder that holds source files. - let (steps, places) = filter_steps(run.steps, override_open, false); + let (steps, places) = filter_steps(run.steps, override_open); let run = Run { steps: &steps, ..*run }; let in_dest: Vec<Option<(String, bool)>> = files.iter().map(|path| name_in_folder(path, run.dest_folder)).collect(); let mut picker = @@ -272,7 +267,7 @@ fn batch_datasets(s: &mut Session, cmd: &str, run: &Run<'_>) -> Result<Value> { } let doc_stem = st.path.as_deref().and_then(|p| std::path::Path::new(p).file_stem().and_then(|s| s.to_str())).unwrap_or("Untitled").to_string(); let stems = dataset_stems(&names, &doc_stem, run.dataset_file_naming, run, &st.doc)?; - let (steps, places) = filter_steps(run.steps, true, false); + let (steps, places) = filter_steps(run.steps, true); let run = Run { steps: &steps, ..*run }; let mut processed = Vec::new(); let mut failed = 0usize; @@ -353,22 +348,13 @@ impl StemPicker { } } -/// Drop Open (and optionally Close) steps when the batch supplies the file itself → the steps that -/// stay, and the index of each in `cmds`. +/// Drop the `document.open` steps when `drop_open` (the batch opens each source file itself) → the +/// steps that stay, and the index of each in `cmds`. #[cfg(not(target_arch = "wasm32"))] -fn filter_steps(cmds: &[Value], drop_open: bool, drop_close: bool) -> (Vec<Value>, Vec<usize>) { +fn filter_steps(cmds: &[Value], drop_open: bool) -> (Vec<Value>, Vec<usize>) { cmds.iter() .enumerate() - .filter(|(_, c)| { - let id = c.get("command").and_then(Value::as_str).unwrap_or(""); - if drop_open && matches!(id, "document.open" | "file.open") { - return false; - } - if drop_close && matches!(id, "file.close" | "document.close") { - return false; - } - true - }) + .filter(|(_, c)| !(drop_open && c.get("command").and_then(Value::as_str) == Some("document.open"))) .map(|(i, c)| (c.clone(), i)) .unzip() } @@ -385,12 +371,24 @@ fn play_steps(s: &mut Session, run: &Run<'_>, places: &[usize], commands: Vec<Va let Some((n, id, reason)) = batch_step_failure(&text) else { return e }; let same = run.steps.get(n).and_then(|c| c.get("command")).and_then(Value::as_str) == Some(id); match places.get(n) { - Some(place) if same => EngineError::Other(format!("action step {} (`{id}`) failed: {reason}", place + 1)), + Some(&place) if same => EngineError::Other(action_step(place, id, reason)), _ => e, } }) } +/// The text naming the member at `index` of an `action.batch`'s `commands`, counted from 1, with +/// its command id when it has one, and `reason`: ``action step 2 (`object.move`) failed: …``. The +/// checks before a batch runs and the errors of its steps as they run give the same text. +pub(crate) fn action_step(index: usize, id: &str, reason: &str) -> String { + let n = index.saturating_add(1); + if id.is_empty() { + format!("action step {n} failed: {reason}") + } else { + format!("action step {n} (`{}`) failed: {reason}", vectorcraft_apischema::shown_key(id)) + } +} + /// The step number, command id and reason in the error `command.batch` gives when one of its steps /// fails (``batch step 2 (`object.move`) failed: …``); none for any other error. #[cfg(not(target_arch = "wasm32"))] @@ -540,7 +538,7 @@ fn dataset_output_extensions(run: &Run<'_>, doc: &vectorcraft_doc::Document, def outputs.push(DatasetOutput { ext: String::new(), artboards: false, joiner: "-", folder: true }); continue; } - let writes = (run.override_save && matches!(id, "document.save" | "file.save" | "file.saveAs")) + let writes = (run.override_save && matches!(id, "document.save" | "file.saveAs")) || (run.override_export && matches!(id, "document.export" | "document.exportSelection")); if writes { let format = step.get("params").and_then(|p| p.get("format")).and_then(Value::as_str).filter(|f| !f.is_empty()); @@ -551,7 +549,7 @@ fn dataset_output_extensions(run: &Run<'_>, doc: &vectorcraft_doc::Document, def }; if safe_extension(&ext) { let format_id = super::format(format.unwrap_or(default_ext)).map(|f| f.id).unwrap_or("vectorcraft"); - let is_save = matches!(id, "document.save" | "file.save" | "file.saveAs"); + let is_save = matches!(id, "document.save" | "file.saveAs"); let artboards = if is_save { !doc.artboards.is_empty() && matches!(format_id, "vectorcraft" | "template" | "ai" | "ait") } else { @@ -693,7 +691,7 @@ fn rewrite_paths( .map(|c| { let id = c.get("command").and_then(Value::as_str).unwrap_or(""); let mut c = c.clone(); - let rewrite = (override_save && matches!(id, "document.save" | "file.save" | "file.saveAs")) + let rewrite = (override_save && matches!(id, "document.save" | "file.saveAs")) || (override_export && matches!(id, "document.export" | "document.exportForScreens" | "document.exportSelection" | "assets.export")); if !rewrite { return c; @@ -2385,10 +2383,97 @@ mod tests { let mut s = Session::new(); let p = json!({"folder": src.to_string_lossy(), "commands": [{"command": "object.unlockAll"}, {"command": "prefs.import", "params": {}}]}); let e = s.execute("action.batch", &p).unwrap_err().to_string(); - assert!(e.contains("commands[1]: `prefs.import` runs on its own, not as a batch step"), "{e}"); + assert!(e.contains("action step 2 (`prefs.import`) failed: `prefs.import` runs on its own, not as a batch step"), "{e}"); assert!(s.active().is_none(), "no file was opened"); } + /// Each step the checks before the batch refuse is named by its place in `commands`, from 1, + /// as a step that fails as it runs is, and no source file is opened. + #[test] + fn a_refused_step_is_named_by_its_place_from_1() { + let src = tmp("step-number-refused-src"); + write_svg(&src, "a.svg", "#f00"); + let prefix = "invalid parameters for `action.batch`: "; + let cases = [ + (json!({"params": {}}), "action step 2 failed: missing `command`"), + (json!({"command": "select.al"}), "action step 2 (`select.al`) failed: unknown command `select.al`; did you mean `select.all`?"), + (json!({"command": "command.batch", "params": {"commands": []}}), "action step 2 (`command.batch`) failed: batches cannot nest"), + (json!({"command": "action.batch", "params": {}}), "action step 2 (`action.batch`) failed: batches cannot nest"), + ( + json!({"command": "view.saved.new", "params": {"center": [0, 0], "zoom": 0}}), + "action step 2 (`view.saved.new`) failed: invalid parameters for `view.saved.new`: `zoom` must be a number > 0, not 0", + ), + ]; + for (step, want) in cases { + let mut s = Session::new(); + let p = json!({"folder": src.to_string_lossy(), "commands": [{"command": "object.unlockAll"}, step]}); + let e = s.execute("action.batch", &p).unwrap_err().to_string(); + assert_eq!(e, format!("{prefix}{want}"), "{step}"); + assert!(s.active().is_none(), "{step}: a file was opened"); + assert!(s.journal.is_empty(), "{step}: a step ran"); + } + } + + /// The parameter check of an `action.batch` names the step whose params it refuses, from 1; + /// that of a `command.batch` passes the step's error on as it is. + #[test] + fn the_parameter_check_names_the_refused_step() { + let bad_view = json!({"command": "view.saved.new", "params": {"center": [0, 0], "zoom": 0}}); + let commands = json!([{"command": "object.unlockAll"}, {"command": "select.all"}, bad_view]); + let own = "invalid parameters for `view.saved.new`: `zoom` must be a number > 0, not 0"; + let e = crate::cmd::params::check_params("action.batch", &json!({"commands": commands})).unwrap_err().to_string(); + assert_eq!(e, format!("invalid parameters for `action.batch`: action step 3 (`view.saved.new`) failed: {own}")); + let e = crate::cmd::params::check_params("command.batch", &json!({"commands": commands})).unwrap_err().to_string(); + assert_eq!(e, own); + } + + /// The ids of the File menu's Open… and Save in the app (`file.open`, `file.save`) and + /// `document.close` are not engine commands, so a step with one is refused before the batch + /// starts, with Override Open and Override Save on or off. + #[test] + fn steps_with_ids_that_are_not_engine_commands_are_refused() { + let src = tmp("step-number-aliases-src"); + write_svg(&src, "a.svg", "#f00"); + for id in ["file.open", "file.save", "document.close"] { + for overrides in [true, false] { + let mut s = Session::new(); + let p = json!({ + "folder": src.to_string_lossy(), + "overrideOpen": overrides, + "overrideSave": overrides, + "commands": [{"command": "object.unlockAll"}, {"command": id, "params": {}}], + }); + let e = s.execute("action.batch", &p).unwrap_err().to_string(); + assert!( + e.starts_with(&format!("invalid parameters for `action.batch`: action step 2 (`{id}`) failed: unknown command `{id}`")), + "{e}" + ); + assert!(s.active().is_none(), "{id}: a file was opened"); + } + } + } + + /// `command.batch` keeps its own numbering, from 0, for a step that fails. + #[test] + fn command_batch_keeps_its_own_step_numbers() { + let mut s = Session::new(); + s.execute("file.new", &json!({})).unwrap(); + let e = s + .execute("command.batch", &json!({"commands": [{"command": "object.unlockAll"}, {"command": "object.align", "params": {}}]})) + .unwrap_err(); + assert!(e.to_string().starts_with("batch step 1 (`object.align`) failed: "), "{e}"); + } + + /// A step's id in the error is cut short, as an unknown key's is. + #[test] + fn a_long_step_id_is_cut_short() { + let id = "x".repeat(10_000); + let shown = action_step(0, &id, "why"); + assert!(shown.len() < 1_000, "{}", shown.len()); + assert!(shown.starts_with("action step 1 (`xxx") && shown.ends_with("…`) failed: why"), "{shown}"); + assert_eq!(action_step(usize::MAX, "", "why"), format!("action step {} failed: why", usize::MAX)); + } + /// Only the error `command.batch` gives for a failed step is read as one. #[test] fn batch_step_failure_reads_only_a_step_error() { diff --git a/crates/engine/src/cmd/fileio/commands.rs b/crates/engine/src/cmd/fileio/commands.rs index 554d088b79..be066a471d 100644 --- a/crates/engine/src/cmd/fileio/commands.rs +++ b/crates/engine/src/cmd/fileio/commands.rs @@ -117,7 +117,7 @@ pub fn specs() -> Vec<CommandSpec> { "Batch…", [], None, - "{commands: [{command, params}] (the action's steps), source?: folder (default) | datasets, folder? (required for folder: the source folder), includeSubdirs?: false, destination?: none (default: leave each file open) | saveAndClose (save over the source and close; for source datasets, save the open document over its own file after each data set, and refuse a document that was never saved, was converted from an older version or was restored by Data Recovery, unless a recorded Save or Save As step writes a file first; a Save or Save As step that overrideSave points into destinationFolder makes each data set's file the document's own) | folder (save or export into destinationFolder and close), destinationFolder? (required when destination is folder; also the folder Override Save/Export write into), datasetFileNaming?: fileNumber | fileDataSetName (default) | dataSetName (used only for source datasets; ignored for folder), overrideOpen?: true (skip document.open / file.open steps: the batch opens each source file), overrideSave?: true (point document.save / file.save / file.saveAs at destinationFolder/{stem}.{ext}), overrideExport?: true (point document.export / document.exportSelection the same way, and give document.exportForScreens / assets.export the folder destinationFolder/{stem}, one for each source file or data set, in which the export names its files as it does outside Batch), stopOnError?: true, label?} play the commands on every readable file in folder (and its subfolders when includeSubdirs; {stem} is the file's name without its extension and without trailing periods and spaces, with `-2`, `-3`… added to a name an earlier file used or whose file or folder has the name of one an earlier file wrote or of another source file or a folder of source files in destinationFolder), or on every data set of the open document. Data set names use the document stem plus a three-digit ordinal, the document stem and an underscore plus the data set name, or the data set name alone. Invalid file name characters become `-` and trailing periods and spaces are dropped; a name already used in the batch or whose output file or folder already exists in a destination folder the batch may read and write gets the next free `-2`, `-3` suffix before the format-derived extension. Caps: 500 files or data sets, 8 folder levels, 256 steps. Batches cannot nest, and a prefs.import step is refused (commands[i], from 0) before any file is opened. A switch (includeSubdirs, overrideOpen, overrideSave, overrideExport, stopOnError) that is not true or false, or a source, folder, destination, destinationFolder, datasetFileNaming or label that is not a string, is an error before any folder is made or file opened; null reads as left out. A step that fails is named in the error by its place in commands, from 1, counting the Open steps the batch skips (action step 3 (`object.align`) failed: …); the batch's own opening of a file, choosing of a data set and destination save, export or close give their errors without a step number. → {processed: [{path|dataset, result|error}…], count, failed, stopped, warning?} (warning: for source datasets, when Save and Close without such a step, or a Save, Save a Copy, Save as Template or export step (document.export, exportSelection, exportForScreens, exportPdf, exportEps, exportDxf, exportForWeb, exportForOffice) that writes a file and is not pointed into destinationFolder, saves every data set over the same file)", + "{commands: [{command, params}] (the action's steps), source?: folder (default) | datasets, folder? (required for folder: the source folder), includeSubdirs?: false, destination?: none (default: leave each file open) | saveAndClose (save over the source and close; for source datasets, save the open document over its own file after each data set, and refuse a document that was never saved, was converted from an older version or was restored by Data Recovery, unless a recorded Save or Save As step writes a file first; a Save or Save As step that overrideSave points into destinationFolder makes each data set's file the document's own) | folder (save or export into destinationFolder and close), destinationFolder? (required when destination is folder; also the folder Override Save/Export write into), datasetFileNaming?: fileNumber | fileDataSetName (default) | dataSetName (used only for source datasets; ignored for folder), overrideOpen?: true (skip document.open steps: the batch opens each source file), overrideSave?: true (point document.save / file.saveAs at destinationFolder/{stem}.{ext}), overrideExport?: true (point document.export / document.exportSelection the same way, and give document.exportForScreens / assets.export the folder destinationFolder/{stem}, one for each source file or data set, in which the export names its files as it does outside Batch), stopOnError?: true, label?} play the commands on every readable file in folder (and its subfolders when includeSubdirs; {stem} is the file's name without its extension and without trailing periods and spaces, with `-2`, `-3`… added to a name an earlier file used or whose file or folder has the name of one an earlier file wrote or of another source file or a folder of source files in destinationFolder), or on every data set of the open document. Data set names use the document stem plus a three-digit ordinal, the document stem and an underscore plus the data set name, or the data set name alone. Invalid file name characters become `-` and trailing periods and spaces are dropped; a name already used in the batch or whose output file or folder already exists in a destination folder the batch may read and write gets the next free `-2`, `-3` suffix before the format-derived extension. Caps: 500 files or data sets, 8 folder levels, 256 steps. A step without a command, with a command the engine doesn't have, with params its command refuses, or with command.batch, action.batch or prefs.import (batches cannot nest) is refused before any file is opened, named by its place in commands, from 1 (action step 2 (`select.al`) failed: unknown command `select.al`; did you mean `select.all`?). A switch (includeSubdirs, overrideOpen, overrideSave, overrideExport, stopOnError) that is not true or false, or a source, folder, destination, destinationFolder, datasetFileNaming or label that is not a string, is an error before any folder is made or file opened; null reads as left out. A step that fails as it runs is named the same way, counting the Open steps the batch skips (action step 3 (`object.align`) failed: …); the batch's own opening of a file, choosing of a data set and destination save, export or close give their errors without a step number. → {processed: [{path|dataset, result|error}…], count, failed, stopped, warning?} (warning: for source datasets, when Save and Close without such a step, or a Save, Save a Copy, Save as Template or export step (document.export, exportSelection, exportForScreens, exportPdf, exportEps, exportDxf, exportForWeb, exportForOffice) that writes a file and is not pointed into destinationFolder, saves every data set over the same file)", always, action_batch::action_batch ), diff --git a/crates/engine/src/cmd/params.rs b/crates/engine/src/cmd/params.rs index 8dc29b9704..156f665dad 100644 --- a/crates/engine/src/cmd/params.rs +++ b/crates/engine/src/cmd/params.rs @@ -928,9 +928,14 @@ fn check_params_in(id: &str, params: &Value, in_batch: bool) -> Result<()> { crate::schemas::check(spec, params, false)?; } if matches!(id, "command.batch" | "action.batch") && !in_batch { - for step in params.get("commands").and_then(Value::as_array).into_iter().flatten() { + for (i, step) in params.get("commands").and_then(Value::as_array).into_iter().flatten().enumerate() { if let Some(step_id) = step.get("command").and_then(Value::as_str) { - check_params_in(step_id, step.get("params").unwrap_or(&Value::Null), true)?; + let checked = check_params_in(step_id, step.get("params").unwrap_or(&Value::Null), true); + // An `action.batch` names the step it refuses by its place, from 1, as its own checks and its steps' errors do. + match checked { + Err(e) if id == "action.batch" => return Err(bad(id, super::fileio::action_step(i, step_id, &e.to_string()))), + checked => checked?, + } } } } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index e6c622963a..cb96d7517e 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -371,9 +371,12 @@ fn a_long_unknown_command_id_is_answered_at_once() { fn action_batch_names_the_nearest_command_id() { let mut s = session(); let e = s.execute("action.batch", &json!({"source": "dataSets", "commands": [{"command": "select.al"}]})).unwrap_err(); - assert_eq!(e.to_string(), "invalid parameters for `action.batch`: commands[0]: unknown command `select.al`; did you mean `select.all`?"); + assert_eq!( + e.to_string(), + "invalid parameters for `action.batch`: action step 1 (`select.al`) failed: unknown command `select.al`; did you mean `select.all`?" + ); let e = s.execute("action.batch", &json!({"source": "dataSets", "commands": [{"command": "nope"}]})).unwrap_err(); - assert_eq!(e.to_string(), "invalid parameters for `action.batch`: commands[0]: unknown command `nope`"); + assert_eq!(e.to_string(), "invalid parameters for `action.batch`: action step 1 (`nope`) failed: unknown command `nope`"); } #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 092faabc4c..e7fe0234fe 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2258,6 +2258,11 @@ path to a value inside a list or an object, and the document and its undo histor → invalid parameters for `view.saved.edit`: `edits[0].delete` must be true or false, not 1 ``` +A refused step of a `command.batch` gives its command's error as it is. A refused step of an `action.batch` is named +by its place in `commands`, from 1, before its command's error: with `commands` of an Unlock All and the +`view.saved.new` above, the error is +``invalid parameters for `action.batch`: action step 2 (`view.saved.new`) failed: invalid parameters for `view.saved.new`: `zoom` must be a number > 0, not 0``. + A schema nests at most 16 lists and objects. A value that would go past that depth is refused with the same kind of parameter error, ``invalid parameters for `<id>`: `<path>` is nested too deeply``, where `<path>` is the path to the value. A schema that is wrong in itself, such as one that nests past 16 levels or puts a list of ids or a point @@ -6736,8 +6741,14 @@ A null is read as a key left out. When a step fails on a file or data set, that place in the `commands` sent, from 1, counting the Open steps the batch skips: with `commands` of an Open, an Unlock All and an Align, a failed Align gives `` action step 3 (`object.align`) failed: `` and the reason. The batch's own opening of a source file, choosing of a data set and destination save, export or close give their errors without a -step number. This numbering is VectorCraft's own rule. A `prefs.import` step is refused before any file is opened, -with `` commands[1]: `prefs.import` runs on its own, not as a batch step `` (counted from 0, as for an unknown command). An action recorded in the Actions panel leaves the artboard out, +step number. This numbering is VectorCraft's own rule. Before any file is opened, `action.batch` refuses a step +without a command, with a command the engine does not have, with params its command refuses, or with +`command.batch`, `action.batch` (batches cannot nest) or `prefs.import`, and names it the same way, from 1: with +`commands` of an Unlock All and a `prefs.import`, the error is +``invalid parameters for `action.batch`: action step 2 (`prefs.import`) failed: `prefs.import` runs on its own, not as a batch step``. +Override Open skips `document.open` steps, and Override Save points `document.save` and `file.saveAs` steps at the +destination folder. `file.open` and `file.save` are the app's commands, not the engine's, so a step with one is +refused as an unknown command. An action recorded in the Actions panel leaves the artboard out, and its steps of these commands get the artboard that is active when the action plays. A press with the Selection, Direct Selection or Group Selection tool inside an artboard makes that artboard the active one; with the Selection tool, a Shift-click on an empty spot inside an artboard makes it active and keeps the selection. Choosing the Artboard diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index e9fc9a6820..6d45f34382 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -852,6 +852,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Batch…: Override Save and Override Export name each file with the extension of the format the step writes, however the step spells the format (`.svg` and `SVG` give `.svg`, `png8` gives `.png`), in `action.batch`. - Batch…: Override Export writes the files of an Export for Screens or Export Assets step into a folder for each source file or data set inside the destination folder, under the names the export gives them (`action.batch`). The folder and file names drop trailing periods and spaces (`a..svg` gives `a`). When two source files would get the same name that way (compared without case), or a later file's folder or file would take the name of an output an earlier file wrote, of a source file in the destination folder or, for data sets, of a file already there, Batch adds `-2`, `-3`… to the later one's name. - Batch…: when a step fails on a file or data set, the error names the step by its place in the action's steps, from 1, counting the Open steps the batch skips (`action.batch`). This numbering is VectorCraft's own rule. Tests `cmd::fileio::action_batch::tests::{a_folder_batch_error_names_the_step_in_the_commands_sent, a_recorded_open_that_fails_is_the_first_step, a_data_set_batch_error_names_the_step_in_the_commands_sent, a_redirected_export_that_fails_keeps_its_place, a_source_that_does_not_open_names_no_step}`. + - Batch…: a step refused before any file opens (no command, a command the engine does not have, params its command refuses, a nested batch or `prefs.import`) is named the same way, by its place from 1 and its command id (`action.batch`). Tests `cmd::fileio::action_batch::tests::{a_refused_step_is_named_by_its_place_from_1, the_parameter_check_names_the_refused_step, steps_with_ids_that_are_not_engine_commands_are_refused}`. - Actions panel menu: Save Actions… writes the current action set with all its actions to a file, and Load Actions… adds the set from such a file to the panel ([Manage a set of actions](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/manage-a-set-of-actions.html); `ui.actionSet.save`, `ui.actionSet.load`). The file is VectorCraft's own action set file (`.vcactions`); a loaded set named like one in the panel gets the next free number. - Actions panel menu: Load Actions… keeps a step whose command this build or its installed plug-ins do not have, and reports each one when the set loads: the `ui.actionSet.load` answer lists the action, step and command id (`unknownCommands`, `unknownCount`), and the status bar names the first and the count. An action with such a step included does not play, and the error names the step and its id before any step runs; an excluded one does not stop it. These are VectorCraft's own rules. Tests `panels::actions::tests::{load_actions_reports_steps_with_unknown_commands, load_actions_bounds_what_it_reports_of_unknown_commands, an_action_with_an_unknown_command_does_not_play}`. - Actions panel menu: Save Actions… does not write a set with a step that sets a folder preference (the Fonts, Plug-ins, Templates and Recovery folders and the two scratch disks) to a folder, and names the action and the preference instead; an empty folder and the scratch disk choices Startup and None save. Export Preferences leaves out both scratch disks, and `ui.inspect` under automation read roots leaves such a folder outside them out of recorded steps. These are VectorCraft's own rules (`ui.actionSet.save`, `prefs.export`). From 393fe5dc802c9bba52c48ff13f692f1473e2a12f Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 17 Nov 2026 12:16:59 -0800 Subject: [PATCH 125/176] OpenType: the panel menu has a Stylistic Sets submenu The OpenType panel menu gains a Stylistic Sets submenu after Reset OpenType Features. It lists the same sets, labels and checks as the panel's Stylistic Sets button, and a set chosen there turns on or off for the characters the panel acts on in one undo step, keeping their other features. The submenu is disabled with no text selected or when the font offers no sets. --- crates/ui-egui/src/panels/opentype.rs | 100 +++++++++++++++++++++----- docs/target-app-parity.md | 1 + 2 files changed, 85 insertions(+), 16 deletions(-) diff --git a/crates/ui-egui/src/panels/opentype.rs b/crates/ui-egui/src/panels/opentype.rs index fe144edbf9..4cfcb27e89 100644 --- a/crates/ui-egui/src/panels/opentype.rs +++ b/crates/ui-egui/src/panels/opentype.rs @@ -1,7 +1,7 @@ //! OpenType panel: per-character OpenType features (ligatures, alternates, swashes, small caps, -//! ordinals, fractions, figure style, position, and with the East Asian options the menu's H or V -//! Style and Roman Italics) for the selected text (every frame of each selected threaded story) or -//! the Type tool's selected characters. +//! ordinals, fractions, figure style, position, stylistic sets from the panel or its menu, and with +//! the East Asian options the menu's H or V Style and Roman Italics) for the selected text (every +//! frame of each selected threaded story) or the Type tool's selected characters. use egui::Ui; use serde_json::json; @@ -257,18 +257,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { change = Some(Change::Toggle(flag, shown != Some(true))); } } - // The font, not the text, decides which numbered sets can be offered. Each set is an - // independent feature, so the menu permits several at once. A font's own label wins over - // the numbered fallback. See the public Stylistic Sets help page. A set is checked when every - // character has it. - let sets: Vec<(StylisticSet, Flag, bool)> = offered_sets(&st) - .into_iter() - .map(|set| { - let flag = Flag::Extra(EXTRA_FEATURES[usize::from(set.number - 1)]); - let on = shown_flag(app, flag) == Some(true); - (set, flag, on) - }) - .collect(); + let sets = set_entries(app, &st); ui.add_enabled_ui(!sets.is_empty(), |ui| { ui.menu_button(tl!("Stylistic Sets"), |ui| { widgets::menu_scroll(ui, |ui| { @@ -300,6 +289,22 @@ fn tracking_drops_ligatures(app: &VectorcraftApp) -> bool { }) } +/// The Stylistic Sets entries of the panel's button and of the panel menu's submenu: each set the +/// font `st` names offers, the feature it turns on and off, and whether it is checked. The font, +/// not the text, decides which numbered sets can be offered. Each set is an independent feature, +/// so the menu permits several at once. A font's own label wins over the numbered fallback. See +/// the public Stylistic Sets help page. A set is checked when every character has it. +fn set_entries(app: &VectorcraftApp, st: &CharStyle) -> Vec<(StylisticSet, Flag, bool)> { + offered_sets(st) + .into_iter() + .map(|set| { + let flag = Flag::Extra(EXTRA_FEATURES[usize::from(set.number - 1)]); + let on = shown_flag(app, flag) == Some(true); + (set, flag, on) + }) + .collect() +} + /// The stylistic sets of the font `st` names. A font that is not available offers none, rather than /// the sets of the face drawn in its place. fn offered_sets(st: &vectorcraft_doc::CharStyle) -> Vec<StylisticSet> { @@ -345,10 +350,31 @@ fn east_asian_items() -> [Toggle; 2] { } pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { - let has = text_style(app).is_some(); + let style = text_style(app); + let has = style.is_some(); if menu_item(ui, tl!("Reset OpenType Features"), has, false) { set(app, OtFeatures::default()); } + // Stylistic Sets: the sets, labels and checks of the panel's Stylistic Sets button. A set chosen + // while only some characters have it turns it on for all of them. Disabled with no text or when + // the font offers no sets. + let sets = style.map(|(st, _)| set_entries(app, &st)).unwrap_or_default(); + let mut toggle = None; + ui.add_enabled_ui(!sets.is_empty(), |ui| { + // Indented like the items beside it (their check column). + ui.menu_button(format!(" {}", tl!("Stylistic Sets")), |ui| { + widgets::menu_scroll(ui, |ui| { + for (set, flag, on) in &sets { + if widgets::menu_item_name(ui, &set_label(set), true, *on) { + toggle = Some(Change::Toggle(*flag, !on)); + } + } + }); + }); + }); + if let Some(c) = toggle { + edit(app, c); + } if app.session.prefs.show_east_asian_options { ui.separator(); // Checked when every character it changes has it; chosen then, it turns it off. @@ -767,6 +793,48 @@ mod tests { assert_eq!(undo_steps(&app), undo + 1); } + /// The panel menu's Stylistic Sets submenu lists the font's sets with the labels of the panel's + /// Stylistic Sets button. Chosen, a set turns on for the selected type in one undo step and + /// shows checked, keeping the other features; chosen again, it turns off. With no text + /// selected the submenu is disabled and does not open. + #[test] + fn the_panel_menu_stylistic_sets_submenu_turns_sets_on_and_off() { + let mut app = selected_text(); + let Some((st, _)) = text_style(&app) else { panic!("no text style") }; + let sets = set_entries(&app, &st); + // Builds without the bundled fonts have no face that offers sets. + let Some((first, _, _)) = sets.first() else { return }; + let (label, tag) = (set_label(first), EXTRA_FEATURES[usize::from(first.number - 1)]); + set(&mut app, OtFeatures { small_caps: true, ..Default::default() }); + let entry = |t: &str| t.trim_start_matches(['✓', ' ']).to_string(); + // Opens the submenu in a fresh context and returns the drawn text of `label`'s entry and + // its rect, if the submenu shows it. + let open = |app: &mut VectorcraftApp, ctx: &egui::Context| { + crate::theme::install_fonts(ctx); + let texts = super::super::tests_appearance::frame_events(ctx, app, vec![], menu); + let sub = super::super::tests_appearance::text_rect(&texts, " Stylistic Sets"); + super::super::tests_appearance::click(ctx, app, sub.center(), menu); + let texts = super::super::tests_appearance::frame_events(ctx, app, vec![], menu); + texts.into_iter().find(|(t, _)| entry(t) == label && t != " Stylistic Sets") + }; + let ctx = egui::Context::default(); + let Some((text, at)) = open(&mut app, &ctx) else { panic!("{label} missing from the submenu") }; + assert!(!text.starts_with('✓'), "{text:?}"); + let undo = undo_steps(&app); + super::super::tests_appearance::click(&ctx, &mut app, at.center(), menu); + assert_eq!(undo_steps(&app), undo + 1); + let on = text_style(&app).unwrap().0.features; + assert!(on.iter().any(|f| f == tag) && on.iter().any(|f| f == "smcp"), "{on:?}"); + let ctx = egui::Context::default(); + let Some((text, at)) = open(&mut app, &ctx) else { panic!("{label} missing from the reopened submenu") }; + assert!(text.starts_with('✓'), "{text:?}"); + super::super::tests_appearance::click(&ctx, &mut app, at.center(), menu); + assert_eq!(text_style(&app).unwrap().0.features, ["smcp"]); + app.session.execute("select.set", &json!({"ids": []})).unwrap(); + let ctx = egui::Context::default(); + assert!(open(&mut app, &ctx).is_none(), "the submenu opened with no text selected"); + } + /// H or V Style and Roman Italics are in the panel menu with the East Asian options only. #[test] fn kana_style_and_roman_italics_show_with_the_east_asian_options() { diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index e9fc9a6820..d8327c0153 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1533,6 +1533,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur With a Type tool and exactly one character selected, the canvas shows that character's alternate glyphs in a row beside it, and a click on one replaces the character's glyph, as [Replace characters with alternate glyphs](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/replace-characters-with-alternate-glyphs.html) describes ("Replace a character with on-canvas alternate glyphs"). The row shows at most five alternates, and an arrow at its end opens the Glyphs panel on Alternates for Current Selection when the character has more, as the [reference manual](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=479) describes. A click runs the command the panel's double-click runs, as one undo step, so a letter of an Arabic word keeps the word joined. These rules are VectorCraft's own: the row leaves out the glyph the character is drawn with and puts the default glyph first for a character drawn with an alternate; it stands under a character of horizontal type and on the right of a character of vertical type, or on the other side when the canvas ends there or the Contextual Task Bar is there; Preferences › Type › Show Character Alternates (`showCharacterAlternates`, on by default) turns it off. Tests: `canvas::alternates_bar::tests`, `tests::prefs::show_character_alternates_preference_is_on_by_default_and_saved`. With an OpenType font in the Glyphs panel, the Show menu and the panel menu list the font's glyph categories after Alternates for Current Selection, and choosing one restricts the grid to the glyphs of that kind, as the [Glyphs panel overview](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/glyphs-panel-overview.html) describes. The categories are Ligatures, Swash, Stylistic Alternates, each stylistic set by the font's name for it (else Set N), Small Caps, Ornaments, Fractions and Figures, each listed only when the font's `GSUB` features give it glyphs; which features make up each category and their order are VectorCraft's own. A font without the chosen category shows Entire Font. `text.glyphCategories` lists them for agents. Tests: `fontdb::gsub::tests` in the text crate, `panels::glyphs::tests::the_show_menu_lists_the_fonts_opentype_categories`, `tests::fontlist::glyph_categories_list_the_glyphs_of_each_kind_of_feature`. The OpenType panel's Stylistic Sets menu offers `ss01`–`ss20` sets present in the selected text's font, using the font's custom labels when available and numbered labels otherwise. Sets can be combined and deselected individually. With mixed fonts, the menu shows the first selected character's font's sets and applies the feature tag to all selected text; a font without that set draws unchanged. The mixed-font rule is a VectorCraft design choice. Behavior reference: [Add stylistic sets to selected text](https://helpx.adobe.com/illustrator/desktop/design-with-text/special-characters-glyphs/add-stylistic-sets-to-selected-text.html) and the [OpenType specification](https://learn.microsoft.com/en-us/typography/opentype/spec/features_pt). + The OpenType panel menu has a Stylistic Sets submenu after Reset OpenType Features, with the same sets, labels and checks as the panel's Stylistic Sets button; a set chosen there turns on or off for the characters the panel acts on in one undo step, keeping their other features, and the submenu is disabled with no text selected or when the font offers no sets. The 2019 user guide ([the help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf)) has stylistic sets chosen from the OpenType panel menu. The submenu's place in the menu is VectorCraft's own. Tests: `panels::opentype::tests::the_panel_menu_stylistic_sets_submenu_turns_sets_on_and_off`. With Show East Asian Options on, the OpenType panel menu has H or V Style and Roman Italics, as [Format East Asian characters](https://helpx.adobe.com/illustrator/using/formatting-asian-characters.html) describes. H or V Style sets the feature tag `hkna`, which draws kana with the forms the font makes for horizontal type, and with `vkna` for vertical type in vertical type; Roman Italics sets `ital`, the font's italic forms of half-width alphanumerics ([OpenType feature list](https://learn.microsoft.com/en-us/typography/opentype/spec/featurelist)). Each is checked when every selected character has it and turns it on or off for all of them in one undo step; character styles carry both in OpenType Features. Tests: `panels::opentype::tests::kana_style_and_roman_italics_turn_on_and_off`, `features::tests::kana_style_and_roman_italics_are_kept_and_shaped`. `text.setStyle {stroke, strokeWidth}` sets the character stroke's color and weight of the selected type or of a range of its characters (the weight in document points, as `stroke.set` sets it), in the same undo step as the command's other changes. Tests: `tests::textedit::set_style_sets_the_character_stroke`. - **Paragraph alignment:** the shared Paragraph/Properties alignment row leaves every button unselected when the paragraphs it acts on differ. Auto resolves per paragraph; choosing an alignment uses the existing command. Headless paragraph_mixed_alignment_* regressions exercise mixed → Center → Undo, caret/uniform states, Unicode range boundaries, Auto/direction, split runs and grouped text. These regressions and full integration CI pass. Original captures confirm mixed → Center → Undo in the existing alignment-button layout. The [public Paragraph panel guide](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/paragraph-panel-overview.html) lists the seven controls, but does not specify mixed-state rendering. Other paragraph fields remain outside this change; scores and hours unchanged. From e7e90c19c5b22f744905b6952444be8c806ed662 Mon Sep 17 00:00:00 2001 From: datatimp <12644819+datatimp@users.noreply.github.com> Date: Tue, 17 Nov 2026 15:45:42 -0500 Subject: [PATCH 126/176] Document the refused copy of objects beside their own top-level layer --- docs/mcp.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/mcp.md b/docs/mcp.md index 0db522ba42..b3a3a786dd 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5402,7 +5402,8 @@ and `layerRows`, the rows highlighted in the panel. Intertwine for the members an Intertwine group takes; an object placed beside a top-level layer goes inside it); a row never goes into itself or a row inside it, and a locked layer or group takes nothing. With `copy`, the target may be one of the rows copied: the copies go above or below it, as an Alt-drag onto a row's own row (or a - bottom layer's into the empty space under the list) places them (#8237). Dragging the + bottom layer's into the empty space under the list) places them, unless objects are copied with a top-level layer + that is the target, which would put them inside it (#8237). Dragging the selected-art square is `layer.move` with the selected objects. `node.move {id, parent?, index}` is the low-level form with the same nesting rules; unlike `layer.move`, it also moves a row into a locked layer or group. - **Buttons**: `layer.new {name?, top?, below?, …options}` (above the current layer at its level; `top` with From 5c2b3be4fc314eac42296007d2c291f5d6134c05 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 17 Nov 2026 12:46:07 -0800 Subject: [PATCH 127/176] Document Setup: a grid color box opens the Color Picker On the Transparency tab, a click on either color box beside Grid Colors, or Enter or Space with the keyboard on it, opens the Color Picker over Document Setup on that color. The picker's OK sets only that entry of gridColors and goes back to Document Setup, whose Grid Colors menu then names the pair (Custom unless it matches a preset); Document Setup's OK applies it in one undo step. The picker's Cancel leaves both colors as they were. Each box is a focusable button named for its color. --- crates/ui-egui/src/dialogs/color_picker.rs | 27 ++- crates/ui-egui/src/dialogs/document_setup.rs | 163 ++++++++++++++++++- docs/mcp.md | 3 + docs/target-app-parity.md | 1 + 4 files changed, 190 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/dialogs/color_picker.rs b/crates/ui-egui/src/dialogs/color_picker.rs index f86ee17f51..ca0e6051f8 100644 --- a/crates/ui-egui/src/dialogs/color_picker.rs +++ b/crates/ui-egui/src/dialogs/color_picker.rs @@ -285,6 +285,18 @@ pub(super) fn over_effect(parent: &Dialog, field: &str, colour: Color) -> Dialog d } +/// The entry of the dialog's color list that a Color Picker opened with [`over_list_entry`] sets. +const COLOUR_INDEX: &str = "__colourIndex"; + +/// The Color Picker over the dialog `parent`, on `colour`, that sets entry `index` of the dialog's +/// list of colors `field` (Document Setup's `gridColors`) with its OK and goes back to it, leaving +/// the other entries as they are. Cancel goes back to `parent` as it was. It previews nothing. +pub(super) fn over_list_entry(parent: &Dialog, field: &str, index: usize, colour: Color) -> Dialog { + let mut d = over_effect(parent, field, colour); + d.fields.insert(COLOUR_INDEX.into(), json!(index)); + d +} + /// The field of a Color Picker opened over Recolor Artwork ([`over_recolor`]): the row whose new /// color it picks. const RECOLOR_ROW: &str = "__recolorRow"; @@ -724,7 +736,20 @@ fn swatch_list(app: &VectorcraftApp, ui: &mut Ui, d: &mut Dialog, current: &Colo fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> { if let Some(field) = d.fields.get(COLOUR_FIELD).and_then(Value::as_str) { let mut parent = super::parent(d).ok_or("the dialog it was opened over is no longer open")?; - parent.fields.insert(field.to_string(), json!(picked(d).color.to_hex())); + let hex = json!(picked(d).color.to_hex()); + match d.fields.get(COLOUR_INDEX) { + None => { + parent.fields.insert(field.to_string(), hex); + } + Some(index) => { + let entry = index + .as_u64() + .and_then(|i| usize::try_from(i).ok()) + .and_then(|i| parent.fields.get_mut(field)?.as_array_mut()?.get_mut(i)) + .ok_or("no such color")?; + *entry = hex; + } + } // The dialog previews the new colour when it comes back: end this picker's interaction, as // Cancel does, so the dialog starts its preview afresh. let _ = app.session.cancel_interaction(); diff --git a/crates/ui-egui/src/dialogs/document_setup.rs b/crates/ui-egui/src/dialogs/document_setup.rs index 1946cc86b2..f1fa79018c 100644 --- a/crates/ui-egui/src/dialogs/document_setup.rs +++ b/crates/ui-egui/src/dialogs/document_setup.rs @@ -175,6 +175,11 @@ fn general(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool close } +/// The id of the Transparency tab's box that shows grid color `index` (0 or 1). +fn grid_color_box_id(index: usize) -> egui::Id { + egui::Id::unique(("grid-color-box", index)) +} + fn transparency(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { let t = Tokens::get(ui.ctx()); widgets::subheader(ui, tl!("Transparency Grid")); @@ -196,16 +201,35 @@ fn transparency(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { d.fields.insert("gridColors".into(), json!(pair.map(|c| c.to_hex()))); } }); - // The two colours (the first is also the paper colour): editing either makes them Custom. + // The two colours (the first is also the paper colour): editing either makes them Custom. A + // click on a color's box, or Space or Enter with the keyboard on it, opens the Color Picker on + // that color (white when its hex is not a color), and the picker's OK sets that color. + let mut pick = None; widgets::label_row(ui, "", LABEL, |ui| { for i in 0..2 { let hex = colors.get(i).map_or("", |h| h.trim_start_matches('#')); + let colour = vectorcraft_color::Color::from_hex(hex); + let name = format!("{} {}", tl!("Grid Colors:"), i + 1); let (chip, _) = ui.allocate_exact_size(egui::vec2(18.0, 18.0), egui::Sense::hover()); - if let Some(c) = vectorcraft_color::Color::from_hex(hex) { + let resp = ui.interact(chip, grid_color_box_id(i), egui::Sense::click()); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, &name)); + let keyed = resp.has_focus() + && ui.input_mut(|inp| { + inp.consume_key(egui::Modifiers::NONE, egui::Key::Space) | inp.consume_key(egui::Modifiers::NONE, egui::Key::Enter) + }); + if resp.clicked() || keyed { + pick = Some((i, colour.unwrap_or(vectorcraft_color::Color::WHITE))); + } + if resp.hovered() { + ui.ctx().set_cursor_icon(egui::CursorIcon::PointingHand); + } + if let Some(c) = colour { ui.painter().rect_filled(chip, 2.0, crate::panels::c32(&c)); } ui.painter().rect_stroke(chip, 2.0, egui::Stroke::new(1.0, t.input_border), egui::StrokeKind::Inside); - let name = format!("{} {}", tl!("Grid Colors:"), i + 1); + if resp.has_focus() { + ui.painter().rect_stroke(chip.expand(2.0), 3.0, ui.visuals().selection.stroke, egui::StrokeKind::Outside); + } if let Some(c) = widgets::hex_field_named(ui, ("grid-color", i), Some(&name), hex).and_then(|h| vectorcraft_color::Color::from_hex(&h)) { let mut v = colors.clone(); v.resize(2, "#ffffff".into()); @@ -215,6 +239,9 @@ fn transparency(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { ui.add_space(10.0); } }); + if let Some((i, c)) = pick { + *d = super::color_picker::over_list_entry(d, "gridColors", i, c); + } ui.add_space(4.0); check(ui, d, "simulatePaper", tl!("Simulate Colored Paper")); ui.add_space(14.0); @@ -635,4 +662,134 @@ mod tests { assert_eq!(fill(&app, id), before); assert_eq!(undo_steps(&app), steps); } + + /// The Light pair a new document's transparency grid starts with. + const LIGHT: [&str; 2] = ["#ffffff", "#cccccc"]; + + fn hex(h: &str) -> Color { + Color::from_hex(h).unwrap_or_else(|| panic!("bad hex {h}")) + } + + /// The grid colors Document Setup `d` holds. + fn dialog_grid(d: &crate::state::Dialog) -> Vec<Color> { + d.fields["gridColors"].as_array().unwrap().iter().map(|c| hex(c.as_str().unwrap())).collect() + } + + /// A new document with Document Setup open on its Transparency tab, drawn in the context returned. + fn transparency_tab() -> (VectorcraftApp, egui::Context) { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("file.documentSetup", json!({})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("tab".into(), json!("Transparency")); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + crate::theme::apply(&ctx, Default::default()); + for _ in 0..4 { + dialog_frame(&mut app, &ctx, vec![]); + } + (app, ctx) + } + + /// Clicks the box of grid color `index`. + fn click_grid_box(app: &mut VectorcraftApp, ctx: &egui::Context, index: usize) { + let at = ctx.read_response(super::grid_color_box_id(index)).unwrap_or_else(|| panic!("no box {index}")).rect.center(); + let button = |pressed| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Default::default() }; + dialog_frame(app, ctx, vec![Event::PointerMoved(at), button(true)]); + dialog_frame(app, ctx, vec![button(false)]); + } + + /// The Color Picker is open over Document Setup, on `color`, and Document Setup's OK has not run. + fn assert_picker_over_setup(app: &VectorcraftApp, color: &str, case: &str) { + let d = app.ui.dialog.as_ref().unwrap_or_else(|| panic!("{case}: no dialog")); + assert_eq!(d.kind, "colorPicker", "{case}"); + assert_eq!(d.fields.get("color").and_then(vectorcraft_engine::cmd::color_value), Some(hex(color)), "{case}"); + assert_eq!(crate::dialogs::parent(d).map(|p| p.kind), Some(super::KIND.to_string()), "{case}"); + assert_eq!(undo_steps(app), 0, "{case}: Document Setup's OK has not run"); + } + + /// A click on either grid color's box opens the Color Picker over Document Setup on that + /// color. Its OK sets only that color, the Grid Colors menu names the pair (Custom, or the + /// preset it matches), and Document Setup's OK applies the pair in one undo step. + #[test] + fn a_grid_color_box_opens_the_color_picker_and_its_ok_sets_that_color() { + for (index, picked, pair, name) in [(0, "#00ff00", ["#00ff00", "#cccccc"], "Custom"), (1, "#c4dcff", ["#ffffff", "#c4dcff"], "Blue")] { + let (mut app, ctx) = transparency_tab(); + click_grid_box(&mut app, &ctx, index); + assert_picker_over_setup(&app, LIGHT[index], name); + app.ui.dialog.as_mut().unwrap().fields.insert("color".into(), json!(picked)); + crate::dialogs::confirm(&mut app).unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.kind.as_str(), dialog_grid(d)), (super::KIND, pair.map(hex).to_vec()), "{name}"); + assert_eq!(undo_steps(&app), 0, "{name}: the picker's OK leaves the document as it is"); + dialog_frame(&mut app, &ctx, vec![]); + let texts: Vec<String> = dialog_frame(&mut app, &ctx, vec![]).into_iter().map(|(t, _)| t).collect(); + assert!(texts.iter().any(|t| t == name), "{name}: {texts:?}"); + crate::dialogs::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + let st = app.session.active().unwrap(); + assert_eq!((st.doc.setup.grid_colors, st.doc.setup.grid_colors_name()), (pair.map(hex), name)); + assert_eq!(undo_steps(&app), 1, "{name}"); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(app.session.active().unwrap().doc.setup.grid_colors, LIGHT.map(hex), "{name}"); + } + } + + /// With the keyboard on a grid color's box, Enter or Space opens the Color Picker on that + /// color instead of pressing Document Setup's OK. + #[test] + fn enter_or_space_on_a_grid_color_box_opens_the_color_picker() { + for (index, key) in [(0, egui::Key::Enter), (1, egui::Key::Space)] { + let (mut app, ctx) = transparency_tab(); + ctx.memory_mut(|m| m.request_focus(super::grid_color_box_id(index))); + dialog_frame(&mut app, &ctx, vec![]); + let press = Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() }; + dialog_frame(&mut app, &ctx, vec![press]); + assert_picker_over_setup(&app, LIGHT[index], &format!("{key:?}")); + } + } + + /// Cancel in the Color Picker goes back to Document Setup with the grid colors as they were, + /// and so does its OK on the color it opened on; Document Setup's OK then records no undo step. + #[test] + fn grid_color_picker_cancel_or_an_unchanged_ok_changes_nothing() { + for cancel in [true, false] { + let (mut app, ctx) = transparency_tab(); + click_grid_box(&mut app, &ctx, 1); + assert_picker_over_setup(&app, LIGHT[1], &format!("cancel {cancel}")); + if cancel { + app.ui.dialog.as_mut().unwrap().fields.insert("color".into(), json!("#ff0000")); + crate::dialogs::cancel(&mut app); + } else { + crate::dialogs::confirm(&mut app).unwrap(); + } + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.kind.as_str(), dialog_grid(d)), (super::KIND, LIGHT.map(hex).to_vec()), "cancel {cancel}"); + crate::dialogs::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(app.session.active().unwrap().doc.setup.grid_colors_name(), "Light"); + assert_eq!(undo_steps(&app), 0, "cancel {cancel}"); + } + } + + /// The picker's OK sets nothing when the dialog under it has no such color or is gone: it is + /// an error, and the picker stays open. + #[test] + fn grid_color_picker_without_its_color_or_its_dialog_is_an_error() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.run("file.documentSetup", json!({})).unwrap(); + let setup = app.ui.dialog.clone().unwrap(); + let mut short = setup.clone(); + short.fields.insert("gridColors".into(), json!(["#ffffff"])); + let mut orphan = crate::dialogs::color_picker::over_list_entry(&setup, "gridColors", 0, Color::WHITE); + orphan.fields.remove(crate::dialogs::PARENT); + for picker in [crate::dialogs::color_picker::over_list_entry(&short, "gridColors", 1, Color::WHITE), orphan] { + app.ui.dialog = Some(picker); + app.ui.dialog.as_mut().unwrap().fields.insert("color".into(), json!("#ff0000")); + assert!(crate::dialogs::confirm(&mut app).is_err()); + assert_eq!(app.ui.dialog.as_ref().map(|d| d.kind.as_str()), Some("colorPicker")); + } + assert_eq!(app.session.active().unwrap().doc.setup.grid_colors, LIGHT.map(hex)); + assert_eq!(undo_steps(&app), 0); + } } diff --git a/docs/mcp.md b/docs/mcp.md index 4c1b661f42..47280755e2 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7385,6 +7385,9 @@ small caps size (1 to 200%) lies outside those ranges opens with the nearer end `document.setup` does not take the color mode or the assigned profiles. The Document Setup dialog's Color tab sets them with `edit.assignProfile` and `file.documentColorMode`: its OK runs `document.setup`, then `edit.assignProfile`, then `file.documentColorMode` in one `command.batch`, and the document's changes are one undo step. +On the dialog's Transparency tab, a click on either grid color's box (or Enter or Space with the keyboard on it) opens +the `colorPicker` dialog over Document Setup on that color. Its OK sets only that entry of the dialog's `gridColors` +and goes back to Document Setup, whose OK runs `document.setup`; its Cancel goes back with `gridColors` unchanged. ```json {"name":"run_command","arguments":{"command":"document.setup","params":{"gridColors":"Blue","gridSize":"large","language":"German","bleed":9}}} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index ef83de54ad..233b38249e 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -810,6 +810,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Window › New Window (G7, #4116):** New Window (`window.newWindow`) opens another view of the current document ([public source](https://helpx.adobe.com/illustrator/using/viewing-artwork.html) describes showing one document in several windows at once), with its own zoom, center, rotation, artboard and Outline or Preview, as a tab of its own; an edit in one view shows in every view. Tile, Cascade, Float in Window, Float All in Windows and Consolidate All Windows arrange each view as they arrange a document, and Next and Previous Document step through the views. Closing a view leaves the document open; closing its last view closes the document, asking to save it first. The view's number after the name in its tab ("Name:2", while the document has more than one view) is VectorCraft's own. Tests: `crates/ui-egui/src/doc_windows/tests.rs`. - **Document Setup modal handoff:** Document Setup → Edit Artboards applies valid settings, closes the dialog and activates the Artboard tool. Pointer-click tests cover successful handoff, invalid settings, OK, Cancel and Undo in `dialogs/document_setup.rs`. +- **Document Setup › Transparency grid color boxes:** a click on either color box beside Grid Colors opens the Color Picker on that color, as [the help page](https://helpx.adobe.com/illustrator/desktop/manage-colors/apply-transparency-and-blending/view-transparency-in-artworks.html) describes choosing a custom color for each of the grid's two alternating squares. The picker's OK sets only that color in the dialog, Grid Colors then names the pair (Custom unless it matches one of VectorCraft's presets), and Document Setup's OK applies it in one undo step; the picker's Cancel leaves both colors as they were. With the keyboard on a box, Enter or Space opens the picker. The keyboard handling and staging the color until Document Setup's OK are VectorCraft's own. Tests: `a_grid_color_box_opens_the_color_picker_and_its_ok_sets_that_color` and the other grid color tests in `dialogs/document_setup.rs`. - **Document Setup › Color:** a Color tab shows the document color mode (RGB Color or CMYK Color), a Convert to CMYK or Convert to RGB box for a mode change (cleared: the colors keep their numbers), and the RGB and CMYK profiles assigned to the document, with a working-space entry for none. OK runs `edit.assignProfile` and then `file.documentColorMode` with the dialog's other changes in one `command.batch`, and the document's changes are one undo step. An unchanged Color tab adds no color commands, and Cancel, or OK with nothing changed, records no undo step. A Color tab field with a value of the wrong kind is an error, and the dialog stays open. The tab is VectorCraft's own layout; File › Document Color Mode and Edit › Assign Profile… stay as they are. Tests in `dialogs/document_setup.rs`. - **Assign Profile's three choices:** the Assign rows of Edit › Assign Profile… (the Separations panel's Color Settings section) offer Don't Color Manage This Document, the working space of the document's color mode (Working RGB or Working CMYK, with its name) and Profile with the other profiles of that kind, as [Assign or remove a color profile](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=150) lists them. They act on the profile of the document's color mode: an RGB document's RGB profile, a CMYK document's CMYK profile; the other model's profile stays as it is (VectorCraft's own rule; Document Setup › Color sets both). Picking the working space assigns its profile, which stays when the working space changes later. A choice the document already has runs nothing. Tests in `panels/separations.rs`. - **Canvas through the display's profile on Windows and X11:** Preferences › Performance › Use Monitor Profile for Canvas (on by default) converts the canvas's art, artboard paper and transparency grid from sRGB into the ICC profile of the display that shows most of the main window, after any proof, as the help page describes the monitor's profile translating the document's colors for the monitor ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=151)). Windows gives the display's default profile, and a display with Advanced Color on is left to Windows ([Microsoft Learn](https://learn.microsoft.com/en-us/windows/win32/wcs/advanced-color-icc-profiles)); X11 gives colord's profile for the output or the `_ICC_PROFILE` property. macOS converts the window itself, and a Wayland session stays sRGB. `ui.inspect` reports `displayProfile`. Tests in `color/src/cms/display.rs`, `ui-egui/src/display_profile.rs` and `canvas::tests::the_canvas_is_drawn_through_the_display_profile_while_the_preference_is_on`. From 88b5da22bc5e962c33d0d92a803d7dda45a98ad1 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 17 Nov 2026 12:46:29 -0800 Subject: [PATCH 128/176] DXF: Use Artboards applies live effects once for all the drawings DXF export with Use Artboards baked the whole document's live effects and placed symbol art again for every artboard. export_drawings now checks the options and every region, bakes once, and writes each drawing from the same baked document. export calls it with one drawing, and the encoder makes one call for all the chosen artboards. Each drawing's bytes, linked images, warnings and setting notes are the same as before; the tests compare them with drawings baked one at a time. --- crates/cad/src/lib.rs | 39 ++++- crates/cad/src/tests.rs | 198 ++++++++++++++++++++++ crates/engine/src/cmd/fileio/dxf.rs | 5 +- crates/engine/src/cmd/fileio/tests_dxf.rs | 18 ++ docs/target-app-parity.md | 1 + 5 files changed, 253 insertions(+), 8 deletions(-) diff --git a/crates/cad/src/lib.rs b/crates/cad/src/lib.rs index eafb4616f1..8aefe61a0d 100644 --- a/crates/cad/src/lib.rs +++ b/crates/cad/src/lib.rs @@ -7,6 +7,8 @@ //! hatches, type text entities or glyph outlines, and placed images image entities linked to PNG //! or JPEG files the caller writes next to the drawing. Coordinates are y-up, in drawing units: `scale` units per //! `unit` of the art, with the origin at the bottom-left corner of [`DxfOptions::region`]. +//! [`export_drawings`] writes one such drawing for each of several regions, applying the live +//! effects once for all of them. //! //! What DXF can't hold (blending modes, opacity masks, raster effects, gradients, patterns, //! clipping) is approximated or left out, and each such loss comes back as a warning. @@ -436,18 +438,43 @@ pub const SCALE_RANGE: std::ops::RangeInclusive<f64> = 1e-6..=1e6; /// Write `doc` as a DXF drawing with `opts`. Live geometry effects are applied first; template /// layers, guides and hidden objects are left out. pub fn export(doc: &Document, opts: &DxfOptions) -> Result<DxfOutput, String> { + Ok(export_drawings(doc, opts, &[(opts.region, opts.crop)])?.pop().unwrap_or_default()) +} + +/// Write `doc` as one DXF drawing for each `(region, crop)` of `drawings`, in order, each as +/// [`export`] writes it with `opts` and that region and crop. Live geometry effects are applied +/// once for all the drawings. +pub fn export_drawings(doc: &Document, opts: &DxfOptions, drawings: &[(Rect, bool)]) -> Result<Vec<DxfOutput>, String> { + export_drawings_with(doc, opts, drawings, bake_for_drawings) +} + +/// `doc` with its live geometry effects applied and its symbols' art placed, or `None` when +/// nothing changes. +fn bake_for_drawings(doc: &Document) -> Option<Document> { + // Symbols' art is placed without clipping, as the scene places it. + let layers = vectorcraft_effects::WrittenLayers { hidden: true, non_printing: true, hidden_objects: false }; + vectorcraft_effects::bake_document_placing_symbols(doc, false, layers) +} + +/// [`export_drawings`] with `bake` applying the live effects. +fn export_drawings_with( + doc: &Document, + opts: &DxfOptions, + drawings: &[(Rect, bool)], + bake: impl Fn(&Document) -> Option<Document>, +) -> Result<Vec<DxfOutput>, String> { if !(opts.scale.is_finite() && SCALE_RANGE.contains(&opts.scale)) { return Err(format!("scale must be a number from {} to {}, not {}", SCALE_RANGE.start(), SCALE_RANGE.end(), opts.scale)); } - let r = opts.region; - if ![r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite()) { + if drawings.iter().any(|(r, _)| ![r.x0, r.y0, r.x1, r.y1].iter().all(|v| v.is_finite())) { return Err("the export region is not finite".into()); } - // Symbols' art is placed without clipping, as the scene places it. - let layers = vectorcraft_effects::WrittenLayers { hidden: true, non_printing: true, hidden_objects: false }; - let baked = vectorcraft_effects::bake_document_placing_symbols(doc, false, layers); + if drawings.is_empty() { + return Ok(vec![]); + } + let baked = bake(doc); let doc = baked.as_ref().unwrap_or(doc); - Ok(scene::Scene::new(doc, opts).run()) + Ok(drawings.iter().map(|&(region, crop)| scene::Scene::new(doc, &DxfOptions { region, crop, ..opts.clone() }).run()).collect()) } #[cfg(test)] diff --git a/crates/cad/src/tests.rs b/crates/cad/src/tests.rs index dda09a0696..797223b688 100644 --- a/crates/cad/src/tests.rs +++ b/crates/cad/src/tests.rs @@ -1493,3 +1493,201 @@ fn export_bytes_match_shared_writer_goldens() { assert_eq!(got, expected, "DXF bytes changed versus {}", path.display()); } } + +/// One drawing written by applying the live effects for it alone and walking the result, as each +/// drawing of a multi-drawing export was written before [`export_drawings`]. +fn export_baking_alone(doc: &Document, opts: &DxfOptions) -> DxfOutput { + let baked = crate::bake_for_drawings(doc); + crate::scene::Scene::new(baked.as_ref().unwrap_or(doc), opts).run() +} + +/// A written drawing's bytes, linked images (name and bytes), warnings and setting notes. +type Written = (Vec<u8>, Vec<(String, Vec<u8>)>, Vec<String>, Vec<String>); + +/// Every field of a written drawing, for comparing two. +fn written(out: &DxfOutput) -> Written { + let images = out.images.iter().map(|i| (i.name.clone(), i.bytes.clone())).collect(); + (out.bytes.clone(), images, out.warnings.clone(), out.setting_notes.clone()) +} + +/// A Transform effect that moves its object `x` pt right. +fn moved_by(mut n: Node, x: f64) -> Node { + n.appearance.effects.push(vectorcraft_doc::Effect { id: "distort.transform".into(), params: serde_json::json!({"moveH": x}), visible: true }); + n +} + +/// A line moved by a Transform effect, an instance of a symbol whose art carries the same effect +/// stained by its fill, a semi-transparent line in a blending mode, and a placed PNG image. +fn drawings_doc() -> Document { + let png = craft_image_codecs::encode( + &craft_image_codecs::Image::from_raw( + 2, + 2, + craft_image_codecs::ChannelLayout::Rgba, + craft_image_codecs::SampleType::U8, + [0u8, 128, 255, 255].repeat(4), + ) + .unwrap(), + craft_image_codecs::Format::Png, + &craft_image_codecs::EncodeOptions::default(), + ) + .unwrap(); + let mut d = doc_with(|d| { + let line = path(d, shapes::line((10.0, 10.0).into(), (20.0, 10.0).into()), Paint::None, Paint::solid(Color::BLACK), 1.0); + let mut instance = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Moved".into(), xf: Affine::IDENTITY }); + instance.appearance = Appearance::basic(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), Paint::None, 0.0).into(); + let mut faint = path(d, shapes::line((10.0, 90.0).into(), (190.0, 90.0).into()), Paint::None, Paint::solid(Color::BLACK), 1.0); + faint.opacity = 0.5; + faint.blend = vectorcraft_color::BlendMode::Multiply; + let im = ImageObject { + key: "raster-1".into(), + width: 2, + height: 2, + xf: Affine::translate((150.0, 20.0)) * Affine::scale(10.0), + link: None, + placement: Default::default(), + pixels: None, + }; + vec![moved_by(line, 100.0), instance, faint, Node::new(d.alloc_id(), NodeKind::Image(Box::new(im)))] + }); + let art = path(&mut d, shapes::rectangle(Rect::new(10.0, 40.0, 30.0, 60.0)), Paint::solid(Color::rgb(1.0, 0.0, 0.0)), Paint::None, 0.0); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Moved".into(), art: Arc::new(moved_by(art, 20.0)) }); + d.images.insert("raster-1".into(), ImageBlob { mime: "image/png".into(), bytes: Arc::new(png), proxy: None }); + d +} + +#[test] +fn drawings_apply_the_live_effects_once_and_match_drawings_written_alone() { + let d = drawings_doc(); + assert!(crate::bake_for_drawings(&d).is_some(), "the document has live effects to apply"); + // The left and right halves cropped, the whole page uncropped, and a region off the page. + let drawings = [ + (Rect::new(0.0, 0.0, 100.0, 100.0), true), + (Rect::new(100.0, 0.0, 200.0, 100.0), true), + (Rect::new(0.0, 0.0, 200.0, 100.0), false), + (Rect::new(300.0, 0.0, 400.0, 100.0), true), + ]; + // With every option, and with images and hatches left out (which adds setting notes). + let all_in = opts(&d); + for o in [all_in.clone(), DxfOptions { include_images: false, include_hatches: false, ..all_in }] { + let bakes = std::cell::Cell::new(0); + let outs = crate::export_drawings_with(&d, &o, &drawings, |doc| { + bakes.set(bakes.get() + 1); + crate::bake_for_drawings(doc) + }) + .unwrap(); + assert_eq!(bakes.get(), 1, "the live effects are applied once for every drawing"); + assert_eq!(outs.len(), drawings.len()); + for ((region, crop), out) in drawings.iter().zip(&outs) { + let alone = export_baking_alone(&d, &DxfOptions { region: *region, crop: *crop, ..o.clone() }); + assert_eq!(written(out), written(&alone), "the drawing over {region:?}, crop {crop}"); + let one = export(&d, &DxfOptions { region: *region, crop: *crop, ..o.clone() }).unwrap(); + assert_eq!(written(&one), written(&alone), "export over {region:?}, crop {crop}"); + } + let public: Vec<_> = export_drawings(&d, &o, &drawings).unwrap().iter().map(written).collect(); + assert_eq!(public, outs.iter().map(written).collect::<Vec<_>>()); + // The halves hold different art, the left half a line with losses, and the region off the + // page nothing. + assert!(!entities(&outs[0]).is_empty() && !entities(&outs[1]).is_empty() && !outs[0].warnings.is_empty()); + assert_ne!(outs[0].bytes, outs[1].bytes); + assert!(entities(&outs[3]).is_empty() && outs[3].images.is_empty()); + if o.include_images { + assert_eq!(outs[2].images.len(), 1); + } else { + assert!(!outs[2].setting_notes.is_empty() && outs[2].images.is_empty()); + } + } +} + +#[test] +fn drawings_are_checked_before_the_live_effects_are_applied() { + let d = drawings_doc(); + let o = opts(&d); + let bakes = std::cell::Cell::new(0); + let count = |doc: &Document| { + bakes.set(bakes.get() + 1); + crate::bake_for_drawings(doc) + }; + let page = (d.artboards[0].rect, false); + let off = (Rect::new(0.0, 0.0, f64::NAN, 100.0), false); + assert_eq!(crate::export_drawings_with(&d, &o, &[page, off], count).unwrap_err(), "the export region is not finite"); + let e = crate::export_drawings_with(&d, &DxfOptions { scale: 0.0, ..o.clone() }, &[page], count).unwrap_err(); + assert!(e.starts_with("scale must be a number"), "{e}"); + assert!(crate::export_drawings_with(&d, &o, &[], count).unwrap().is_empty()); + assert_eq!(bakes.get(), 0, "nothing is applied for drawings that are refused or for none"); +} + +/// The thread's time on the CPU in nanoseconds where Linux reports it, otherwise `None`. +fn thread_cpu_ns() -> Option<u64> { + std::fs::read_to_string("/proc/thread-self/schedstat").ok()?.split_whitespace().next()?.parse().ok() +} + +/// Time a Use Artboards export of eight artboards whose art has live effects, written drawing by +/// drawing with the effects applied for each (as before [`export_drawings`]) and with +/// [`export_drawings`], alternating, seven times each, and check that both write the same +/// drawings. Prints the median of each in milliseconds of the thread's CPU time (on Linux) and of +/// wall-clock time. +/// Run with `cargo test --release -p vectorcraft-cad --lib dxf_artboards_bake_perf -- --ignored --nocapture`. +#[test] +#[ignore = "manual timing probe; wall-clock performance depends on machine load"] +fn dxf_artboards_bake_perf() { + const BOARDS: usize = 8; + let mut d = Document::new(200.0 * BOARDS as f64, 200.0); + let layer = d.layers[0].id; + let effect = |id: &str, params: serde_json::Value| vectorcraft_doc::Effect { id: id.into(), params, visible: true }; + let mut art = vec![]; + for i in 0..50 { + let (x, y) = (f64::from(i % 10) * 5.0, f64::from(i / 10) * 5.0); + art.push(Arc::new(path(&mut d, shapes::rectangle(Rect::new(x, y, x + 4.0, y + 4.0)), Paint::None, Paint::solid(Color::BLACK), 0.5))); + } + let mut cell = Node::group(d.alloc_id(), art); + cell.appearance.effects.push(effect("distort.zigZag", serde_json::json!({"size": 1.0, "relative": false, "ridges": 4, "points": "smooth"}))); + d.symbols.push(vectorcraft_doc::Symbol { dynamic: false, name: "Cell".into(), art: Arc::new(cell) }); + for b in 0..BOARDS { + let x0 = 200.0 * b as f64; + for i in 0..250 { + let (x, y) = (x0 + f64::from(i % 25) * 8.0, f64::from(i / 25) * 8.0); + let mut n = path(&mut d, shapes::ellipse(Rect::new(x, y, x + 6.0, y + 6.0)), Paint::None, Paint::solid(Color::BLACK), 0.5); + let params = serde_json::json!({"size": 1.0, "relative": false, "detail": 10.0, "points": "smooth", "seed": i}); + n.appearance.effects.push(effect("distort.roughen", params)); + d.insert(Some(layer), usize::MAX, n).unwrap(); + } + for i in 0..20 { + let xf = Affine::translate((x0 + f64::from(i % 5) * 40.0, 100.0 + f64::from(i / 5) * 25.0)); + let instance = Node::new(d.alloc_id(), NodeKind::SymbolInstance { symbol: "Cell".into(), xf }); + d.insert(Some(layer), usize::MAX, instance).unwrap(); + } + } + let o = DxfOptions { unit: Unit::Points, ..DxfOptions::default() }; + let drawings: Vec<(Rect, bool)> = (0..BOARDS).map(|b| (Rect::new(200.0 * b as f64, 0.0, 200.0 * (b + 1) as f64, 200.0), true)).collect(); + let before = || drawings.iter().map(|&(region, crop)| export_baking_alone(&d, &DxfOptions { region, crop, ..o.clone() })).collect::<Vec<_>>(); + let after = || export_drawings(&d, &o, &drawings).unwrap(); + let time = |f: &dyn Fn() -> Vec<DxfOutput>| { + let (cpu, wall) = (thread_cpu_ns(), std::time::Instant::now()); + let outs = f(); + let wall = wall.elapsed().as_secs_f64() * 1000.0; + let cpu = cpu.zip(thread_cpu_ns()).map(|(a, b)| (b - a) as f64 / 1e6); + (outs, cpu, wall) + }; + let (mut runs_before, mut runs_after) = (vec![], vec![]); + for _ in 0..7 { + let (a, cpu_a, wall_a) = time(&before); + let (b, cpu_b, wall_b) = time(&after); + assert_eq!(a.len(), BOARDS); + assert_eq!(a.iter().map(written).collect::<Vec<_>>(), b.iter().map(written).collect::<Vec<_>>(), "both write the same drawings"); + runs_before.push((cpu_a, wall_a)); + runs_after.push((cpu_b, wall_b)); + } + let median = |runs: &[(Option<f64>, f64)], cpu: bool| { + let mut v: Vec<f64> = runs.iter().filter_map(|r| if cpu { r.0 } else { Some(r.1) }).collect(); + v.sort_by(f64::total_cmp); + v.get(v.len() / 2).copied() + }; + for (name, runs) in [("drawing by drawing", &runs_before), ("export_drawings", &runs_after)] { + println!( + "{name}: {BOARDS} artboards, median CPU {:?} ms, median wall {:?} ms; runs (CPU ms, wall ms) {runs:?}", + median(runs, true), + median(runs, false) + ); + } +} diff --git a/crates/engine/src/cmd/fileio/dxf.rs b/crates/engine/src/cmd/fileio/dxf.rs index 8486cd2226..8004234c07 100644 --- a/crates/engine/src/cmd/fileio/dxf.rs +++ b/crates/engine/src/cmd/fileio/dxf.rs @@ -226,9 +226,10 @@ pub(super) fn encode(doc: &Document, p: &Value, use_artboards: Option<bool>) -> vec![(Some(b), rect(b)?, false)] } }; + let regions: Vec<(Rect, bool)> = drawings.iter().map(|&(_, region, crop)| (region, crop)).collect(); + let outs = vectorcraft_cad::export_drawings(doc, &opts, ®ions).map_err(|e| bad(C, e))?; let mut enc = Encoded::default(); - for (board, region, crop) in drawings { - let out = vectorcraft_cad::export(doc, &DxfOptions { region, crop, ..opts.clone() }).map_err(|e| bad(C, e))?; + for ((board, _, _), out) in drawings.into_iter().zip(outs) { enc.files.push((board, out.bytes)); for w in out.warnings { if !enc.warnings.contains(&w) { diff --git a/crates/engine/src/cmd/fileio/tests_dxf.rs b/crates/engine/src/cmd/fileio/tests_dxf.rs index 1a3368b56f..b5129d1910 100644 --- a/crates/engine/src/cmd/fileio/tests_dxf.rs +++ b/crates/engine/src/cmd/fileio/tests_dxf.rs @@ -116,6 +116,24 @@ fn use_artboards_writes_one_drawing_per_artboard() { assert!(e.contains("useArtboards"), "{e}"); } +#[test] +fn each_artboard_s_drawing_is_the_drawing_of_that_artboard_alone() { + let mut s = two_boards(); + // A second rectangle on the second artboard, so the two drawings differ. + let second = s.doc().unwrap().doc.artboards[1].rect.x0; + s.execute("shape.rectangle", &json!({"x": second + 50.0, "y": 50, "width": 20, "height": 20})).unwrap(); + let r = s.execute("document.export", &json!({"format": "dxf", "useArtboards": true, "unit": "pt"})).unwrap(); + let files = r["files"].as_array().unwrap(); + let doc = &s.doc().unwrap().doc; + let o = dxf::options(&json!({"unit": "pt"})).unwrap(); + assert_eq!(files.len(), doc.artboards.len()); + assert_ne!(b64(&files[0]), b64(&files[1])); + for (f, board) in files.iter().zip(&doc.artboards) { + let alone = vectorcraft_cad::export(doc, &vectorcraft_cad::DxfOptions { region: board.rect, crop: true, ..o.clone() }).unwrap(); + assert_eq!(b64(f), alone.bytes, "{}", f["name"]); + } +} + #[test] fn selected_only_exports_the_selection_in_its_layers() { let mut s = two_boards(); diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index e9fc9a6820..193fbbfb56 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2055,6 +2055,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - DXF control-point SPLINE import honors its closed flag (#1299 follow-up after #1320 fixed export), including rational curves; open curves whose endpoints meet stay open. Own-fixture regressions cover controls/knots, fit-point fallback and all export versions (`crates/cad/src/import/tests.rs`, `crates/cad/src/tests.rs`); native save/read checked. Circular cubic paths export as native CIRCLE/ARC where stroke semantics permit; R12 weighted strokes remain POLYLINE; a closed four-cubic ellipse, or a circle scaled out of proportion, exports as a native ELLIPSE in R13 and later (an ellipse whose minor-to-major ratio is below 1e-6 is still written as a polyline or spline), and R12 keeps the existing fallback (`crates/cad/src/tests.rs`); an open path of one straight segment exports as a LINE (R12 to R14 strokes with a weight stay polylines, which carry the width) and reads back as the same segment (`crates/cad/src/tests.rs`, `crates/cad/src/import/tests.rs`); DXF Options' Preset menu and `document.exportDxf`'s `dxfPreset: "cnc"` set the CNC / CAM options (version 2000, 1 mm = 1 unit, 256 colors, Maximize Editability with Alter Paths off, Outline Text, placed images and fill hatches left out), and the menu shows Custom once a field changes (`the_cnc_preset_writes_version_2000_in_millimeters_with_type_as_paths_and_strokes_as_lines`, `the_cnc_preset_sets_the_options_that_are_not_given`, `the_cnc_cam_preset_sets_the_fields_and_a_change_shows_custom`); VCarve QA remains pending. - DXF export's Include Placed Images and Include Fill Hatches (`includeImages`, `includeHatches`; VectorCraft's own options, on by default and off in CNC / CAM) leave out placed images with their linked files, without decoding them, and the solid hatch after each filled area's outlines, each on its own, with one note in `warnings` when something was left out; R12 keeps its own notes. An open path's fill outline is closed, as the fill is, in every version (`an_open_path_s_fill_outline_keeps_its_closing_edge`, `fills_without_hatches_keep_their_outlines`, `images_can_be_left_out_with_their_files`, `images_and_hatches_are_left_out_independently_and_the_cnc_preset_leaves_out_both`, `placed_images_and_fill_hatches_can_be_left_out`, `include_placed_images_and_fill_hatches_follow_the_preset_and_a_change_shows_custom`). - DXF export writes a path of straight segments and circular arcs (a slot, a D shape, a rounded rectangle, a pie) as one polyline whose vertices carry a bulge (group 42) for each arc: an LWPOLYLINE in R14 and later, a POLYLINE with VERTEX entities in R12 and R13, closed when the path is closed, and it reads back as the same outline (#1299, `crates/cad/src/tests.rs`). Such a path was written as one SPLINE (a flattened polyline in R12); a path with any other curve still is. A shallow curve becomes an ARC or a bulge only when it lies on the circle within 5e-4 of its own extent as well as of the radius, and the drawing extents (`$EXTMIN`, `$EXTMAX`) reach the furthest points of every ARC and bulge. + - DXF export with Use Artboards applies live effects and places symbols' art once for all the artboards' drawings instead of once for each drawing; each drawing's bytes, linked images, warnings and notes are the same as before (`drawings_apply_the_live_effects_once_and_match_drawings_written_alone`, `each_artboard_s_drawing_is_the_drawing_of_that_artboard_alone`). - Affinity documents in (AF.1–AF.4): `.af` (Affinity 3) and `.afdesign`/`.afphoto`/`.afpub` (Affinity 1 and 2, container versions 8–12) open and place as editable art: layers and sublayers, groups (pass-through or isolated), artboards (with their names and backgrounds) and Publisher pages side by side, curves with live corners, parametric shapes (rectangles with corner radii, ellipses, polygons, stars, pies, triangles, trapezoids), compound shapes, solid/linear/elliptical gradient fills and strokes (weight, dashes, alignment, scale-with-object), clipping by nesting, vector and pixel masks, artistic and frame text with fonts, sizes, tracking, leading and alignment, placed images (their original JPEG/PNG) and pixel layers (8/16-bit RGB, CMYK), opacity, visibility, locking and blend modes, at the document's resolution in points. Effects, adjustments, brushes and pressure profiles, transparency gradients, master pages, symbol instances (imported as their cached picture), special shapes (cloud, heart, cog…, imported as ellipses) and Affinity-only blend modes are named in the import warning. A file whose native data can't be read opens as its embedded preview with the reason, and that preview can't be placed. Save never writes back over the Affinity file and there is no Affinity export. AF.5 (from DesignCraft's import, storytold/designcraft#291) adds master pages (on a locked layer behind the pages that show them), tables (area type per cell and a line per edge), each paragraph's alignment, indents, spacing and leading, horizontal text scale, outlined text, frame text sized by its text scale, drop shadows and outer glows as live effects (inner shadows as inner glows), outline effects as strokes, colour and gradient overlays baked into the paint, embedded Affinity documents as editable content (their artboards don't become artboards), pixel layers over 64 MP at a reduced resolution and HEIC photos from their stored pixels; automatic leading (size plus the font's line gap) fitted on thumbnails; underlines and strikethrough; strokes whose style is None (every shape stores one) left out, which also brings 6 public files closer to their thumbnails; line breaks inside a paragraph; table cell text centred as Affinity centres it, also where it is taller than its cell; CMYK pixel layers converted through the document's embedded CMYK profile (relative colorimetric with black-point compensation, as each layer's colour settings name), or kept as CMYK images when there is none; outline effects on stroked shapes around their stroke; artistic text whose paragraphs align differently aligned within its longest line, a frame's first baseline at cap height, and frames whose last lines' descenders hang out made tall enough to show them (all measured on a local document's own PDF export: baselines match to 0.1 pt); a local 56-artboard document's mean thumbnail difference went from 16.2 to 11.4, and its pages' mean difference from the owner's PDF export from 12.9 to 9.3. AF.4 adds Affinity 3 artboard recognition and actual-outline clipping, source-backed JPEG/PNG raster tiles, Unicode text-run recovery, stored fallback/exact installed fonts, OpenType feature flags and compound-geometry limits. 51 public CC0/MIT/Apache-2.0 files (33 current `.af`), pinned and sha256-verified (`cargo xtask corpus --affinity`), test native retention and every-board native/SVG/PDF/PSD output for current files; selected files compare their saved thumbnails. No Affinity reopen or independent paired PSD oracle was available; [source audit and complex-font gaps](affinity-validation.md); [scope, provenance and limits](../crates/affinity/README.md). - Placed documents: File › Place of a `.vectorcraft` file links to it by default (`file.place`'s `link`): one locked object showing an artboard of the document (or its art's bounds), read the way placing it without Link reads it, its symbols, patterns and images kept apart from the document's; without Link (or from bytes, not a file) it is an editable copy as before. It stays vectors in every output (SVG, PDF, EPS, EMF, DXF), and so do placed documents inside it, read from their own files up to 8 levels deep (documents that place each other stop there). On screen they draw from bitmaps cached per file and zoom step, shared by every copy and made in the background (a placeholder until ready), so a sheet of them redraws in about a millisecond; exports and prints draw them exactly. Like linked images, a save keeps only a preview of each (JPEG when opaque) unless Include Linked Files; output, and zooming past the preview, read the file again, falling back to the preview with a warning when it is gone or changed. Saves for older versions write them as plain art. Links check, update, relink, Update Links on open, Link Info (the artboard's size), Placement Options, Break Link (also Embed, Object › Expand: the editable copy placing without Link gives, its resources joining the document), Edit Original (the document in a new tab) and the Links panel cover them; saving a document updates the open documents that place it. The native format (v4) keeps data of 8 KB or more after the JSON instead of base64 in it. - Placed documents' bitmaps on screen: when a bitmap made in the background is ready, the desktop app renders the canvas again only where the objects that show its file are, when the frame shown was rendered on the UI thread and that part is at most half the canvas. Bitmaps drawn or made since a frame began are kept for that frame past the 512 MiB budget, up to 2 GiB, so a view showing more than the budget does not make them again in every frame. A bitmap that would take them past 2 GiB is not kept, and its file draws exactly at that zoom. A bitmap that can't be made (the file can't be read and there is no preview) shows the light placeholder and is not asked for again. Each ready bitmap used to render the whole canvas again, and bitmaps past the budget and bitmaps that could not be made were asked for again in every frame (`crates/render/src/tests/placed_document.rs`). From c9dd40ea54696a4c096c6574f4adfe33dd70f0ca Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 17 Nov 2026 12:20:49 -0800 Subject: [PATCH 129/176] Type: Type tools keep the other frames' layouts between frames With a Type tool active, the overlays laid out every selected area type and type on a path on each frame only to read whether its text overflows, and the single kept layout of the edited frame was replaced by each of them, so the edited frame was laid out again too. After Select All in threaded text, the story's other frames were laid out on every frame with no cache at all. The tool now keeps each other frame's layout from the last overlays call, keyed by the layout inputs (fonts and hyphenation exceptions) and the text object, as the ports of the other tools already do. Each call keeps only the frames it draws, up to 2,048, and choosing another tool drops them. The overlays are the same. --- crates/tools/src/text.rs | 34 +++++ crates/tools/src/text/tests.rs | 266 +++++++++++++++++++++++++++++++++ crates/tools/src/text/tool.rs | 9 +- docs/target-app-parity.md | 1 + 4 files changed, 308 insertions(+), 2 deletions(-) diff --git a/crates/tools/src/text.rs b/crates/tools/src/text.rs index 763325f90e..fb7e38bd0f 100644 --- a/crates/tools/src/text.rs +++ b/crates/tools/src/text.rs @@ -137,6 +137,15 @@ fn text_hash(s: &str) -> u64 { /// The edited text's layout, keyed by [`vectorcraft_text::layout_inputs`] and the text. type CachedLayout = ((u64, TextObject), Arc<TextLayout>); +/// The layouts of the frames other than the edited one that the overlays draw (the ports of the +/// selected area type and type on a path, the other frames of a selected story), by frame, each +/// kept with the layout inputs and the text it was made from ([`TypeTool::frame_layout`]). +type FrameLayouts = std::collections::HashMap<NodeId, CachedLayout>; + +/// The most other frames' layouts [`TypeTool::frames`] keeps: every port drawn ([`PORTS_MAX`]) +/// and a long story's frames. The frames an overlays call draws past it are laid out on each call. +const FRAME_LAYOUTS_MAX: usize = 2_048; + /// Process-global Type-tool edit-session counter: the IME target's replacement epoch. /// /// A per-tool counter restarts at zero when the tool is recreated (a document switch, File › @@ -220,6 +229,9 @@ pub struct TypeTool { /// The state at the start of each `command.batch` still running, innermost last. batches: Vec<HistoryState>, cache: Mutex<Option<CachedLayout>>, + /// The other frames' layouts the last overlays drew ([`FrameLayouts`]): each overlays call + /// keeps only the frames it draws. + frames: Mutex<FrameLayouts>, } struct BeforePress { @@ -296,6 +308,28 @@ impl TypeTool { l } + /// Layout of `t`, frame `id`, for an overlays call that draws a frame other than the edited + /// one: the layout kept in `now` or `was` for `id` when it was made from the layout inputs + /// `fonts` and the same text, otherwise a new one. It is kept in `now` either way while `now` + /// holds fewer than [`FRAME_LAYOUTS_MAX`]. + fn frame_layout(now: &mut FrameLayouts, was: &mut FrameLayouts, fonts: u64, id: NodeId, t: &TextObject) -> Arc<TextLayout> { + if let Some(((g, k), l)) = now.get(&id) + && *g == fonts + && k == t + { + return l.clone(); + } + let kept = match was.remove(&id) { + Some(((g, k), l)) if g == fonts && &k == t => ((g, k), l), + _ => ((fonts, t.clone()), Arc::new(vectorcraft_text::layout(FontDb::global(), t))), + }; + let l = kept.1.clone(); + if now.len() < FRAME_LAYOUTS_MAX { + now.insert(id, kept); + } + l + } + /// The edited text used to find word and paragraph boundaries for selection: the typing session's /// runs, or the document's current text when there is no live session or it has gone stale. fn plain(&self, cx: &ToolContext) -> String { diff --git a/crates/tools/src/text/tests.rs b/crates/tools/src/text/tests.rs index 94063166bc..89a24cc3bf 100644 --- a/crates/tools/src/text/tests.rs +++ b/crates/tools/src/text/tests.rs @@ -1636,10 +1636,276 @@ fn the_edited_types_ports_follow_the_limit_too() { tool.start_editing(id, 0); let boxes = |o: &[Overlay]| o.iter().filter(|o| matches!(o, Overlay::Highlight { color: [255, 255, 255, 255], .. })).count(); assert_eq!(boxes(&tool.overlays(&cx(&d, &sel, &p))), 2 * PORTS_MAX, "at the limit, the edited one's included"); + assert_eq!(kept_frames(&tool), PORTS_MAX - 1, "the other frames' layouts are kept"); let copy = d.alloc_id(); d.insert(Some(l), 1, Node::new(copy, node.kind.clone())).unwrap(); sel.add(copy); assert_eq!(boxes(&tool.overlays(&cx(&d, &sel, &p))), 0, "past it, not even the edited one's"); + assert_eq!(kept_frames(&tool), 0, "no ports drawn, no layouts kept"); +} + +/// How many other frames' layouts the Type tool keeps between overlays calls. +fn kept_frames(tool: &TypeTool) -> usize { + tool.frames.lock().unwrap().len() +} + +/// The value `f` returns, and how many layouts this thread started while it ran. +fn counted<T>(f: impl FnOnce() -> T) -> (T, u64) { + let before = vectorcraft_text::test_fonts::layouts_on_this_thread(); + let v = f(); + (v, vectorcraft_text::test_fonts::layouts_on_this_thread() - before) +} + +/// A document with area type frames of `texts` (each 120 × 40 pt, one under the other) and their ids. +fn area_frames(texts: &[&str]) -> (Document, Vec<NodeId>) { + let mut d = Document::new(500.0, 2000.0); + let l = d.layers[0].id; + let mut ids = Vec::new(); + for (i, s) in texts.iter().enumerate() { + let id = d.alloc_id(); + let mut t = TextObject::point(Point::new(50.0, 50.0 + 60.0 * i as f64), s, CharStyle::default()); + t.kind = area_kind(120.0, 40.0); + d.insert(Some(l), 0, Node::new(id, NodeKind::Text(Box::new(t)))).unwrap(); + ids.push(id); + } + (d, ids) +} + +/// Area type in a `w` × `h` pt frame. +fn area_kind(w: f64, h: f64) -> TextKind { + TextKind::Area { frame: vectorcraft_geom::PathData::from_bezpath(&Rect::new(0.0, 0.0, w, h).to_path(0.1)) } +} + +fn text_mut(d: &mut Document, id: NodeId) -> &mut TextObject { + match &mut d.node_mut(id).unwrap().kind { + NodeKind::Text(t) => t, + _ => panic!("not text"), + } +} + +const OVERFLOWS: &str = "This text is far too long to fit in a frame of one hundred and twenty by forty points."; + +/// The Type tools draw the ports of several different selected frames, with and without one of +/// them being edited, without laying any of them out again on the next frame, and draw the same +/// overlays as a tool that lays every frame out afresh. +#[test] +fn type_overlays_keep_the_selected_frames_layouts() { + let (d, ids) = area_frames(&["One", "Two words", "Three words here", OVERFLOWS]); + let (mut sel, p) = (Selection::default(), paint()); + sel.set(ids.iter().copied()); + let c = cx(&d, &sel, &p); + let mut probe = Vec::new(); + push_port(&mut probe, Point::ZERO, PortState::Overflow, [0, 0, 0], 1.0); + let Some(Overlay::Line { color: red, .. }) = probe.last().cloned() else { panic!("the red plus is drawn with lines") }; + let red_plus = |o: &[Overlay]| o.iter().filter(|o| matches!(o, Overlay::Line { color, .. } if *color == red)).count(); + for editing in [None, Some(ids[0])] { + let mut tool = TypeTool::new("areaType"); + if let Some(id) = editing { + tool.start_editing(id, 0); + } + let (first, n) = counted(|| tool.overlays(&c)); + assert!(n > 0, "{editing:?}: the first frame lays the frames out"); + let (second, n) = counted(|| tool.overlays(&c)); + assert_eq!(n, 0, "{editing:?}: the next frame lays none out again"); + assert_eq!(first, second, "{editing:?}"); + let mut fresh = TypeTool::new("areaType"); + if let Some(id) = editing { + fresh.start_editing(id, 0); + } + assert_eq!(second, fresh.overlays(&c), "{editing:?}: what laying out afresh draws"); + assert!(red_plus(&second) > 0, "{editing:?}: the overflowing frame's out port shows its red plus"); + } +} + +/// After Select All in threaded text, the story's other frames are highlighted without laying them +/// out again on the next frame. +#[test] +fn type_overlays_keep_a_selected_storys_layouts() { + let (mut d, ids) = area_frames(&["Story one ", "story two ", "story three ", "story four"]); + d.text_threads.push(ids.clone()); + let (mut sel, p) = (Selection::default(), paint()); + sel.set([ids[0]]); + let story = json!({ "story": ids.iter().map(|id| id.0).collect::<Vec<_>>() }); + let c = cx(&d, &sel, &p); + let mut tool = TypeTool::new("areaType"); + tool.start_editing(ids[0], 0); + tool.set_option("selectAll", &story); + assert_eq!(tool.story_others(&c).len(), 3); + let highlights = |o: &[Overlay]| o.iter().filter(|o| matches!(o, Overlay::Highlight { color: [60, 120, 255, 90], .. })).count(); + let (first, n) = counted(|| tool.overlays(&c)); + assert!(n > 0); + let (second, n) = counted(|| tool.overlays(&c)); + assert_eq!(n, 0, "the story's other frames are not laid out again"); + assert_eq!(first, second); + let mut fresh = TypeTool::new("areaType"); + fresh.start_editing(ids[0], 0); + fresh.set_option("selectAll", &story); + assert_eq!(second, fresh.overlays(&c), "what laying out afresh draws"); + assert!(highlights(&second) >= 4, "every frame's text is highlighted: {}", highlights(&second)); +} + +/// A kept layout is used only while its frame's text object is unchanged: editing the text, +/// changing the frame and undoing both lay out just the frames that changed, a frame that is no +/// longer drawn is dropped, and choosing another tool drops them all. +#[test] +fn type_overlays_lay_out_again_only_the_frames_that_changed() { + let (mut d, ids) = area_frames(&["One", "Two", "Three", OVERFLOWS]); + let (mut sel, p) = (Selection::default(), paint()); + sel.set(ids.iter().copied()); + let mut tool = TypeTool::new("areaType"); + let fresh = |d: &Document, sel: &Selection| TypeTool::new("areaType").overlays(&cx(d, sel, &p)); + tool.overlays(&cx(&d, &sel, &p)); + let start = d.clone(); + // Edit the text of one frame. + text_mut(&mut d, ids[1]).runs[0].text = OVERFLOWS.into(); + let (o, n) = counted(|| tool.overlays(&cx(&d, &sel, &p))); + assert_eq!(n, 1, "only the edited frame"); + assert_eq!(o, fresh(&d, &sel)); + // Make another frame tall enough for its text. + text_mut(&mut d, ids[3]).kind = area_kind(120.0, 400.0); + let (o, n) = counted(|| tool.overlays(&cx(&d, &sel, &p))); + assert_eq!(n, 1, "only the changed frame"); + assert_eq!(o, fresh(&d, &sel)); + // Undo puts both back. + let (o, n) = counted(|| tool.overlays(&cx(&start, &sel, &p))); + assert_eq!(n, 2, "the two frames undo changed"); + assert_eq!(o, fresh(&start, &sel)); + // A smaller selection keeps only its frames; the others are laid out again when selected again. + let mut one = Selection::default(); + one.set([ids[0]]); + assert_eq!(counted(|| tool.overlays(&cx(&start, &one, &p))).1, 0); + assert_eq!(kept_frames(&tool), 1); + let (o, n) = counted(|| tool.overlays(&cx(&start, &sel, &p))); + assert_eq!(n, 3); + assert_eq!(o, fresh(&start, &sel)); + tool.deactivate(&cx(&start, &sel, &p)); + assert_eq!(kept_frames(&tool), 0, "another tool chosen"); +} + +/// A story of more frames than [`FRAME_LAYOUTS_MAX`] keeps that many layouts, lays the rest out on +/// each call, and draws what laying every frame out afresh draws. +#[test] +fn type_overlays_keep_at_most_frame_layouts_max() { + let texts = vec!["a "; FRAME_LAYOUTS_MAX + 3]; + let (mut d, ids) = area_frames(&texts); + d.text_threads.push(ids.clone()); + let (mut sel, p) = (Selection::default(), paint()); + sel.set([ids[0]]); + let story = json!({ "story": ids.iter().map(|id| id.0).collect::<Vec<_>>() }); + let c = cx(&d, &sel, &p); + let mut tool = TypeTool::new("areaType"); + tool.start_editing(ids[0], 0); + tool.set_option("selectAll", &story); + let first = tool.overlays(&c); + assert_eq!(kept_frames(&tool), FRAME_LAYOUTS_MAX); + let (second, n) = counted(|| tool.overlays(&c)); + assert_eq!(n, 2, "the two other frames past the limit"); + assert_eq!(kept_frames(&tool), FRAME_LAYOUTS_MAX); + assert_eq!(first, second); +} + +#[test] +fn frame_layouts_follow_fonts_and_hyphenation_exceptions() { + // Other tests can load system fonts; this assertion needs its own process-wide database. + #[cfg(not(target_arch = "wasm32"))] + if std::env::var("VECTORCRAFT_FONT_CACHE_TEST_CHILD").as_deref() != Ok("1") { + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "text::tests::frame_layouts_follow_fonts_and_hyphenation_exceptions", "--nocapture", "--test-threads=1"]) + .env("VECTORCRAFT_FONT_CACHE_TEST_CHILD", "1") + .output() + .unwrap(); + let stdout = String::from_utf8_lossy(&output.stdout); + assert!( + output.status.success() && stdout.contains("test result: ok. 1 passed; 0 failed;"), + "isolated font cache test failed:\n{stdout}\n{}", + String::from_utf8_lossy(&output.stderr), + ); + return; + } + let (mut d, ids) = area_frames(&["One", "Two", "Three ", "four"]); + d.text_threads.push(vec![ids[2], ids[3]]); + let (mut sel, p) = (Selection::default(), paint()); + sel.set([ids[0], ids[1], ids[2]]); + let c = cx(&d, &sel, &p); + let mut tool = TypeTool::new("areaType"); + tool.start_editing(ids[2], 0); + tool.set_option("selectAll", &json!({ "story": [ids[2].0, ids[3].0] })); + tool.overlays(&c); + assert_eq!(counted(|| tool.overlays(&c)).1, 0); + // Two selected frames, the story's other frame and the edited one. + let font = vectorcraft_text::test_fonts::variable_font().unwrap(); + assert!(FontDb::global().add_font(font) > 0, "the test font is new to this process"); + assert_eq!(counted(|| tool.overlays(&c)).1, 4, "a font added after the layouts refreshes them"); + assert_eq!(counted(|| tool.overlays(&c)).1, 0); + vectorcraft_text::set_hyphenation_exceptions(&vectorcraft_text::hyphenation_exceptions()); + assert_eq!(counted(|| tool.overlays(&c)).1, 4, "new hyphenation exceptions refresh them"); +} + +/// Times the Type tool's overlays on 200 selected area type frames of about 400 characters, one of +/// them edited, and on a 5-frame story after Select All, laying every frame out on each call as the +/// tool did before it kept their layouts (base) against keeping them (kept). Run with +/// `cargo test --release -p vectorcraft-tools --lib type_overlays_timing -- --ignored --nocapture`. +#[test] +#[ignore = "timing, run by hand"] +fn type_overlays_timing() { + use std::time::Instant; + let words = "The quick brown fox jumps over the lazy dog while seven wizards box. ".repeat(6); + let texts: Vec<String> = (0..200).map(|i| format!("{i} {words}")).collect(); + let (mut d, ids) = area_frames(&texts.iter().map(String::as_str).collect::<Vec<_>>()); + for id in &ids { + text_mut(&mut d, *id).kind = area_kind(200.0, 200.0); + } + let story: Vec<NodeId> = ids[..5].to_vec(); + d.text_threads.push(story.clone()); + let p = paint(); + let mut all = Selection::default(); + all.set(ids.iter().copied()); + let mut first = Selection::default(); + first.set([ids[0]]); + // Before, the selected frames' layouts replaced the edited one's single kept layout; with only + // the edited frame selected, it stayed. + let cases = [("200 selected frames, one edited", &all, None, true), ("5-frame story, Select All", &first, Some(story), false)]; + for (name, sel, story, evicted) in cases { + let c = cx(&d, sel, &p); + let mut tool = TypeTool::new("areaType"); + tool.start_editing(ids[0], 0); + if let Some(s) = &story { + tool.set_option("selectAll", &json!({ "story": s.iter().map(|id| id.0).collect::<Vec<_>>() })); + } + let expected = tool.overlays(&c); + tool.frames.lock().unwrap().clear(); + if evicted { + *tool.cache.lock().unwrap() = None; + } + let (_, before) = counted(|| tool.overlays(&c)); + let (_, after) = counted(|| tool.overlays(&c)); + println!("{name}: {before} layouts per call before, {after} after"); + let calls = 20; + let (mut base, mut kept) = (Vec::new(), Vec::new()); + for _ in 0..7 { + let start = Instant::now(); + for _ in 0..calls { + // Before: the other frames were laid out on every call. + tool.frames.lock().unwrap().clear(); + if evicted { + *tool.cache.lock().unwrap() = None; + } + assert_eq!(tool.overlays(&c), expected); + } + base.push(start.elapsed().as_secs_f64() * 1000.0 / f64::from(calls)); + let start = Instant::now(); + for _ in 0..calls { + assert_eq!(tool.overlays(&c), expected); + } + kept.push(start.elapsed().as_secs_f64() * 1000.0 / f64::from(calls)); + } + let median = |v: &mut Vec<f64>| { + v.sort_by(f64::total_cmp); + v[v.len() / 2] + }; + println!("{name}: base runs {base:.3?} ms per call, kept runs {kept:.3?} ms per call"); + println!("{name}: median base {:.3} ms, kept {:.3} ms per call", median(&mut base), median(&mut kept)); + } } /// Type on a path has its in port just before its start bracket and its out port just past its diff --git a/crates/tools/src/text/tool.rs b/crates/tools/src/text/tool.rs index e18754f0ca..6ed7374eba 100644 --- a/crates/tools/src/text/tool.rs +++ b/crates/tools/src/text/tool.rs @@ -472,6 +472,7 @@ impl Tool for TypeTool { } fn deactivate(&mut self, cx: &ToolContext) -> Vec<Action> { self.prev_tool = None; + self.frames.get_mut().unwrap_or_else(|e| e.into_inner()).clear(); self.finish(cx) } /// Editing ends when a command takes the text out of the selection (Deselect, another object @@ -633,13 +634,17 @@ impl Tool for TypeTool { o.push(Overlay::Measure { p: d, text: cx.size_label(size.width, size.height) }); } } + // The other frames this call draws keep their layouts for the next call; the rest are dropped. + let fonts = vectorcraft_text::layout_inputs(); + let mut now = self.frames.lock().unwrap_or_else(|e| e.into_inner()); + let mut was = std::mem::take(&mut *now); // The ports of selected area type and type on a path, as many as show ([`PORTS_MAX`]), the // edited one's included. let shown = ports_shown(cx.doc, &cx.selection.objects); if shown { for id in cx.selection.objects.iter().filter(|id| Some(**id) != self.editing) { if let Some(t) = ported(cx.doc, *id) { - let lay = self.layout(t); + let lay = Self::frame_layout(&mut now, &mut was, fonts, *id, t); ports(cx, *id, t, lay.overflow, &mut o); } } @@ -688,7 +693,7 @@ impl Tool for TypeTool { if self.preedit.is_none() { for f in self.story_others(cx) { let Some(other) = Self::text(cx, f) else { continue }; - let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), other); + let lay = Self::frame_layout(&mut now, &mut was, fonts, f, other); for q in vectorcraft_text::selection_quads(&lay, 0, edit::runs_len(&other.runs)) { o.push(Overlay::Highlight { quad: q.map(|p| other.xf * p), color: [60, 120, 255, 90] }); } diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index ef83de54ad..c68f20a6af 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2196,6 +2196,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur A subpath keeps its anchors in chunks of up to 256 anchors, and the versions of a path share the chunks they have not changed. Editing one anchor copies only the chunk that holds it, so its undo step keeps that chunk instead of a copy of every anchor; adding or deleting an anchor copies the chunk it is in and rebuilds the subpath's table of chunks. When the renderer looks for the anchors that moved, it compares only the chunks the edit copied. Moving one anchor of a selected open path of 10,000 or 200,000 anchors (`path.moveAnchor`, `path.setHandle`, `path.moveAnchors` or a nudge) keeps at most 48 KiB in the undo step and in the redo step, where it kept a copy of every anchor at 56 bytes each (counted in the engine's tests). Files are written and read as before, each subpath's anchors as one list. Opening a document keeps the layouts it makes for its type objects, up to 128 MiB, and the first frame uses them instead of laying those objects out again. It does not keep a layout with bitmap or color glyphs or a text object with a gradient. The frame uses a layout only for a text object equal to the one laid out, and only while the fonts and the hyphenation exceptions have not changed. It uses each layout once. The renderer drops the rest when a frame that used one ends, and all of them after eight frames that use none. The frames of a threaded story are laid out while the file is read, and the first frame lays them out again. The pixels are the same. On Windows at 1600 × 1200, in medians of seven interleaved rounds of a local example, counted in the main thread's CPU cycles because other builds were running: with 5,000 point type objects in view the first frame takes 409 million cycles instead of 894 million and the open 816 million instead of 665 million, so the two together take 1,225 million instead of 1,559 million; with one area type object of 500 paragraphs the first frame takes 697 million instead of 1,193 million and the open 535 million instead of 568 million. Type › Show Hidden Characters keeps the marks it places on each text object from one frame to the next. The canvas lays a text object out again when an edit changes it or its threaded story, or when the last frame that showed the marks did not draw it, and it lays out all type in view again when the fonts or the hyphenation exceptions change. With 1,000 two-line labels in view, drawing the marks takes 0.8 ms per frame in a release build instead of 19.7 ms. + With a Type tool active, the in and out ports of the selected area type and type on a path, and the highlight of a selected story's other frames after Select All, use each frame's layout from the last frame instead of laying the frame out again. A frame is laid out again when its text object changes, or when the fonts or the hyphenation exceptions change. With 200 selected area type frames of about 400 characters, one of them being edited, the Type tool's overlays take 0.27 ms per frame instead of 121 ms; with a 5-frame story selected they take 0.016 ms instead of 2.0 ms (release build on Linux, medians of seven runs, measured while other builds were running). A selection with more than 100,000 points to outline shows its bounds instead of each object's outline and anchors. Paths count their anchors. Area type and type on a path count the anchors of their frame or path, and point type counts six: its box's corners and the ends of its baseline marker. Images, symbol instances, placed documents, and area type or type on a path in perspective count the four corners of their box, and gradient meshes and envelopes count their points and the ends of their mesh lines. The hover highlight leaves out an object past that count, and such an object shows its bounds as the key object. With 32,768 type objects, images, symbol instances, gradient meshes or envelopes selected, the selection's outlines and anchors add fewer than 100 vertices to the canvas's mesh (#2460). The canvas keeps the selected objects' outlines, anchors and handles from one frame to the next as one mesh. It builds an object's marks again when the object, its layer color or its selected anchors change. A pan moves the kept outlines and handles and places the anchor squares again. Each subpath and handle gets its triangles the first time it is in view. A frame with a new zoom or rotation draws the marks one shape at a time and keeps nothing, and the next frame at that view builds them. The pixels are the same, apart from two small differences: a kept outline's corner of exactly 90 degrees in a rotated view can keep its miter or cut corner after a pan, and kept vertices can move by rounding errors. On Windows at 1440 × 900, in a release build, with 2,000 selected circles of 50 anchors each in 10 fill colors, an idle frame takes 12.8 ms instead of 59.9 ms with the Selection tool and 29.8 ms instead of 192.1 ms with Direct Selection (medians of five runs). A frame during a zoom takes about what it did: 86.7 ms instead of 80.0 ms with the Selection tool. Delete, Cut, Group, Ungroup, Make and Release Compound Path, Make Clipping Mask, Send to Current Layer, Duplicate, Copy in the Move, Rotate, Scale, Reflect and Shear dialogs, Transform Each with Copy and each move of an Alt-drag take time in proportion to the size of the document (#1429). From 18066332748e9aae4617b15c4acbf99ed04b0545 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 17 Nov 2026 12:55:26 -0800 Subject: [PATCH 130/176] Control bar: X, Y, W and H use the Transform panel's reference point The inline X and Y fields showed the center of the selection's box and every edit sent reference point 4, whatever point the Transform panel's locator had chosen. They now show the shared reference point (or, with Use Registration Point for Symbol, the symbol instance's registration point), a new X or Y moves that point, and a new W or H keeps it in place, as the Transform panel and the Properties panel's Transform section do. The edits also follow the Transform panel menu's Transform Object Only, Transform Pattern Only and Transform Both. --- crates/ui-egui/src/chrome/control_bar.rs | 69 ++++++++++++-------- crates/ui-egui/src/panels/transform/tests.rs | 56 ++++++++++++++-- docs/target-app-parity.md | 3 +- 3 files changed, 92 insertions(+), 36 deletions(-) diff --git a/crates/ui-egui/src/chrome/control_bar.rs b/crates/ui-egui/src/chrome/control_bar.rs index 71b737dbfc..ff7d58dfec 100644 --- a/crates/ui-egui/src/chrome/control_bar.rs +++ b/crates/ui-egui/src/chrome/control_bar.rs @@ -203,6 +203,46 @@ fn inline_transform_width(ui: &Ui, t: &Tokens) -> f32 { labels + fields + crate::panels::transform::CONSTRAIN_LINK_SIZE + ui.spacing().item_spacing.x * items as f32 } +/// The Control bar's inline X/Y/W/H fields for the selection's box `b`, rotated with rotated +/// objects: X/Y are its reference point on the page (or a symbol instance's registration point), +/// shared with the Transform panel, and W/H its own sides. Edits keep or move that point, and the +/// Transform panel's menu choice of objects, patterns or both applies to them. +fn inline_transform_fields(app: &mut VectorcraftApp, ui: &mut Ui, t: &Tokens, units: vectorcraft_doc::Unit, b: &vectorcraft_doc::OrientedBox) { + let reference = crate::panels::transform::panel_reference(app, ui, b); + let (refi, rp) = (reference.index, reference.point); + let origin = app.ruler_origin(); + let link = crate::panels::transform::proportional(app, ui); + let copy = crate::panels::transform::alt_enter_copies(app, ui); + let values = [(rp.x, origin.x), (rp.y, origin.y), (b.rect.width(), 0.0), (b.rect.height(), 0.0)]; + // The W/H link sits between W and H, but is made after H so Tab goes from W + // straight to H and finds the link after it. + let mut link_room = None; + for ((k, lbl), (v, offset)) in INLINE_FIELDS.into_iter().zip(values) { + if k == "height" { + link_room = Some(crate::panels::transform::constrain_link_room(ui)); + } + widgets::field_label(ui, inline_label(t, lbl)); + let (id, shown) = (("cb", k), Some(v - offset)); + let set = if matches!(k, "width" | "height") { + widgets::size_field(ui, id, shown, units, INLINE_FIELD_WIDTH) + } else { + widgets::num_field(ui, id, shown, units, INLINE_FIELD_WIDTH) + }; + if let Some(nv) = set { + let params = match k { + "x" => json!({"x": reference.bounds_xy(nv + offset, 0.0).0, "reference": refi, "copy": copy}), + "y" => json!({"y": reference.bounds_xy(0.0, nv + offset).1, "reference": refi, "copy": copy}), + _ => json!({k: nv, "reference": refi, "proportional": link, "copy": copy}), + }; + crate::panels::transform::run_transform(app, "object.setBounds", params); + } + } + if let Some(room) = link_room { + let id = ui.scope_id().with("cb-constrain-link"); + crate::panels::transform::constrain_link_at(app, ui, ui.interact(room, id, Sense::click())); + } +} + /// The size of the Control bar's Align, Distribute and area type vertical alignment buttons, and /// the height of its Align To menu. const BUTTON: f32 = 24.0; @@ -1036,38 +1076,11 @@ fn contents(app: &mut VectorcraftApp, ui: &mut Ui, t: &Tokens, bar: egui::Rect, return; } crate::panels::transform::link(app, ui); - // The bounding box, rotated with rotated objects: its centre and its own sides. let selection_box = app.selection_box(); if selection_box.is_some() && ui.available_width() < inline_transform_width(ui, t) { left_out(ui); } else if let Some(b) = selection_box { - let c = b.center(); - let origin = app.ruler_origin(); - let link = crate::panels::transform::proportional(app, ui); - let copy = crate::panels::transform::alt_enter_copies(app, ui); - let values = [(c.x, origin.x), (c.y, origin.y), (b.rect.width(), 0.0), (b.rect.height(), 0.0)]; - // The W/H link sits between W and H, but is made after H so Tab goes from W - // straight to H and finds the link after it. - let mut link_room = None; - for ((k, lbl), (v, offset)) in INLINE_FIELDS.into_iter().zip(values) { - if k == "height" { - link_room = Some(crate::panels::transform::constrain_link_room(ui)); - } - widgets::field_label(ui, inline_label(t, lbl)); - let (id, shown) = (("cb", k), Some(v - offset)); - let set = if matches!(k, "width" | "height") { - widgets::size_field(ui, id, shown, units, INLINE_FIELD_WIDTH) - } else { - widgets::num_field(ui, id, shown, units, INLINE_FIELD_WIDTH) - }; - if let Some(nv) = set { - app.run("object.setBounds", json!({k: nv + offset, "reference": 4, "proportional": link, "copy": copy})).ok(); - } - } - if let Some(room) = link_room { - let id = ui.scope_id().with("cb-constrain-link"); - crate::panels::transform::constrain_link_at(app, ui, ui.interact(room, id, Sense::click())); - } + inline_transform_fields(app, ui, t, units, &b); } // Select Similar Objects comes last: it takes only the room every control ahead of it left. trailing_select_similar(app, ui); diff --git a/crates/ui-egui/src/panels/transform/tests.rs b/crates/ui-egui/src/panels/transform/tests.rs index 3dff8e6a4b..6844210599 100644 --- a/crates/ui-egui/src/panels/transform/tests.rs +++ b/crates/ui-egui/src/panels/transform/tests.rs @@ -233,8 +233,9 @@ fn type_into(ctx: &egui::Context, app: &mut VectorcraftApp, draw: fn(&mut Vector } /// The panel menu's Transform Object Only, Transform Pattern Only and Transform Both, one -/// checked: a new X typed in the panel (or the Properties panel's Transform section) moves the -/// pattern-filled rectangle and leaves its tiles, moves its tiles alone, or moves both. Until +/// checked: a new X typed in the panel (or the Properties panel's Transform section, or the +/// Control bar) moves the pattern-filled rectangle and leaves its tiles, moves its tiles alone, or +/// moves both. Until /// one is chosen the panels do as General › Transform Pattern Tiles says, as they did before /// the menu acted, and the menu checks Transform Both while it is on, Transform Object Only /// while it is off; a choice overrides it, and resetting the preferences returns to it. @@ -248,7 +249,7 @@ fn the_menu_chooses_whether_the_object_its_pattern_or_both_transform() { let labels = ["Transform Object Only", "Transform Pattern Only", "Transform Both"]; let modes = ["object", "pattern", "both"]; let checked = |shown: &[String]| -> Vec<usize> { (0..3).filter(|i| shown.contains(&format!("✓ {}", labels[*i]))).collect() }; - for draw in [show as fn(&mut VectorcraftApp, &mut Ui), crate::panels::properties::transform_section] { + for draw in [show as fn(&mut VectorcraftApp, &mut Ui), crate::panels::properties::transform_section, crate::chrome::control_bar] { for general in [false, true] { for pick in [None, Some(0), Some(1), Some(2)] { let case = format!("General › Transform Pattern Tiles {general}, menu choice {pick:?}"); @@ -333,12 +334,12 @@ fn the_menu_choice_also_applies_to_rotation_and_shear() { } } -/// Use Registration Point for Symbol: with one symbol instance selected, the panel and the -/// Properties panel's Transform section show and set X and Y at its symbol's registration point -/// (here the top-left one) instead of the reference point (the centre). +/// Use Registration Point for Symbol: with one symbol instance selected, the panel, the +/// Properties panel's Transform section and the Control bar show and set X and Y at its symbol's +/// registration point (here the top-left one) instead of the reference point (the center). #[test] fn use_registration_point_for_symbol_measures_an_instance_from_its_registration_point() { - for draw in [show as fn(&mut VectorcraftApp, &mut Ui), crate::panels::properties::transform_section] { + for draw in [show as fn(&mut VectorcraftApp, &mut Ui), crate::panels::properties::transform_section, crate::chrome::control_bar] { let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); app.run("file.new", json!({"width": 300, "height": 300})).unwrap(); app.run("shape.rectangle", json!({"x": 100, "y": 50, "width": 80, "height": 40})).unwrap(); @@ -366,6 +367,47 @@ fn use_registration_point_for_symbol_measures_an_instance_from_its_registration_ } } +/// The Control bar's X, Y, W and H use the reference point the Transform panel's locator chose: +/// X and Y show that point of the selection's box and a new X or Y moves it there, a new W or H +/// keeps it in place, and choosing another point changes what the fields show without editing the +/// art. Each field edit is one undo step. +#[test] +fn the_control_bar_fields_use_the_shared_reference_point() { + use crate::panels::tests_appearance::frame_events; + let draw = crate::chrome::control_bar as fn(&mut VectorcraftApp, &mut Ui); + // The reference point (top-left, center, bottom-right): X/Y shown for the rectangle at + // (10, 20), 100 × 50; the box after X becomes `x`, and after W becomes 200 and H 100. + let cases = [ + (0usize, ("10 pt", "20 pt"), "30", Rect::new(30.0, 20.0, 130.0, 70.0), Rect::new(30.0, 20.0, 230.0, 120.0)), + (4, ("60 pt", "45 pt"), "80", Rect::new(30.0, 20.0, 130.0, 70.0), Rect::new(-20.0, -5.0, 180.0, 95.0)), + (8, ("110 pt", "70 pt"), "130", Rect::new(30.0, 20.0, 130.0, 70.0), Rect::new(-70.0, -30.0, 130.0, 70.0)), + ]; + for (refi, (x, y), new_x, moved, sized) in cases { + let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 20, "width": 100, "height": 50})).unwrap(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let revision = |app: &VectorcraftApp| app.session.active().unwrap().revision; + let shown = |app: &mut VectorcraftApp| frame_events(&ctx, app, vec![], draw).into_iter().map(|(t, _)| t).collect::<Vec<_>>(); + shown(&mut app); + let before = revision(&app); + ctx.data_mut(|d| d.insert_temp(egui::Id::unique("refpt"), refi)); + let texts = shown(&mut app); + assert!(texts.iter().any(|t| t == x) && texts.iter().any(|t| t == y), "reference {refi}: X {x}, Y {y} in {texts:?}"); + assert_eq!(revision(&app), before, "reference {refi}: choosing the point leaves the art"); + type_into(&ctx, &mut app, draw, x, new_x); + assert_eq!(app.selection_box().unwrap().rect, moved, "reference {refi}: X"); + assert_eq!(revision(&app), before + 1, "reference {refi}: one undo step"); + type_into(&ctx, &mut app, draw, "100 pt", "200"); + type_into(&ctx, &mut app, draw, "50 pt", "100"); + assert_eq!(app.selection_box().unwrap().rect, sized, "reference {refi}: W and H"); + app.run("edit.undo", json!({})).unwrap(); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(app.selection_box().unwrap().rect, moved, "reference {refi}: undo"); + } +} + /// Use Registration Point for Symbol on a reflected, a rotated and a sheared symbol instance: /// the panel and the Properties panel's Transform section show X and Y at the registration /// point where the instance's transform put it (not at the box's point of the same index), a diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index ef83de54ad..04b25c70eb 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1045,7 +1045,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - The History panel menu has Step Backward and Step Forward, which run Edit › Undo and Edit › Redo and are disabled when there is no step to undo or redo, and Set History Limit…, which opens Preferences at Performance, where History States is set. - The History panel menu's Clear History (`edit.clearHistory`) removes every step to undo and to redo and leaves the document as it is; it is not an undo step itself, and it is disabled when there is no step to clear. - The New Document from State button at the bottom of the History panel (`edit.newDocumentFromState`) makes a new document, which becomes active, from the state the panel has selected ([public source](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/undo-edits-and-manage-design-history.html)). VectorCraft's own rules: the new document takes the next Untitled-N name, is marked unsaved, has nothing selected and has no steps to undo or redo, and the source document and its steps stay as they are. - - The Transform panel menu's Transform Object Only, Transform Pattern Only and Transform Both (`transformPanelPatterns`) choose whether the fields, flips and menu flips of the Transform panel and the Properties panel's Transform section move the object and leave its pattern tiles, move the tiles alone, or both (until a choice they follow General › Transform Pattern Tiles, as before); Use Registration Point for Symbol (`useRegistrationPointForSymbol`) measures and transforms one selected symbol instance from its symbol's registration point, where the instance's flips, rotations and shears put it ([Transform panel overview](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/transform-panel-overview.html); `panels::transform::tests::the_menu_chooses_whether_the_object_its_pattern_or_both_transform`, `use_registration_point_for_symbol_measures_an_instance_from_its_registration_point`, `use_registration_point_for_symbol_follows_a_transformed_instance`, `tests_prefs::transform_panel_patterns_defaults_to_following_the_general_preference`). + - The Transform panel menu's Transform Object Only, Transform Pattern Only and Transform Both (`transformPanelPatterns`) choose whether the fields, flips and menu flips of the Transform panel and the Properties panel's Transform section, and the Control bar's inline X, Y, W and H, move the object and leave its pattern tiles, move the tiles alone, or both (until a choice they follow General › Transform Pattern Tiles, as before); Use Registration Point for Symbol (`useRegistrationPointForSymbol`) measures and transforms one selected symbol instance from its symbol's registration point, where the instance's flips, rotations and shears put it ([Transform panel overview](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/transform-panel-overview.html); `panels::transform::tests::the_menu_chooses_whether_the_object_its_pattern_or_both_transform`, `use_registration_point_for_symbol_measures_an_instance_from_its_registration_point`, `use_registration_point_for_symbol_follows_a_transformed_instance`, `tests_prefs::transform_panel_patterns_defaults_to_following_the_general_preference`). - The Transform panel's Align to Pixel Grid checkbox (`object.setPixelAligned`) gives paths and compound paths a pixel-aligned property, saved in the native file: their horizontal and vertical straight segments sit on whole points (half points under an odd centered stroke) with whole stroke weights, and every move, scale, rotation, reflection, Transform Each, Align move, Transform panel change, move of direct-selected anchors or of one anchor, move of a compound path's path on its own, artboard move, resize or copy that carries the art, Duplicate or paste that moves a copy, stroke edit and appearance edit that adds, removes, hides, repaints or reweighs a stroke snaps them again, while diagonal segments and curves keep their shape; a compound path made from an aligned path or compound path is aligned and snaps its paths with its own stroke; the box shows a dash for a mixed selection and is unavailable for type, images and groups ([Pixel-aligned property](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/pixel-preview-mode-for-web-graphics.html); `tests::pixelalign::turning_it_on_snaps_the_path_in_one_undo_step`, `it_stays_aligned_through_transforms`, `it_stays_aligned_when_its_artboard_moves`, `diagonal_segments_and_curves_keep_their_shape`, `type_and_images_cannot_be_aligned`, `the_property_is_saved_and_read_back`, `stroke_edits_keep_it_aligned`, `a_compound_path_of_aligned_paths_is_aligned`, `a_compound_path_of_an_aligned_compound_path_is_aligned`, `a_stroke_without_paint_snaps_to_whole_points`, `moving_direct_selected_anchors_keeps_it_aligned`, `moving_one_anchor_keeps_it_aligned`, `moving_a_path_of_an_aligned_compound_path_keeps_it_aligned`, `artboard_options_and_artboard_copies_keep_it_aligned`, `appearance_edits_keep_it_aligned`, `placed_gradients_follow_the_snapped_path`, `duplicates_and_pastes_keep_it_aligned`, `paths_added_to_or_moved_in_an_aligned_compound_path_keep_it_aligned`, `the_art_of_a_linked_opacity_mask_keeps_it_aligned`, `a_linked_opacity_mask_follows_a_snap`, `aligning_direct_selected_anchors_keeps_it_aligned`, `global_edit_keeps_its_members_aligned`, `a_path_with_live_corners_snaps_its_inner_edges`, `geometry_edits_keep_it_aligned`, `other_path_edits_keep_it_aligned`, `panels::transform::tests::align_to_pixel_grid_shows_and_sets_the_property`). - Align New Objects to Pixel Grid (`document.setup {alignNewObjectsToPixelGrid}`, a checkbox in New Document's Advanced Options and a checked item in the Transform panel menu) gives every path and compound path drawn in the document, the paths of a new grid or flare included, the pixel-aligned property, snapped in the step that draws it; it is on in the Mobile and Web presets and off in the others, saved presets and Recent keep it, and the document saves it. Type, images and groups do not take it, and art already in the document, pasted, duplicated or placed keeps its own property (VectorCraft's own rules) ([Pixel-aligned property](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/pixel-preview-mode-for-web-graphics.html); `tests::pixelalign::align_new_objects_makes_new_paths_pixel_aligned`, `align_new_objects_reaches_grids_flares_and_add_on_shapes`, `align_new_objects_is_saved_and_read_back`, `tests::newdoc::align_new_objects_to_pixel_grid_follows_the_preset`, `panels::transform::tests::align_new_objects_menu_item_toggles_the_active_document`, `dialogs::new_document::tests::align_new_objects_checkbox_follows_the_preset_and_reaches_the_document`). - The Transform panel works out its Align to Pixel Grid checkbox once for each document revision and reuses it on later frames, and lists the selected objects' ids only when the box is clicked. The box shows the same state. With Select All of 99,500 objects (100,000 paths, 1,000 of them in 500 compound paths), working the state out on every frame took a median 33.5 ms of thread CPU time per frame in a release build on a loaded machine; the first frame after a change now takes 31.5 ms and later frames take about 1 ns (`panels::transform::tests::align_to_pixel_grid_kept_state_equals_a_full_measure`, `align_to_pixel_grid_state_is_measured_once_per_revision`, `pixel_aligned_state_timing`). @@ -1144,6 +1144,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Scrubby labels (#400, beyond Illustrator, as in Photoshop): dragging a numeric field's label left or right (the ↔ cursor shows over it) steps the value one unit every 2 points (Shift: ten, Ctrl/Cmd: a tenth; counts stay whole), in the field's unit and within its limits, applied live as the art follows; the whole drag is one undo step and Escape puts the value back. A click on the label focuses the field; the text box itself never scrubs, and a field with no label doesn't. Text labels before a field (Transform, Properties, Control bar, Stroke, Transparency, form rows in dialogs) and the Character and Paragraph panels' icons act as labels, and so do the links that label a field (the Control bar's Stroke: and Opacity:, the Properties panel's Stroke), which a click still follows to their panel (#4088). Preferences › General › Scrub Numeric Fields by Dragging (on by default) turns it off. - In the Transform panel, the Properties panel's Transform section and the Control bar, Alt+Enter (Option+Return) applies a value to a copy of the selection and selects the copy, in one undo step. With anchor points selected with Direct Selection it applies the value to them, as Enter does. Ctrl/Cmd+Enter in W or H applies the value and scales the selection proportionally with the link off. With the Artboard tool, it scales the active artboard proportionally. A percentage typed alone in W or H (`50%`) is that share of the size the field shows, and the link and Ctrl/Cmd+Enter keep the proportions as with a length (#2401). - The Control bar's underlined Transform link opens the Transform panel in a popover under it (reference point, X/Y/W/H, Rotate and Shear with their icons and angle presets, flips, shape properties, Scale Corners and Scale Strokes & Effects), as its Stroke link does the Stroke panel; X/Y/W/H also show inline while the bar has room. The reference point locator is nine squares, the outer eight joined around the box. As VectorCraft's own keyboard rule, the locator is one tab stop in the Control bar popover, the Transform panel, the Properties panel and the dialogs, the Arrange Tools dialogs included. While it has the focus it shows an outline, and ←, →, ↑ and ↓ move the reference point one square, stopping at the edges (`the_reference_point_grid_is_one_tab_stop`, `arrow_keys_move_the_reference_point`, `the_reference_point_locator_is_one_tab_stop_and_arrows_move_it`). + - The Control bar's inline X and Y show the point of the selection's box that the Transform panel's locator chose, counted from the ruler origin, and a new X or Y moves that point there; a new W or H resizes the selection about it. The help page (<https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=333>) describes typing X and Y in the Transform panel or the Control panel after choosing the point on the locator. Use Registration Point for Symbol applies to the inline fields as it does to the panel's. Choosing another point changes only what the fields show; each field edit is one undo step (`panels::transform::tests::the_control_bar_fields_use_the_shared_reference_point`). - In isolation mode the Control bar has an Exit Isolation Mode button (`object.exitIsolation`), except while a pattern is edited. Outside isolation mode, with one group, compound path, path, image, mesh or placed file selected, it has an Isolate Selected Object button (`object.isolate`), which also isolates a path inside a group that Direct Selection selected. - The canvas context menu has Isolate Selected Path (`object.isolate`) when the selection is one path, a path selected inside a group or a compound path included, as the [help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=324) lists it beside Isolate Selected Group. As VectorCraft's own rule, neither item shows for two or more objects, or for an object `object.isolate` refuses: a hidden or locked object, one in a hidden or locked group or layer, a guide while Lock Guides is on, and, while a symbol is edited, an object outside the symbol's art (`single_path_context_item_enters_isolation`, `isolation_context_item_follows_selected_kind`, `isolation_context_item_skips_objects_that_cannot_be_isolated`). - While an opacity mask is edited, Exit Isolation Mode (Esc, the isolation bar's back arrow, the Control bar's button, and the Layers panel menu's and canvas context menu's Exit Isolation Mode) leaves mask editing as Stop Editing Opacity Mask does, in one undo step: the mask keeps the edits, and the masked object is selected. While a pattern is edited, the Exit Isolation Mode item of the Layers panel menu and of the canvas context menu saves the pattern and leaves pattern editing, as Done does. From 1483e61f858c8294819c4c2acfe45a82f4013a84 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 17 Nov 2026 12:53:58 -0800 Subject: [PATCH 131/176] Swatches: Swatch Options and New Swatch show the out-of-gamut and web color warnings Both dialogs now show the out-of-gamut triangle and the out-of-web-color cube under the color, each with its correction beside it. A click on the icon or on the correction changes the dialog's color; OK applies it as one swatch.edit or swatch.new undo step. The warning icons in the Color panel and the Color Picker now correct the color too. The triangle shows in RGB, HSB and Lab and the cube in every mode but Web Safe RGB. A web correction of a Grayscale, Lab or CMYK color is edited in RGB; a gamut correction keeps the color's CMYK equivalent and is edited in CMYK. --- .../ui-egui/src/dialogs/color_picker/tests.rs | 3 +- crates/ui-egui/src/dialogs/new_swatch.rs | 30 ++- crates/ui-egui/src/dialogs/swatch_options.rs | 213 ++++++++++++++++-- crates/ui-egui/src/panels/color.rs | 20 +- docs/control-protocol.md | 5 +- docs/mcp.md | 4 +- docs/target-app-parity.md | 1 + 7 files changed, 246 insertions(+), 30 deletions(-) diff --git a/crates/ui-egui/src/dialogs/color_picker/tests.rs b/crates/ui-egui/src/dialogs/color_picker/tests.rs index 0786df7ca9..15344a131c 100644 --- a/crates/ui-egui/src/dialogs/color_picker/tests.rs +++ b/crates/ui-egui/src/dialogs/color_picker/tests.rs @@ -670,7 +670,8 @@ fn warnings_fit_below_the_preview_without_widening_the_dialog() { } let after = ctx.memory(|m| m.area_rect(id)).unwrap(); assert!((before.size() - after.size()).length() < 1.0, "{before:?} vs {after:?}"); - click_at(&ctx, &mut app, warnings[1].center()); + // The cube icon left of the web correction corrects the color too. + click_at(&ctx, &mut app, warnings[1].center() - vec2(19.0, 0.0)); assert!(is_web_safe(&picked(app.ui.dialog.as_ref().unwrap()).color), "web correction remains clickable"); } diff --git a/crates/ui-egui/src/dialogs/new_swatch.rs b/crates/ui-egui/src/dialogs/new_swatch.rs index 5b6c5b117c..ec2ab707d4 100644 --- a/crates/ui-egui/src/dialogs/new_swatch.rs +++ b/crates/ui-egui/src/dialogs/new_swatch.rs @@ -1,5 +1,5 @@ -//! New Swatch: the Swatch Options fields (name, colour type, Global, mode, sliders and hex) -//! prefilled from the active fill or stroke; a gradient, a pattern or a tint of a global colour +//! New Swatch: the Swatch Options fields (name, colour type, Global, mode, sliders, hex and the +//! colour warnings) prefilled from the active fill or stroke; a gradient, a pattern or a tint of a global colour //! (saved as a tint swatch, "Name 40%") only takes a name. OK runs `swatch.new`. //! //! Fields: `name`, `spot`, `global`, `mode` and `color` as in Swatch Options, `group` (the colour @@ -45,7 +45,7 @@ pub fn open(app: &mut VectorcraftApp, spot: bool, global: bool, group: Option<&s fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { if d.fields.contains_key("__paint") { grid(ui, |ui| name_row(ui, d)); - } else if editor(ui, d) + } else if editor(app, ui, d) && d.str("name") == d.str("__auto") && let Some(st) = app.session.active() { @@ -87,6 +87,30 @@ mod tests { assert_eq!(params(&d), json!({"name": "Dots", "pattern": "Dots"})); } + #[test] + fn a_warning_corrects_the_new_colour_only_until_ok() { + use super::super::swatch_options::tests::{click_at, context, settled, warning_rows}; + let (ctx, mut app) = (context(), VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default())); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap(); + app.run("paint.setFill", json!({"color": "#0000fe"})).unwrap(); + let count = |app: &VectorcraftApp| app.session.active().unwrap().doc.swatches_iter().count(); + let before = count(&app); + open(&mut app, false, false, None).unwrap(); + let rows = warning_rows(&settled(&ctx, &mut app)); + assert_eq!(rows.len(), 2, "out of gamut and out of web colors"); + click_at(&ctx, &mut app, rows[1].1.center()); + let d = app.ui.dialog.clone().unwrap(); + assert_eq!((color_of(&d).to_hex(), d.str("mode")), ("#0000ff".to_string(), "rgb".to_string())); + assert_eq!(count(&app), before, "no swatch before OK"); + assert_eq!(warning_rows(&settled(&ctx, &mut app)).len(), 1, "the web warning is gone"); + let name = app.ui.dialog.as_ref().unwrap().str("name"); + super::super::confirm(&mut app).unwrap(); + assert_eq!(app.session.active().unwrap().doc.swatch(&name).and_then(|s| s.paint.color()).map(|c| c.to_hex()), Some("#0000ff".into())); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(count(&app), before, "one undo step"); + } + #[test] fn a_tint_opens_as_a_named_tint_swatch() { let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default()); diff --git a/crates/ui-egui/src/dialogs/swatch_options.rs b/crates/ui-egui/src/dialogs/swatch_options.rs index 9583b893ef..4ff5cdc1ba 100644 --- a/crates/ui-egui/src/dialogs/swatch_options.rs +++ b/crates/ui-egui/src/dialogs/swatch_options.rs @@ -1,7 +1,10 @@ //! Swatch Options: name, colour type (process or spot), Global, colour mode with sliders and hex, -//! previewed live on the canvas (Cancel rolls the preview back). Double-clicking a swatch opens it -//! for a solid colour; for a gradient it shows the name and the gradient; patterns open pattern -//! editing ([`open`]). +//! and the out-of-gamut and out-of-web-color warnings under the colour, previewed live on the canvas +//! (Cancel rolls the preview back). A click on a warning's icon or colour corrects the colour +//! (https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf, +//! Swatch options; https://helpx.adobe.com/illustrator/using/adjusting-colors.html). +//! Double-clicking a swatch opens it for a solid colour; for a gradient it shows the name and the +//! gradient; patterns open pattern editing ([`open`]). //! //! Fields: `__swatch` (the swatch being edited), `name`, `spot`, `global`, `mode` (`gray`, `rgb`, //! `hsb`, `lab`, `cmyk` or `web`), `color` (`"#rrggbb"` or a colour object such as @@ -14,7 +17,9 @@ use vectorcraft_color::{Color, Paint}; use super::{DialogSpec, form, run_and_close}; use crate::VectorcraftApp; -use crate::panels::color::{Mode, components, from_components, parse_hex, track_color, web_safe}; +use crate::panels::color::{ + GAMUT_WARNING, Mode, WEB_WARNING, components, from_components, gamut_fix, is_web_safe, parse_hex, track_color, warning_chip, web_safe, +}; use crate::state::Dialog; use crate::theme::Tokens; use crate::widgets; @@ -113,7 +118,7 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { widgets::gradient_chip(ui, r, &g); changed } - None => editor(ui, d), + None => editor(app, ui, d), }; ui.add_space(8.0); let mut pv = d.bool("preview"); @@ -157,9 +162,9 @@ pub(super) fn name_row(ui: &mut egui::Ui, d: &mut Dialog) -> bool { changed } -/// The shared fields of Swatch Options and New Swatch: name, colour type, Global, mode, sliders and -/// hex. Returns true when anything changed. -pub(super) fn editor(ui: &mut egui::Ui, d: &mut Dialog) -> bool { +/// The shared fields of Swatch Options and New Swatch: name, colour type, Global, mode, sliders, +/// hex and the colour warnings. Returns true when anything changed. +pub(super) fn editor(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { let mut changed = false; grid(ui, |ui| { changed |= name_row(ui, d); @@ -191,15 +196,46 @@ pub(super) fn editor(ui: &mut egui::Ui, d: &mut Dialog) -> bool { ui.end_row(); }); ui.add_space(6.0); - changed | sliders(ui, d) + changed | sliders(app, ui, d) } -/// One slider and value field per component of the dialog's mode, the hex field (RGB, HSB and Web) -/// and a chip of the colour. Returns true when the colour changed. -fn sliders(ui: &mut egui::Ui, d: &mut Dialog) -> bool { +/// A warning under the colour of the swatch dialogs. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum Warning { + Gamut, + Web, +} + +/// The warnings the swatch dialogs show in `mode`: out of gamut in RGB, HSB and Lab, and out of web +/// colors in every mode but Web Safe RGB. +fn shown_warnings(mode: Mode) -> (bool, bool) { + (matches!(mode, Mode::Rgb | Mode::Hsb | Mode::Lab), mode != Mode::WebSafe) +} + +/// The colour and mode a click on `warning` gives `c`, edited in `mode`: the nearest web-safe colour +/// (in RGB unless the mode is RGB or HSB), or the colour's CMYK equivalent in the active CMYK space +/// (in CMYK). `None` when the conversion returns no CMYK values. +fn corrected(app: &mut VectorcraftApp, warning: Warning, mode: Mode, c: &Color) -> Result<Option<(Color, Mode)>, String> { + match warning { + Warning::Web => Ok(Some((web_safe(c), if matches!(mode, Mode::Rgb | Mode::Hsb) { mode } else { Mode::Rgb }))), + Warning::Gamut => { + let r = app.run("color.convert", json!({"color": crate::panels::color_json(c), "to": "cmyk"}))?; + let v = |i: usize| r["values"][i].as_f64().map(|v| v as f32); + Ok(v(0).zip(v(1)).zip(v(2)).zip(v(3)).map(|(((c, m), y), k)| (Color::cmyk(c, m, y, k), Mode::Cmyk))) + } + } +} + +/// One slider and value field per component of the dialog's mode, the hex field (RGB, HSB and Web), +/// a chip of the colour and under it the mode's warnings. Returns true when the colour changed. +fn sliders(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { let t = Tokens::get(ui.ctx()); let mode = mode_of(d); let color = color_of(d); + let (shows_gamut, shows_web) = shown_warnings(mode); + let gamut = if shows_gamut { gamut_fix(app, ui.ctx(), "swatch-gamut", &color) } else { None }; + let web = (shows_web && !is_web_safe(&color)).then(|| web_safe(&color)); + let mut clicked: Option<Warning> = None; // Keep the displayed components while the colour is unchanged (hue survives S = 0 etc.). let key = format!("{}|{}", mode_id(mode), serde_json::to_string(&color).unwrap_or_default()); let comps: Vec<f32> = match d.fields.get("__comps") { @@ -239,13 +275,47 @@ fn sliders(ui: &mut egui::Ui, d: &mut Dialog) -> bool { }); } }); - let (r, _) = ui.allocate_exact_size(vec2(44.0, 44.0), egui::Sense::hover()); - widgets::swatch_tile(ui, r, &Paint::solid(color), false, false); + ui.vertical(|ui| { + let (r, _) = ui.allocate_exact_size(vec2(44.0, 44.0), egui::Sense::hover()); + widgets::swatch_tile(ui, r, &Paint::solid(color), false, false); + let warnings: Vec<_> = [(Warning::Gamut, GAMUT_WARNING, gamut), (Warning::Web, WEB_WARNING, web)] + .into_iter() + .filter_map(|(w, chip, fix)| Some((w, chip, fix?))) + .collect(); + for (w, chip, fix) in &warnings { + ui.add_space(4.0); + if warning_chip(ui, *chip, fix) { + clicked = Some(*w); + } + } + // Room for the mode's other warnings, so the dialog keeps its height as the colour changes. + for _ in warnings.len()..usize::from(shows_gamut) + usize::from(shows_web) { + ui.add_space(4.0); + ui.scope(|ui| { + ui.set_invisible(); + warning_chip(ui, WEB_WARNING, &Color::WHITE) + }); + } + }); }); + let mut mode = mode; + if let Some(w) = clicked { + match corrected(app, w, mode, &color) { + Ok(Some((c, m))) => { + mode = m; + d.fields.insert("mode".into(), json!(mode_id(m))); + new = Some((c, components(m, &c))); + } + Ok(None) => {} + Err(e) => app.status(e), + } + } let Some((c, comps)) = new else { return false }; set_color(d, c); d.fields.insert("__compsKey".into(), json!(format!("{}|{}", mode_id(mode), serde_json::to_string(&c).unwrap_or_default()))); d.fields.insert("__comps".into(), json!(comps)); + // The warnings above were drawn for the colour before the change. + ui.ctx().request_repaint(); true } @@ -277,9 +347,122 @@ fn hex_field(ui: &mut egui::Ui, hex: &str) -> Option<Color> { } #[cfg(test)] -mod tests { +pub(super) mod tests { use super::*; + /// A test context with the application's fonts and default theme. + pub(crate) fn context() -> egui::Context { + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + crate::theme::apply(&ctx, Default::default()); + ctx + } + + /// Runs one frame of the open dialog with `events` and returns the rectangles it paints. + pub(crate) fn draw(ctx: &egui::Context, app: &mut VectorcraftApp, events: Vec<egui::Event>) -> Vec<egui::Rect> { + fn collect(s: &egui::Shape, out: &mut Vec<egui::Rect>) { + match s { + egui::Shape::Rect(r) => out.push(r.rect), + egui::Shape::Vec(v) => v.iter().for_each(|s| collect(s, out)), + _ => {} + } + } + let input = + egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(1280.0, 900.0))), events, ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| super::super::show(app, ui.ctx())); + out.textures_delta.clear(); + let mut boxes = vec![]; + out.shapes.iter().for_each(|c| collect(&c.shape, &mut boxes)); + boxes + } + + /// Lets the auto-sized dialog settle and returns the rectangles of the next frame. + pub(crate) fn settled(ctx: &egui::Context, app: &mut VectorcraftApp) -> Vec<egui::Rect> { + for _ in 0..6 { + draw(ctx, app, vec![]); + } + draw(ctx, app, vec![]) + } + + /// A primary-button press and release at `at`, in two frames. + pub(crate) fn click_at(ctx: &egui::Context, app: &mut VectorcraftApp, at: egui::Pos2) { + for pressed in [true, false] { + let button = egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + draw(ctx, app, vec![egui::Event::PointerMoved(at), button]); + } + } + + /// The warning rows under the dialog's 44-point colour chip, top first: the centre of each + /// row's icon and the rectangle of its corrected colour. + pub(crate) fn warning_rows(boxes: &[egui::Rect]) -> Vec<(egui::Pos2, egui::Rect)> { + let near = |a: f32, b: f32| (a - b).abs() < 0.5; + let chip = boxes.iter().find(|r| near(r.width(), 44.0) && near(r.height(), 44.0)).copied().unwrap(); + let mut rows: Vec<egui::Rect> = boxes + .iter() + .filter(|r| near(r.width(), 16.0) && near(r.height(), 16.0)) + .filter(|r| r.top() >= chip.bottom() && r.left() >= chip.left() - 1.0 && r.right() <= chip.right() + 1.0) + .copied() + .collect(); + rows.sort_by(|a, b| a.top().total_cmp(&b.top())); + rows.dedup_by(|a, b| near(a.top(), b.top())); // The tile's fill and border share one rectangle. + rows.into_iter().map(|r| (r.center() - vec2(19.0, 0.0), r)).collect() + } + + fn dialog(app: &VectorcraftApp) -> &Dialog { + app.ui.dialog.as_ref().unwrap() + } + + #[test] + fn swatch_options_shows_and_corrects_both_warnings() { + let (ctx, mut app) = (context(), VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default())); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.run("swatch.new", json!({"name": "Sky", "color": "#0000fe", "spot": true})).unwrap(); + app.run("ui.swatchOptions", json!({"name": "Sky"})).unwrap(); + let rows = warning_rows(&settled(&ctx, &mut app)); + assert_eq!(rows.len(), 2, "out of gamut and out of web colors"); + // The cube's icon shifts to the nearest web-safe colour, in the same mode. + click_at(&ctx, &mut app, rows[1].0); + assert_eq!((color_of(dialog(&app)).to_hex(), dialog(&app).str("mode")), ("#0000ff".to_string(), "rgb".to_string())); + let rows = warning_rows(&settled(&ctx, &mut app)); + assert_eq!(rows.len(), 1, "web-safe blue is still out of gamut"); + // The triangle's colour shifts to the CMYK equivalent, edited in CMYK. + let ink = corrected(&mut app, Warning::Gamut, Mode::Rgb, &Color::rgb8(0, 0, 255)).unwrap().unwrap().0; + click_at(&ctx, &mut app, rows[0].1.center()); + assert_eq!((color_of(dialog(&app)), dialog(&app).str("mode")), (ink, "cmyk".to_string())); + assert!(app.ui.dialog.is_some(), "a correction only edits the fields"); + super::super::confirm(&mut app).unwrap(); + let sw = app.session.active().unwrap().doc.swatch("Sky").cloned().unwrap(); + assert_eq!((sw.paint.color(), sw.spot, sw.global), (Some(ink), true, true), "still a spot colour"); + app.run("edit.undo", json!({})).unwrap(); + let sw = app.session.active().unwrap().doc.swatch("Sky").cloned().unwrap(); + assert_eq!(sw.paint.color().map(|c| c.to_hex()), Some("#0000fe".into()), "one undo step"); + } + + #[test] + fn swatch_warnings_follow_the_mode() { + let (ctx, mut app) = (context(), VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default())); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.run("swatch.new", json!({"name": "Mid", "color": "#808080"})).unwrap(); + app.run("ui.swatchOptions", json!({"name": "Mid"})).unwrap(); + let mut rows_in = |mode: &str, c: Color| { + let d = app.ui.dialog.as_mut().unwrap(); + d.fields.insert("mode".into(), json!(mode)); + set_color(d, c); + warning_rows(&settled(&ctx, &mut app)).len() + }; + assert_eq!(rows_in("gray", Color::gray(0.5)), 1, "a gray off the web palette, never out of gamut"); + let cyan = Color::cmyk(1.0, 0.0, 0.0, 0.0); + assert_eq!(rows_in("cmyk", cyan), usize::from(!is_web_safe(&cyan)), "CMYK is never out of gamut"); + assert_eq!(rows_in("web", Color::rgb8(0, 0, 255)), 0, "Web Safe RGB shows no warning"); + assert_eq!(rows_in("rgb", Color::rgb8(0, 0, 255)), 1, "RGB blue is out of gamut"); + assert_eq!(rows_in("lab", Color::lab(30.0, 60.0, -100.0)), 2, "Lab shows both"); + // A web correction of a Lab colour is edited in RGB. + let rows = warning_rows(&settled(&ctx, &mut app)); + click_at(&ctx, &mut app, rows[1].0); + assert_eq!(dialog(&app).str("mode"), "rgb"); + assert!(is_web_safe(&color_of(dialog(&app)))); + } + #[test] fn fields_round_trip_modes_and_colours() { for (m, id) in MODES { diff --git a/crates/ui-egui/src/panels/color.rs b/crates/ui-egui/src/panels/color.rs index 28fb618dc9..c6a96b62d1 100644 --- a/crates/ui-egui/src/panels/color.rs +++ b/crates/ui-egui/src/panels/color.rs @@ -231,19 +231,23 @@ pub(crate) const WEB_WARNING: (&str, &str) = ("dc-cube", "Out of Web Color Warni /// The out-of-gamut warning: its icon and tooltip. pub(crate) const GAMUT_WARNING: (&str, &str) = ("dc-gamut", "Out of Gamut Warning"); -/// A warning icon with the corrected colour beside it. Returns true when the colour is clicked. +/// A warning icon with the corrected colour beside it. Returns true when the icon or the colour is +/// clicked. pub(crate) fn warning_chip(ui: &mut Ui, (icon, warning): (&str, &str), fix: &Color) -> bool { let t = Tokens::get(ui.ctx()); + let tip = crate::i18n::fmt( + tl!("{warning}: click to correct to the closest color ({hex})"), + &[("warning", tl!(warning)), ("hex", &format!("#{}", hex_digits(fix).to_ascii_lowercase()))], + ); ui.horizontal(|ui| { ui.spacing_mut().item_spacing.x = 3.0; - icons::icon(ui, icon, 16.0, t.icon).on_hover_text(tl!(warning)); + let icon = icons::icon(ui, icon, 16.0, t.icon).interact(Sense::click()); + icon.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, tl!(warning))); let (r, resp) = ui.allocate_exact_size(vec2(16.0, 16.0), Sense::click()); - widgets::swatch_tile(ui, r, &Paint::solid(*fix), false, resp.hovered()); - resp.on_hover_text(crate::i18n::fmt( - tl!("{warning}: click to correct to the closest color ({hex})"), - &[("warning", tl!(warning)), ("hex", &format!("#{}", hex_digits(fix).to_ascii_lowercase()))], - )) - .clicked() + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, &tip)); + widgets::swatch_tile(ui, r, &Paint::solid(*fix), false, resp.hovered() || icon.hovered()); + let icon = icon.on_hover_text(&tip).clicked(); + resp.on_hover_text(&tip).clicked() || icon }) .inner } diff --git a/docs/control-protocol.md b/docs/control-protocol.md index adac088a13..12c0ddfa64 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -131,7 +131,10 @@ the two can still win that race. Swatch editors: `engine.execute` with `ui.swatchOptions {name}` opens the `swatchOptions` dialog for a colour swatch (fields `name`, `spot`, `global`, `mode`: `gray`/`rgb`/`hsb`/`lab`/`cmyk`/`web`, `color`: `"#rrggbb"` or a colour object, `preview`), which previews on the canvas while open; `ui.dialog.confirm` applies it with `swatch.edit` as one undo -step and `ui.dialog.cancel` rolls the preview back. For a gradient swatch the dialog has `name` only (it shows the +step and `ui.dialog.cancel` rolls the preview back. Under the colour it shows the out-of-gamut warning (in RGB, HSB +and Lab) and the out-of-web-color warning (in every mode but `web`); a click on one sets `color` to the correction +and `mode` to `cmyk` for the gamut correction, or to `rgb` for a web correction of a `gray`, `lab` or `cmyk` colour. +The warnings are not fields: set `color` and `mode` to apply a correction from a script. For a gradient swatch the dialog has `name` only (it shows the gradient) and OK renames it; pattern swatches open pattern editing instead. Dropping a gradient (or colour) on a swatch of its kind in the Swatches panel with Alt held replaces it (`swatch.edit {name, paint}`), unless that is a tint swatch. A swatch dragged from the panel with Alt held also replaces the swatch of its kind it is dropped on, diff --git a/docs/mcp.md b/docs/mcp.md index 61c4bb417f..746dd074e9 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1811,8 +1811,8 @@ preferences (the folder the desktop app uses, so both see the same ones; `VECTOR `file.new`, `document.open`, `document.activate`, `file.close`, `file.revert`, `edit.undo`, `edit.redo` and a failed `command.batch` too; with none assigned, or no document open, the working spaces are. The `workingCmyk` target of `view.proofSetup` simulates the working CMYK space in such a document too. `color.convert`'s - `outOfGamut` and `deltaE`, `color.gamutCheck`, and the out-of-gamut warning of the Color panel and Color Picker - check against the assigned CMYK profile, else the working CMYK space; the warning updates when either changes. + `outOfGamut` and `deltaE`, `color.gamutCheck`, and the out-of-gamut warning of the Color panel, the Color Picker, + Swatch Options and New Swatch check against the assigned CMYK profile, else the working CMYK space; the warning updates when either changes. Not remembered: the document, anything else. Nothing is read or written when `VECTORCRAFT_NO_PREFS` is set, and a server confined with `--automation-read-root` or diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 3b3911ea84..14a4f4e107 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -812,6 +812,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Canvas through the display's profile on Windows and X11:** Preferences › Performance › Use Monitor Profile for Canvas (on by default) converts the canvas's art, artboard paper and transparency grid from sRGB into the ICC profile of the display that shows most of the main window, after any proof, as the help page describes the monitor's profile translating the document's colors for the monitor ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=151)). Windows gives the display's default profile, and a display with Advanced Color on is left to Windows ([Microsoft Learn](https://learn.microsoft.com/en-us/windows/win32/wcs/advanced-color-icc-profiles)); X11 gives colord's profile for the output or the `_ICC_PROFILE` property. macOS converts the window itself, and a Wayland session stays sRGB. `ui.inspect` reports `displayProfile`. Tests in `color/src/cms/display.rs`, `ui-egui/src/display_profile.rs` and `canvas::tests::the_canvas_is_drawn_through_the_display_profile_while_the_preference_is_on`. - **Translucent art blended before the display profile:** with Use Monitor Profile for Canvas converting, translucent art and the anti-aliased edges of art over an artboard's paper, a colored artboard or the transparency grid are blended with it in sRGB and the blend is converted, so the monitor's profile translates the document's colors as they are composited ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=151)). The frame rendered whole, the part an edit renders again, the render worker's frame, the pan fill and the other windows' panes do the same; over the pasteboard and in Outline the art is converted on its own, and with no profile to convert into nothing changes. Tests `display_profile::tests::translucent_pixels_over_the_paper_are_blended_before_they_are_converted`, `the_transparency_grid_is_blended_cell_by_cell`, `the_backdrop_is_found_through_the_view` and `canvas::tests::translucent_art_over_the_paper_is_blended_before_the_display_profile`. - **Out-of-gamut warning after a profile change:** the out-of-gamut warning and its closest-color correction in the Color panel and Color Picker ([the help page](https://helpx.adobe.com/illustrator/using/adjusting-colors.html)) check the color against the document's assigned CMYK profile, else the working CMYK space, and update when Edit › Assign Profile… or Edit › Color Settings… changes that space or a loaded profile changes, without a change of color. Which CMYK space the warning uses is VectorCraft's own rule. Tests: `gamut_warning_follows_a_profile_change` and `gamut_warning_follows_a_profile_loaded_again` in `dialogs/color_picker/tests.rs`. +- **Swatch Options and New Swatch color warnings:** both dialogs show the out-of-gamut triangle and the out-of-web-color cube under the color, each with its correction beside it, and a click on the icon or the correction shifts the color to the closest printable or web-safe color ([the archived user guide](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=236), Swatch options; [the help page](https://helpx.adobe.com/illustrator/using/adjusting-colors.html)). The icons in the Color panel and the Color Picker correct the color too. VectorCraft's own rules: the triangle shows in RGB, HSB and Lab and the cube in every mode but Web Safe RGB, both can show at once, a web correction of a Grayscale, Lab or CMYK color is edited in RGB, a gamut correction keeps the CMYK equivalent and is edited in CMYK, and a correction keeps the name, the color type and Global and changes the dialog's fields only, so OK records one undo step. Tests: `swatch_options_shows_and_corrects_both_warnings` and `swatch_warnings_follow_the_mode` in `dialogs/swatch_options.rs`, `a_warning_corrects_the_new_colour_only_until_ok` in `dialogs/new_swatch.rs`. - **Assign Profile and the working spaces:** Edit › Assign Profile… tags the document and leaves the working spaces of Edit › Color Settings… as they are, in Color Settings, the Separations panel and the settings saved for the next start. Colors show and convert through the profiles assigned; a change in Color Settings keeps the profiles the document in front is assigned in use, and removing an assigned profile in use puts the working space back in its place. The profiles in use follow the document in front: a new, opened or reverted document, a switch to another tab, a close, Undo and Redo of Assign Profile, a failed batch, each step of a batch, Export All Open and the update of placed documents put that document's profiles in use, and the working spaces where it is assigned none or no document is open. With Window › Arrange › Tile or floating document windows, each document behind the front one draws its art, paper and transparency grid through its own assigned profiles, and loading or removing a profile redraws the documents assigned it; placed documents inside it still draw through the front document's profiles. How documents behind the front one draw is VectorCraft's own rule. View › Proof Setup › Working CMYK simulates the working CMYK space of Color Settings in Proof Colors and Separations Preview, also in a document assigned another CMYK profile. Public references: [Changing the color profile for a document and About color working spaces](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=150) and [Soft-proof presets](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=134). Tests in `engine/tests/color_settings.rs`. - **Color management policies:** Edit › Color Settings… (the Separations panel's Color Settings section and `edit.colorSettings`) has an RGB and a CMYK policy: Off, Preserve Embedded Profiles and Convert to Working Space, and Preserve Numbers for CMYK. When a document tagged with a profile other than the working space is opened, reverted or opened as a template, the policy keeps the profile, takes it off with the color numbers kept, or converts that model's colors into the working space, with black point compensation as Color Settings set it, and takes it off. The policies are kept in `Color Settings.json`. Preserve Embedded Profiles as the default for both, and the per-model policy for a document tagged with both an RGB and a CMYK profile, are VectorCraft's own rules; placed images and the Profile Mismatches and Missing Profiles prompts are not covered. Public reference: [Color management policy options](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=157). Tests in `engine/tests/color_settings.rs`, `color/src/cms/tests.rs` and `color/src/cms/tests_icc.rs`. - **New Document's units:** the dialog opens in Preferences › Units › General, also on a Recent entry made in other units (an entry in pixels, or a saved preset in the units it was saved in, keeps its units), so File › New and New Without Dialog make documents in the General unit. Units chosen in the Units menu stay when another tab or preset is chosen and when a card is clicked or double-clicked; without such a choice, clicking another Recent or Saved card brings back the units that card was made in (#7944). These are VectorCraft's own rules. Tests: `the_dialog_opens_in_the_general_units_over_a_recent_entry`, `a_recent_saved_preset_keeps_its_units_and_name`, `units_chosen_in_the_menu_survive_tabs_and_presets` and `units_set_over_a_popup_stay_chosen` in `dialogs/new_document.rs`; `a_recent_card_keeps_the_units_chosen_in_the_menu` and `a_double_clicked_card_keeps_the_units_chosen_in_the_menu` in `panels/tests_units.rs`. From e6ec39306221c16e7bbb538a90bfa958df2bb139 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 17 Nov 2026 11:22:16 -0800 Subject: [PATCH 132/176] Shapes: the Circle tool draws a circle through two or three points MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Circle tool, in the Ellipse tool's flyout, draws a circle with shape.circleThroughPoints. A drag from one point to another, or a click on each, draws the circle with the two points as the ends of a diameter. A click on a first point, then a press on a second point dragged to a third, draws the circle through the three. Shift keeps the second point at 45° steps from the first. For a circle on two points, Alt rounds the diameter to the nearest ruler tick at the current zoom in the General unit. Each point snaps to Smart Guides. Until the release the tool shows the circle as a dashed outline (solid once it is more than 50,000 screen points around), a cross at its center, a line from the center to each point and, with Measurement Labels on, the diameter by the pointer. Three different points on one line, or a circle past the canvas, show "Circle too large" by the pointer instead, and the release draws nothing. Escape, a dropped press, and an edit, Undo or Redo made outside the tool drop the first point. A second press within 3 screen points of the first point, or one that snaps to it, places nothing when let go there, and draws the circle on the diameter it drags out when dragged. Each circle is one undo step. The tool's icon is new and drawn for VectorCraft. shape.circleThroughPoints also takes two points, or two selected anchor points, as the ends of a diameter. Its two errors about the number of points now say "two or three", in every catalog that translates them. Part of #7178. --- ASSETS.md | 1 + ROADMAP.md | 1 + assets/icons/dc-circle-points.svg | 1 + crates/engine/src/cmd/create.rs | 32 +-- crates/engine/src/tests/circle_through.rs | 54 +++- crates/geom/src/shapes.rs | 25 ++ crates/tools/src/catalog.rs | 1 + crates/tools/src/circle.rs | 296 ++++++++++++++++++++ crates/tools/src/circle/tests.rs | 326 ++++++++++++++++++++++ crates/tools/src/lib.rs | 2 + crates/ui-egui/src/edit_toolbar/tests.rs | 6 +- crates/ui-egui/src/i18n/bg.tsv | 2 + crates/ui-egui/src/i18n/bs.tsv | 2 + crates/ui-egui/src/i18n/ca.tsv | 6 +- crates/ui-egui/src/i18n/cs.tsv | 6 +- crates/ui-egui/src/i18n/da.tsv | 6 +- crates/ui-egui/src/i18n/de.tsv | 6 +- crates/ui-egui/src/i18n/el.tsv | 6 +- crates/ui-egui/src/i18n/es.tsv | 6 +- crates/ui-egui/src/i18n/fi.tsv | 6 +- crates/ui-egui/src/i18n/fr.tsv | 6 +- crates/ui-egui/src/i18n/gu.tsv | 2 + crates/ui-egui/src/i18n/hi.tsv | 6 +- crates/ui-egui/src/i18n/hu.tsv | 6 +- crates/ui-egui/src/i18n/id.tsv | 2 + crates/ui-egui/src/i18n/it.tsv | 6 +- crates/ui-egui/src/i18n/ja.tsv | 6 +- crates/ui-egui/src/i18n/ka.tsv | 6 +- crates/ui-egui/src/i18n/ko.tsv | 6 +- crates/ui-egui/src/i18n/nl.tsv | 6 +- crates/ui-egui/src/i18n/pl.tsv | 6 +- crates/ui-egui/src/i18n/pt-br.tsv | 6 +- crates/ui-egui/src/i18n/ru.tsv | 6 +- crates/ui-egui/src/i18n/sv.tsv | 6 +- crates/ui-egui/src/i18n/tr.tsv | 6 +- crates/ui-egui/src/i18n/uk.tsv | 6 +- crates/ui-egui/src/i18n/vi.tsv | 6 +- crates/ui-egui/src/i18n/zh-hans.tsv | 6 +- crates/ui-egui/src/i18n/zh-hant.tsv | 6 +- crates/ui-egui/src/icon_data.rs | 1 + crates/ui-egui/src/icons.rs | 1 + crates/ui-egui/src/toolbar.rs | 2 +- crates/ui-egui/src/toolbar/tests.rs | 2 +- docs/mcp.md | 35 ++- 44 files changed, 848 insertions(+), 90 deletions(-) create mode 100644 assets/icons/dc-circle-points.svg create mode 100644 crates/tools/src/circle.rs create mode 100644 crates/tools/src/circle/tests.rs diff --git a/ASSETS.md b/ASSETS.md index dbdd8b84d8..2c7a07478b 100644 --- a/ASSETS.md +++ b/ASSETS.md @@ -129,6 +129,7 @@ Generated-in-code art is original and has no file to list. This covers the defau | `assets/icons/dc-cap-square.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-center-hide.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-center-show.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | +| `assets/icons/dc-circle-points.svg` | VectorCraft contributors | Original work, drawn for VectorCraft (a circle with three dots on its edge) | MIT OR Apache-2.0 | | | `assets/icons/dc-clear.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-color-guide.svg` | VectorCraft contributors | Original work, drawn for VectorCraft | MIT OR Apache-2.0 | | | `assets/icons/dc-contour.svg` | VectorCraft contributors | Original work, drawn for VectorCraft (a solid rounded square inside four corner arcs, its offset outline); not derived from any other application's icon | MIT OR Apache-2.0 | | diff --git a/ROADMAP.md b/ROADMAP.md index 4358817b60..e9d2cc56b5 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -138,6 +138,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap - 2026-11-16: Check Fold Lines in the Packaging Tools add-on (Object › Plug-ins › Packaging Tools, and the Fold Lines panel's Check button): the fold lines of the selection or the document are split into blanks, panels and hinges (cut lines bound the material, and creases, partial cuts and perforations divide it into panels), and 15 kinds of issue are listed, errors and warnings, each naming its lines: cut lines that enclose nothing or end loose, gaps closed within a tolerance, a cut on top of a crease, duplicate lines, creases that end inside a panel, divide nothing, lie outside the blank or are not straight, gaps too narrow to map, fold lines in a hole, panels joined by no crease, and fold lines on a non-printing layer. The panel lists the issues in the interface language; clicking one selects its lines (`addon.packaging.check`). A VectorCraft addition: headline numbers unchanged. - 2026-11-02: Mouse wheel over a closed font-family field in Character, Properties or Control changes selected text through the family list using saved font filters (excluding search text), one undo step per notch, stopping at the ends (#5253). Scores and estimates unchanged. - 2026-11-15: Circle through three points: three Shift-clicks with the Ellipse tool, or `shape.circleThroughPoints` with three points or three selected anchor points, draw the circle whose edge passes through them, with the current paint, in one undo step; after two points the tool previews the circle through the pointer, and two points that are the same or three on one line are refused with a message. Scores and estimates unchanged. +- 2026-11-17: Circle tool (after the Ellipse tool in its group): two clicks or a drag draw the circle on that diameter, and a click followed by a drag from a second point to a third draws the circle through the three; Shift keeps the diameter at 45° steps, Alt rounds a two-point circle's diameter to the rulers' ticks at the current zoom, points snap to Smart Guides, and the tool shows the circle, its center, its radii and its diameter until the release, or "Circle too large" for points on one line or a circle past the canvas. `shape.circleThroughPoints` also takes two points or two selected anchor points as the ends of a diameter. One undo step per circle. A VectorCraft addition: headline numbers unchanged. - 2026-10-31: Pattern libraries: Window › Swatch Libraries › Patterns and the Swatches panel's library menu open Geometric Patterns, a built-in library of eleven pattern swatches (dots, stripes, checks, a grid and shapes); clicking one adds its pattern and swatch to the document, once, and applies it to the active fill or stroke (`swatch.library.add`). - 2026-11-11: Pattern libraries: Patterns › Grit Textures, a second built-in pattern library, holds eight seamless black textures (Fine Grain, Coarse Grit, Sand, Speckle, Stipple, Scratches, Sparse Flecks and Dense Flecks) on tiles of 18 to 36 pt, each drawn the same way every time; marks that reach past a tile edge continue on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged. - 2026-11-11: Pattern libraries: Patterns › Optical Effects, a third built-in pattern library, of VectorCraft's own designs, holds eight black wave, moiré and op-art tiles (Sine Bands, Ripple Lines, Interference Rings, Offset Rings, Warped Checks, Pinched Stripes, Chevron Pulse and Radiating Lenses) of 32 to 48 pt, each drawn the same way every time; each tile is one period of its design, and art that reaches past a tile edge continues on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged. diff --git a/assets/icons/dc-circle-points.svg b/assets/icons/dc-circle-points.svg new file mode 100644 index 0000000000..46da3a3401 --- /dev/null +++ b/assets/icons/dc-circle-points.svg @@ -0,0 +1 @@ +<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="7.5"/><circle cx="4.5" cy="12" r="1.6" fill="currentColor"/><circle cx="19.5" cy="12" r="1.6" fill="currentColor"/><circle cx="12" cy="4.5" r="1.6" fill="currentColor"/></svg> diff --git a/crates/engine/src/cmd/create.rs b/crates/engine/src/cmd/create.rs index 013b373d19..e9fcad8883 100644 --- a/crates/engine/src/cmd/create.rs +++ b/crates/engine/src/cmd/create.rs @@ -62,7 +62,7 @@ pub fn specs() -> Vec<CommandSpec> { "Circle Through Points", [], None, - "{points?: [[x, y], [x, y], [x, y]] (left out: the three selected anchor points, where a path selected whole counts all its anchors and selected segments' ends do not count)} → {id, cx, cy, radius}: a circle with the current paint whose edge passes through the three points, not pixel-aligned even while Align New Objects to Pixel Grid is on; two points that are the same or three on one line are an error, and nothing is drawn", + "{points?: [[x, y], [x, y]] or [[x, y], [x, y], [x, y]] (two: the ends of a diameter; left out: the two or three selected anchor points, where a path selected whole counts all its anchors and selected segments' ends do not count)} → {id, cx, cy, radius}: a circle with the current paint whose edge passes through the points, not pixel-aligned even while Align New Objects to Pixel Grid is on; two points that are the same, three on one line, or a circle reaching past the canvas are an error, and nothing is drawn", has_doc, circle_through_points ), @@ -413,16 +413,16 @@ fn ellipse(s: &mut Session, p: &Value) -> Result<Value> { add_art_turned(s, "Ellipse", path_kind(live.to_path(), Some(live)), rotation) } -/// A live ellipse whose edge passes through three points: `points`, or the three selected anchor -/// points ([`selected_anchor_points`]). One undo step, named as an Ellipse tool drag is. +/// A live ellipse whose edge passes through two or three points: `points`, or the two or three +/// selected anchor points ([`selected_anchor_points`]). Two points are the ends of a diameter. One +/// undo step, named as an Ellipse tool drag is. fn circle_through_points(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "shape.circleThroughPoints"; let points = match p.get("points").filter(|v| !v.is_null()) { - Some(v) => three_points(v).ok_or_else(|| bad(C, "`points` must be three [x, y] pairs of numbers"))?, - None => selected_anchor_points(s)?.ok_or_else(|| bad(C, "direct-select three anchor points, or give `points`"))?, + Some(v) => two_or_three_points(v).ok_or_else(|| bad(C, "`points` must be two or three [x, y] pairs of numbers"))?, + None => selected_anchor_points(s)?.ok_or_else(|| bad(C, "direct-select two or three anchor points, or give `points`"))?, }; - let [a, b, c] = points; - let (center, radius) = shapes::circle_through(a, b, c) + let (center, radius) = shapes::circle_through_points(&points) .ok_or_else(|| bad(C, "no circle passes through these points: two are the same or all three lie on one line"))?; let r = Rect::new(center.x - radius, center.y - radius, center.x + radius, center.y + radius); let live = LiveShape::Ellipse { w: r.width(), h: r.height(), pie: (0.0, 360.0), xf: Affine::translate(r.origin().to_vec2()) }; @@ -434,24 +434,25 @@ fn circle_through_points(s: &mut Session, p: &Value) -> Result<Value> { Ok(out) } -/// The three points `[[x, y], [x, y], [x, y]]` holds, each pair two finite numbers. -fn three_points(v: &Value) -> Option<[Point; 3]> { +/// The two or three points `[[x, y], [x, y]]` or `[[x, y], [x, y], [x, y]]` holds, each pair two +/// finite numbers. +fn two_or_three_points(v: &Value) -> Option<Vec<Point>> { let pair = |v: &Value| match v.as_array().map(Vec::as_slice) { Some([x, y]) => x.as_f64().zip(y.as_f64()).filter(|(x, y)| x.is_finite() && y.is_finite()).map(|(x, y)| Point::new(x, y)), _ => None, }; - match v.as_array().map(Vec::as_slice) { - Some([a, b, c]) => Some([pair(a)?, pair(b)?, pair(c)?]), + match v.as_array() { + Some(pairs) if matches!(pairs.len(), 2 | 3) => pairs.iter().map(pair).collect(), _ => None, } } -/// The positions of the selected anchor points, when there are exactly three. They are counted as +/// The positions of the selected anchor points, when there are two or three. They are counted as /// the other anchor commands count them ([`super::path::anchor_targets`]): a selected path with /// anchors picked by Direct Selection gives those, and a path selected whole gives all of its own. /// A selected segment's ends are not selected anchor points, so a selection with segments gives /// none; so does a selection holding an object that is not a path, or an anchor that is gone. -fn selected_anchor_points(s: &Session) -> Result<Option<[Point; 3]>> { +fn selected_anchor_points(s: &Session) -> Result<Option<Vec<Point>>> { let st = s.doc()?; if st.selection.segments.values().any(|set| !set.is_empty()) { return Ok(None); @@ -472,10 +473,7 @@ fn selected_anchor_points(s: &Session) -> Result<Option<[Point; 3]>> { return Ok(None); } } - Ok(match points.as_slice() { - &[a, b, c] => Some([a, b, c]), - _ => None, - }) + Ok(matches!(points.len(), 2 | 3).then_some(points)) } /// The whole-number count `p` gives for `key` (`5` or `5.0`), or `default` when it is left out or diff --git a/crates/engine/src/tests/circle_through.rs b/crates/engine/src/tests/circle_through.rs index 25fcc04beb..e91c48e76a 100644 --- a/crates/engine/src/tests/circle_through.rs +++ b/crates/engine/src/tests/circle_through.rs @@ -1,5 +1,6 @@ -//! `shape.circleThroughPoints`: a circle through three given points, or through the three anchor -//! points selected with Direct Selection, and the Ellipse tool's three Shift-clicks that run it. +//! `shape.circleThroughPoints`: a circle through two or three given points, or through the two or +//! three anchor points selected with Direct Selection, the Ellipse tool's three Shift-clicks that +//! run it, and the Circle tool. use serde_json::{Value, json}; use vectorcraft_doc::{LiveShape, Node, NodeKind}; @@ -95,13 +96,42 @@ fn coincident_or_collinear_points_are_refused() { assert!((r - want).abs() / want < 1e-9 && (cx - 200.0).abs() < 1e-6 && (cy - (199.99 + want)).abs() / want < 1e-9, "{out}"); } -/// Points that are not three pairs of finite numbers are an error, not a fallback. +/// Two points are the ends of a diameter: (20, 40) and (100, 100) give the circle centered at +/// (60, 70) with radius 50, through both points, in one undo step. Two points that are the same +/// are refused, and so is a circle that would reach past the canvas, from two points or from three +/// nearly on one line; nothing is drawn and no undo step is recorded. +#[test] +fn two_points_are_the_ends_of_a_diameter() { + let mut s = session(); + let undo = undo_len(&s); + let out = s.execute(C, &json!({"points": [[20, 40], [100, 100]]})).unwrap(); + assert_eq!((out["cx"].as_f64(), out["cy"].as_f64(), out["radius"].as_f64()), (Some(60.0), Some(70.0), Some(50.0)), "{out}"); + let id = id_of(&out); + assert!(bounds_are(&s, id, vectorcraft_geom::Rect::new(10.0, 20.0, 110.0, 120.0))); + assert!(farthest_from_path(&s, id, &[Point::new(20.0, 40.0), Point::new(100.0, 100.0)]) < 50.0 * 3e-4); + assert_eq!(s.doc().unwrap().selection.objects, [id]); + assert_eq!(undo_len(&s), undo + 1); + let (undo, count) = (undo_len(&s), object_count(&s)); + let e = s.execute(C, &json!({"points": [[30, 30], [30, 30]]})).unwrap_err().to_string(); + assert!(e.contains("no circle passes through these points"), "{e}"); + // 4,100,000 pt across, past the canvas's 4,000,000 pt from the origin; and three points 0.001 pt + // off a chord 200 pt long, whose circle has a radius of about 5,000,000 pt. + for points in [json!([[0, 0], [4_100_000, 0]]), json!([[0, 0], [200, 0], [100, 0.001]])] { + let e = s.execute(C, &json!({ "points": points })).unwrap_err().to_string(); + assert!(e.contains("result would exceed the canvas"), "{points}: {e}"); + } + assert_eq!((undo_len(&s), object_count(&s)), (undo, count)); +} + +/// Points that are not two or three pairs of finite numbers are an error, not a fallback. #[test] fn malformed_points_are_refused() { let mut s = session(); let undo = undo_len(&s); for points in [ - json!([[0, 0], [10, 0]]), + json!([[0, 0]]), + json!([]), + json!([[0, 0], [10]]), json!([[0, 0], [10, 0], [0, 10], [5, 5]]), json!([[0, 0], [10, 0], [0]]), json!([[0, 0], [10, 0], ["0", 10]]), @@ -109,12 +139,12 @@ fn malformed_points_are_refused() { json!([[0, 0], [10, 0], [0, 10, 3]]), ] { let e = s.execute(C, &json!({ "points": points })).unwrap_err().to_string(); - assert!(e.contains("`points` must be three [x, y] pairs of numbers"), "{points}: {e}"); + assert!(e.contains("`points` must be two or three [x, y] pairs of numbers"), "{points}: {e}"); } assert_eq!(undo_len(&s), undo); } -/// With `points` left out, the three anchor points selected with Direct Selection give the +/// With `points` left out, the two or three anchor points selected with Direct Selection give the /// circle, from one path or several; any other number of them is an error. #[test] fn three_direct_selected_anchor_points_give_the_circle() { @@ -130,11 +160,15 @@ fn three_direct_selected_anchor_points_give_the_circle() { s.execute("select.anchors", &json!({"id": other.0, "anchors": [[0, 0]], "mode": "add"})).unwrap(); let out = s.execute(C, &json!({"points": null})).unwrap(); assert_eq!((out["cx"].as_f64(), out["cy"].as_f64()), (Some(40.0), Some(30.0)), "{out}"); - // Two or four anchors, or a path of four anchors selected whole. - for picked in [json!([[0, 0], [0, 1]]), json!([[0, 0], [0, 1], [0, 2], [0, 3]])] { + // Two anchors are the ends of a diameter: (0, 0) and (80, 0). + s.execute("select.anchors", &json!({"id": path.0, "anchors": [[0, 0], [0, 1]], "mode": "set"})).unwrap(); + let out = s.execute(C, &json!({})).unwrap(); + assert_eq!((out["cx"].as_f64(), out["cy"].as_f64(), out["radius"].as_f64()), (Some(40.0), Some(0.0), Some(40.0)), "{out}"); + // One or four anchors, or a path of four anchors selected whole. + for picked in [json!([[0, 0]]), json!([[0, 0], [0, 1], [0, 2], [0, 3]])] { s.execute("select.anchors", &json!({"id": path.0, "anchors": picked, "mode": "set"})).unwrap(); let e = s.execute(C, &json!({})).unwrap_err().to_string(); - assert!(e.contains("direct-select three anchor points, or give `points`"), "{picked}: {e}"); + assert!(e.contains("direct-select two or three anchor points, or give `points`"), "{picked}: {e}"); } s.execute("select.set", &json!({"ids": [path.0]})).unwrap(); assert!(s.execute(C, &json!({})).is_err()); @@ -153,7 +187,7 @@ fn three_direct_selected_anchor_points_give_the_circle() { s.execute("select.segments", &json!({"id": path.0, "segments": [[0, 0], [0, 1]], "mode": "set"})).unwrap(); assert_eq!(s.doc().unwrap().selection.anchors.get(&path).map(|a| a.len()), Some(3)); let e = s.execute(C, &json!({})).unwrap_err().to_string(); - assert!(e.contains("direct-select three anchor points, or give `points`"), "{e}"); + assert!(e.contains("direct-select two or three anchor points, or give `points`"), "{e}"); assert_eq!(undo_len(&s), undo); } diff --git a/crates/geom/src/shapes.rs b/crates/geom/src/shapes.rs index 76b9b71798..838015115b 100644 --- a/crates/geom/src/shapes.rs +++ b/crates/geom/src/shapes.rs @@ -355,6 +355,18 @@ pub fn circle_through(a: Point, b: Point, c: Point) -> Option<(Point, f64)> { (center.is_finite() && radius.is_finite()).then_some((center, radius)) } +/// The circle through two or three points: two are the ends of a diameter, and three lie on its +/// edge ([`circle_through`]). Its center and radius; `None` for any other number of points, for +/// points that are the same, for three on one line, and for a center or radius that is not finite. +pub fn circle_through_points(points: &[Point]) -> Option<(Point, f64)> { + let circle = match *points { + [a, b] if a != b => Some((a.midpoint(b), a.distance(b) / 2.0)), + [a, b, c] => circle_through(a, b, c), + _ => None, + }; + circle.filter(|(c, r)| c.is_finite() && r.is_finite() && *r > 0.0) +} + /// Regular polygon with `sides` (≥ 3), first vertex straight up from the centre. pub fn polygon(center: Point, radius: f64, sides: u32, rotation_deg: f64) -> PathData { let n = sides.max(3); @@ -756,6 +768,19 @@ mod tests { assert_eq!(circle_through(a, b, Point::new(f64::NAN, 0.0)), None); } + /// Two points are the ends of a diameter, three are on the edge; one, four, two that are the + /// same and a point that is not finite give no circle. + #[test] + fn the_circle_through_two_or_three_points() { + let (a, b, c) = (Point::new(8.0, 0.0), Point::new(0.0, 6.0), Point::ORIGIN); + assert_eq!(circle_through_points(&[a, b]), Some((Point::new(4.0, 3.0), 5.0))); + let (center, r) = circle_through_points(&[a, b, c]).unwrap(); + assert!(center.distance(Point::new(4.0, 3.0)) < 1e-12 && (r - 5.0).abs() < 1e-12, "{center:?} {r}"); + for points in [&[a][..], &[a, b, c, a], &[a, a], &[a, Point::new(f64::INFINITY, 0.0)], &[], &[a, b, a.midpoint(b)]] { + assert_eq!(circle_through_points(points), None, "{points:?}"); + } + } + /// Nearly on one line: a point 10⁻⁴ off a chord 2000 long still gives the circle (its sagitta /// formula `r = (h² + (L/2)²) / 2h`), and its center sits on the chord's perpendicular /// bisector; a point 10⁻¹² off it does not. diff --git a/crates/tools/src/catalog.rs b/crates/tools/src/catalog.rs index 529aa80d18..cd6cbf627a 100644 --- a/crates/tools/src/catalog.rs +++ b/crates/tools/src/catalog.rs @@ -56,6 +56,7 @@ pub const TOOL_GROUPS: &[&[ToolInfo]] = &[ t("rectangle", "Rectangle Tool", Some("M"), "tool-rect"), t("roundedRectangle", "Rounded Rectangle Tool", None, "tool-rounded-rect"), t("ellipse", "Ellipse Tool", Some("L"), "tool-ellipse"), + t(crate::circle::ID, "Circle Tool", None, "tool-circle"), t("polygon", "Polygon Tool", None, "tool-polygon"), t("star", "Star Tool", None, "tool-star"), t("flare", "Flare Tool", None, "tool-flare"), diff --git a/crates/tools/src/circle.rs b/crates/tools/src/circle.rs new file mode 100644 index 0000000000..76e5a2df36 --- /dev/null +++ b/crates/tools/src/circle.rs @@ -0,0 +1,296 @@ +//! The Circle tool draws a circle through points it is given (`shape.circleThroughPoints`). +//! +//! Two points are the ends of a diameter: a drag from one to the other, or a click on each. A click +//! on a first point, then a press on a second point dragged to a third, draws the circle through +//! the three. Shift keeps the second point at 45° steps from the first (from General › Constrain +//! Angle), Alt rounds the diameter of a circle drawn on two points to the nearest tick of the +//! rulers at the current zoom, in the General unit, and every point snaps to Smart Guides. Until +//! the release, the tool shows the circle as a dashed outline (solid once it is more than 50,000 +//! screen points around) with its points, its center as a small cross, a line from the center to +//! each point and, with Measurement Labels on, the diameter by the pointer. The circle is one undo +//! step. Escape, a press dropped part way, and an edit, Undo or Redo made outside the tool drop +//! the first point. A second press within 3 screen points +//! of the first point, or one that snaps to it, is a press on it: let go there (a double-click) it +//! places nothing, and dragged out it draws the circle on the diameter it drags out. Where no +//! circle passes through the points (two are the same, three lie on one line) or the circle would +//! reach past the canvas, the tool shows none and the release draws nothing; for three different +//! points on one line, or a circle past the canvas, the pointer shows "Circle too large". + +use serde_json::{Value, json}; +use vectorcraft_doc::MAX_COORD; +use vectorcraft_geom::{Point, Rect, Vec2, shapes}; + +use crate::guides::{DrawSnap, Leave}; +use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; + +pub const ID: &str = "circle"; + +/// How far (screen points) the pointer travels from a press before the press counts as a drag. +const DRAG_PX: f64 = 2.0; +/// Half the length (screen points) of each arm of the cross at the circle's center. +const CROSS_PX: f64 = 4.0; +/// How near (screen points) the first point a second click counts as a click on it. +const REACH_PX: f64 = 3.0; +/// The longest outline (screen points) the preview draws dashed, about 7,000 dashes. +const DASHED_PX: f64 = 50_000.0; + +/// The press in progress. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Press { + /// The first point `at`, pressed with the pointer at `from` (before snapping): a release after + /// a drag draws the circle on that diameter. + First { at: Point, from: Point, dragged: bool }, + /// The second press, after a click placed the first point, with the pointer at `from` (before + /// snapping). `snapped` is the point it snapped to, and `at` that point with Alt's rounding of + /// the diameter. A release without a drag draws the circle on the diameter to `at`; a drag + /// places the third point and the circle passes through `snapped`. A press within + /// [`REACH_PX`] of the first point, or one that snaps to it (`on_first`), is a press on it: let + /// go there it places nothing, and dragged out it draws the circle on the diameter it drags out. + Second { at: Point, snapped: Point, from: Point, on_first: bool, dragged: bool }, +} + +#[derive(Default)] +pub struct CircleTool { + snap: DrawSnap, + /// The first point, placed by a click (or by the press of a drag in progress). + first: Option<Point>, + press: Option<Press>, + /// Where the pointer is, snapped: the point the next press or release places. + pointer: Option<Point>, +} + +/// The command the tool runs for `points`. +fn command(points: &[Point]) -> (String, Value) { + let pairs: Vec<Value> = points.iter().map(|p| json!([p.x, p.y])).collect(); + ("shape.circleThroughPoints".into(), json!({ "points": pairs })) +} + +/// The circle through two points (the ends of a diameter) or three, as `shape.circleThroughPoints` +/// draws it: none where no circle passes through them or it would reach past the canvas. +pub fn circle_of(points: &[Point]) -> Option<(Point, f64)> { + let on_canvas = |(c, r): &(Point, f64)| [c.x - r, c.y - r, c.x + r, c.y + r].iter().all(|v| v.abs() <= MAX_COORD); + shapes::circle_through_points(points).filter(on_canvas) +} + +/// With Alt, `p` moved along the line from `first` so that their distance (the diameter) is on +/// the nearest ruler tick at the current zoom, in the General unit; `p` itself without Alt, and +/// when that rounding leaves no distance. +fn round_diameter(cx: &ToolContext, first: Point, p: Point, mods: Mods) -> Point { + let d = first.distance(p); + let rounded = cx.unit.snap_to_ruler_tick(d, cx.zoom); + if mods.alt && d > 0.0 && rounded > 0.0 && rounded.is_finite() { first + (p - first) * (rounded / d) } else { p } +} + +/// Are the points two or more different points through which no circle is drawn: three on one +/// line, or a circle that would reach past the canvas? +fn too_large(points: &[Point]) -> bool { + let distinct = points.iter().enumerate().all(|(i, p)| !points.iter().take(i).any(|q| q == p)); + points.len() >= 2 && distinct && circle_of(points).is_none() +} + +impl CircleTool { + fn clear(&mut self) { + self.first = None; + self.press = None; + self.pointer = None; + self.snap.clear(); + } + + /// How the second point keeps to the first: Shift's 45° steps and the construction guides. + fn leave(&self, cx: &ToolContext, mods: Mods) -> Option<Leave> { + self.first.map(|a| Leave::segment(cx, a, mods.shift)) + } + + /// The points the circle passes through as the tool shows it now. + fn points(&self) -> Vec<Point> { + let mut out: Vec<Point> = self.first.into_iter().collect(); + match self.press { + Some(Press::First { .. }) | None => out.extend(self.pointer.filter(|_| self.first.is_some())), + // A press on the first point adds no point: a drag from it drags out a diameter. + Some(Press::Second { on_first: true, dragged, .. }) => out.extend(self.pointer.filter(|_| dragged)), + Some(Press::Second { at, dragged: false, .. }) => out.push(at), + Some(Press::Second { snapped, dragged: true, .. }) => { + out.push(snapped); + out.extend(self.pointer); + } + } + out + } + + /// The second point as the tool shows it: none for a press on the first point. + fn second(&self) -> Option<Point> { + match self.press { + Some(Press::Second { on_first: false, dragged: false, at, .. }) => Some(at), + Some(Press::Second { on_first: false, dragged: true, snapped, .. }) => Some(snapped), + _ => None, + } + } + + /// Runs the circle through `points` and starts afresh; where no circle is drawn through them + /// (the tool showed none), it only starts afresh. + fn draw(&mut self, points: &[Point]) -> Vec<Action> { + self.clear(); + if circle_of(points).is_none() { + return vec![]; + } + let (c, v) = command(points); + vec![Action::Exec(c, v)] + } +} + +impl Tool for CircleTool { + fn id(&self) -> &'static str { + ID + } + + fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec<Action> { + if !ev.pos.is_finite() { + return vec![]; + } + match ev.kind { + PointerKind::Move => { + let leave = self.leave(cx, ev.mods); + let p = self.snap.hover(cx, ev.pos, &[], leave.as_ref()); + self.pointer = Some(self.first.map_or(p, |a| round_diameter(cx, a, p, ev.mods))); + vec![] + } + PointerKind::Down => { + match self.first { + None => { + let at = self.snap.press(cx, ev.pos, &[], None); + self.first = Some(at); + self.press = Some(Press::First { at, from: ev.pos, dragged: false }); + self.pointer = Some(at); + } + Some(a) => { + let leave = self.leave(cx, ev.mods); + let snapped = self.snap.press(cx, ev.pos, &[], leave.as_ref()); + let at = round_diameter(cx, a, snapped, ev.mods); + let on_first = snapped == a || ev.pos.distance(a) <= cx.tol(REACH_PX); + self.press = Some(Press::Second { at, snapped, from: ev.pos, on_first, dragged: false }); + self.pointer = Some(at); + } + } + vec![] + } + PointerKind::Drag => { + match &mut self.press { + Some(Press::First { at, from, dragged }) => { + *dragged |= ev.pos.distance(*from) >= cx.tol(DRAG_PX); + let leave = Leave::segment(cx, *at, ev.mods.shift); + self.pointer = Some(round_diameter(cx, *at, self.snap.drag(cx, ev.pos, Some(&leave)), ev.mods)); + } + // Dragged from the first point, the pointer is the other end of a diameter, as + // for a drag from a first press. + Some(Press::Second { from, on_first: true, dragged, .. }) => { + *dragged |= ev.pos.distance(*from) >= cx.tol(DRAG_PX); + let leave = self.first.map(|a| Leave::segment(cx, a, ev.mods.shift)); + let p = self.snap.drag(cx, ev.pos, leave.as_ref()); + self.pointer = Some(self.first.map_or(p, |a| round_diameter(cx, a, p, ev.mods))); + } + Some(Press::Second { from, dragged, .. }) => { + *dragged |= ev.pos.distance(*from) >= cx.tol(DRAG_PX); + self.pointer = Some(self.snap.drag(cx, ev.pos, None)); + } + None => {} + } + vec![] + } + PointerKind::Up => match (self.press.take(), self.first, self.pointer) { + (Some(Press::First { at, dragged: true, .. }), _, Some(b)) if b.distance(at) >= cx.tol(DRAG_PX) => self.draw(&[at, b]), + // A click places the first point; the guides of the press go. + (Some(Press::First { .. }), ..) => { + self.snap.clear(); + vec![] + } + // The second click of a double-click lands on the first point and places nothing; + // a drag from there draws the circle on the diameter it drags out. + (Some(Press::Second { on_first: true, dragged: false, .. }), ..) => vec![], + (Some(Press::Second { on_first: true, dragged: true, .. }), Some(a), Some(c)) => self.draw(&[a, c]), + (Some(Press::Second { at, dragged: false, .. }), Some(a), _) => self.draw(&[a, at]), + // Three points: Alt's rounding of the diameter does not apply. + (Some(Press::Second { snapped, dragged: true, .. }), Some(a), Some(c)) => self.draw(&[a, snapped, c]), + _ => vec![], + }, + PointerKind::DoubleClick | PointerKind::TripleClick => vec![], + } + } + + fn key(&mut self, _cx: &ToolContext, key: ToolKey, _mods: Mods) -> Vec<Action> { + if key == ToolKey::Escape { + self.clear(); + } + vec![] + } + + fn claims_key(&self, _cx: &ToolContext, key: ToolKey) -> bool { + key == ToolKey::Escape && self.first.is_some() + } + + /// A first point placed: Escape drops it. + fn ends_on_escape(&self, _cx: &ToolContext) -> bool { + self.first.is_some() + } + + fn busy(&self) -> bool { + self.first.is_some() + } + + /// A dropped press (a second finger, a canceled touch) drops the points placed so far. + fn drop_press(&mut self, _cx: &ToolContext) -> Vec<Action> { + self.clear(); + vec![] + } + + fn deactivate(&mut self, _cx: &ToolContext) -> Vec<Action> { + self.clear(); + vec![] + } + + fn hover_ended(&mut self, _cx: &ToolContext) { + if self.press.is_none() { + self.pointer = None; + self.snap.clear(); + } + } + + /// An edit, Undo or Redo made outside the tool, or another document, drops the first point. + fn history_moved(&mut self) { + self.clear(); + } + + fn overlays(&self, cx: &ToolContext) -> Vec<Overlay> { + let mut o = self.snap.guides().to_vec(); + let points = self.points(); + let color = crate::draw2::FEEDBACK; + if let Some((c, r)) = circle_of(&points) { + let path = shapes::ellipse(Rect::new(c.x - r, c.y - r, c.x + r, c.y + r)).to_bezpath(); + // The canvas draws a dashed outline dash by dash along its whole length: a circle longer + // than DASHED_PX on screen is drawn solid instead. + let dashed = std::f64::consts::TAU * r <= cx.tol(DASHED_PX); + o.push(Overlay::Path { path, color, width: 1.0, dashed }); + for p in &points { + o.push(Overlay::Line { a: c, b: *p, color, dashed: false }); + } + let arm = cx.tol(CROSS_PX); + o.push(Overlay::Line { a: c - Vec2::new(arm, 0.0), b: c + Vec2::new(arm, 0.0), color, dashed: false }); + o.push(Overlay::Line { a: c - Vec2::new(0.0, arm), b: c + Vec2::new(0.0, arm), color, dashed: false }); + if let Some(p) = self.pointer.filter(|_| cx.measurement_labels) { + o.push(Overlay::Measure { p: p + Vec2::new(cx.tol(12.0), cx.tol(12.0)), text: format!("D: {}", cx.len(2.0 * r)) }); + } + } else if let Some(p) = self.pointer.filter(|_| too_large(&points)) { + o.push(Overlay::Label { p, text: "Circle too large".into(), color }); + } + for p in self.first.into_iter().chain(self.second()) { + o.push(Overlay::Anchor { p, color, filled: true, size: 6.0 }); + } + o + } + + fn cursor(&self, _cx: &ToolContext, _p: Point, _mods: Mods) -> Cursor { + Cursor::Crosshair + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/tools/src/circle/tests.rs b/crates/tools/src/circle/tests.rs new file mode 100644 index 0000000000..a6caafbc1d --- /dev/null +++ b/crates/tools/src/circle/tests.rs @@ -0,0 +1,326 @@ +use super::*; +use crate::testutil::*; +use vectorcraft_doc::Selection; + +fn ev(kind: PointerKind, (x, y): (f64, f64), mods: Mods) -> PointerEvent { + PointerEvent::new(kind, x, y).with_mods(mods) +} + +fn click(t: &mut CircleTool, cx: &ToolContext, p: (f64, f64)) -> Vec<Action> { + let mut acts = t.pointer(cx, &ev(PointerKind::Down, p, Mods::default())); + acts.extend(t.pointer(cx, &ev(PointerKind::Up, p, Mods::default()))); + acts +} + +/// A press at `from`, dragged through `path` and let go at its last point. +fn drag(t: &mut CircleTool, cx: &ToolContext, from: (f64, f64), path: &[(f64, f64)], mods: Mods) -> Vec<Action> { + let mut acts = t.pointer(cx, &ev(PointerKind::Down, from, mods)); + for p in path { + acts.extend(t.pointer(cx, &ev(PointerKind::Drag, *p, mods))); + } + let end = path.last().copied().unwrap_or(from); + acts.extend(t.pointer(cx, &ev(PointerKind::Up, end, mods))); + acts +} + +fn circle(points: &[(f64, f64)]) -> Vec<Action> { + let pairs: Vec<Value> = points.iter().map(|(x, y)| json!([x, y])).collect(); + vec![Action::Exec("shape.circleThroughPoints".into(), json!({ "points": pairs }))] +} + +/// The dashed circle the tool shows: its bounding box. +fn preview(o: &[Overlay]) -> Option<Rect> { + o.iter().find_map(|o| match o { + Overlay::Path { path, dashed: true, .. } => Some(vectorcraft_geom::Shape::bounding_box(path)), + _ => None, + }) +} + +fn near(a: Rect, b: Rect) -> bool { + [(a.x0, b.x0), (a.y0, b.y0), (a.x1, b.x1), (a.y1, b.y1)].iter().all(|(p, q)| (p - q).abs() < 1e-9) +} + +/// A drag from one point to another draws the circle with those two as the ends of a diameter. +#[test] +fn a_drag_draws_the_circle_on_its_diameter() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = CircleTool::default(); + assert_eq!(drag(&mut t, &cx, (300.0, 300.0), &[(340.0, 330.0), (380.0, 360.0)], Mods::default()), circle(&[(300.0, 300.0), (380.0, 360.0)])); + assert!(!t.ends_on_escape(&cx) && t.overlays(&cx).is_empty()); +} + +/// A click places the first point and a second click the other end of the diameter. In between, +/// the tool shows the circle through the first point and the pointer, its center cross, its radii +/// and its diameter. +#[test] +fn two_clicks_draw_the_circle_on_their_diameter() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = CircleTool::default(); + assert_eq!(click(&mut t, &cx, (300.0, 300.0)), vec![]); + assert!(t.ends_on_escape(&cx) && t.claims_key(&cx, ToolKey::Escape)); + t.pointer(&cx, &ev(PointerKind::Move, (380.0, 360.0), Mods::default())); + let o = t.overlays(&cx); + // Center (340, 330), radius 50. + assert!(near(preview(&o).expect("the circle is shown"), Rect::new(290.0, 280.0, 390.0, 380.0)), "{o:?}"); + let center = Point::new(340.0, 330.0); + let lines = o.iter().filter(|o| matches!(o, Overlay::Line { a, .. } if *a == center)).count(); + assert_eq!(lines, 2, "a radius to each point: {o:?}"); + assert!(o.iter().any(|o| matches!(o, Overlay::Measure { text, .. } if text.starts_with("D: 100"))), "{o:?}"); + let without_labels = ToolContext { measurement_labels: false, ..cx }; + assert!(!t.overlays(&without_labels).iter().any(|o| matches!(o, Overlay::Measure { .. }))); + assert_eq!(click(&mut t, &cx, (380.0, 360.0)), circle(&[(300.0, 300.0), (380.0, 360.0)])); + assert!(!t.ends_on_escape(&cx)); +} + +/// A click, then a press on a second point dragged to a third, draws the circle through the three. +#[test] +fn a_click_and_a_drag_draw_the_circle_through_three_points() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = CircleTool::default(); + click(&mut t, &cx, (300.0, 300.0)); + t.pointer(&cx, &ev(PointerKind::Down, (380.0, 300.0), Mods::default())); + t.pointer(&cx, &ev(PointerKind::Drag, (300.0, 360.0), Mods::default())); + // (300, 300), (380, 300) and (300, 360): the right angle stands on the diameter, center + // (340, 330), radius 50. + let o = t.overlays(&cx); + assert!(near(preview(&o).expect("the circle is shown"), Rect::new(290.0, 280.0, 390.0, 380.0)), "{o:?}"); + assert_eq!(o.iter().filter(|o| matches!(o, Overlay::Anchor { .. })).count(), 2, "{o:?}"); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, (300.0, 360.0), Mods::default())), circle(&[(300.0, 300.0), (380.0, 300.0), (300.0, 360.0)])); +} + +/// Three points on one line show no circle, and the release draws nothing and starts afresh. A +/// circle past the canvas is not shown either. +#[test] +fn points_on_one_line_show_no_circle() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = CircleTool::default(); + click(&mut t, &cx, (100.0, 100.0)); + t.pointer(&cx, &ev(PointerKind::Down, (200.0, 200.0), Mods::default())); + t.pointer(&cx, &ev(PointerKind::Drag, (300.0, 300.0), Mods::default())); + assert_eq!(preview(&t.overlays(&cx)), None); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, (300.0, 300.0), Mods::default())), vec![]); + assert!(!t.ends_on_escape(&cx) && t.overlays(&cx).is_empty()); + assert_eq!(circle_of(&[Point::new(0.0, 0.0), Point::new(4.1e6, 0.0)]), None); + assert_eq!(circle_of(&[Point::new(0.0, 0.0), Point::new(200.0, 0.0), Point::new(100.0, 0.001)]), None); +} + +/// Shift keeps the second point at 45° steps from the first. +#[test] +fn shift_keeps_the_diameter_at_45_degree_steps() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let shift = Mods { shift: true, ..Mods::default() }; + let mut t = CircleTool::default(); + let acts = drag(&mut t, &cx, (300.0, 300.0), &[(400.0, 310.0)], shift); + let [Action::Exec(_, v)] = acts.as_slice() else { panic!("one circle: {acts:?}") }; + let end = &v["points"][1]; + assert!((end[1].as_f64().unwrap() - 300.0).abs() < 1e-9, "level with the first point: {v}"); +} + +/// Alt rounds the diameter to the nearest ruler tick at the current zoom: every 5 pt at 100% and +/// every 2.5 pt at 200% in points, keeping the direction from the first point; for a drag, for a +/// second click and in the preview. +#[test] +fn alt_rounds_the_diameter_to_ruler_ticks() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let alt = Mods { alt: true, ..Mods::default() }; + // The second point of the one circle `acts` draws. + let second = |acts: Vec<Action>| { + let [Action::Exec(_, v)] = acts.as_slice() else { panic!("one circle: {acts:?}") }; + Point::new(v["points"][1][0].as_f64().unwrap(), v["points"][1][1].as_f64().unwrap()) + }; + let mut t = CircleTool::default(); + let end = second(drag(&mut t, &cx, (300.0, 300.0), &[(373.0, 300.0)], alt)); + assert!(end.distance(Point::new(375.0, 300.0)) < 1e-9, "{end:?}"); + // (31.2, 41.6) is 52 from the origin, and Alt makes it 50: (30, 40). + click(&mut t, &cx, (0.0, 0.0)); + t.pointer(&cx, &ev(PointerKind::Move, (31.2, 41.6), alt)); + assert!(near(preview(&t.overlays(&cx)).expect("the circle is shown"), Rect::new(-10.0, -5.0, 40.0, 45.0)), "{:?}", t.overlays(&cx)); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Down, (31.2, 41.6), alt)), vec![]); + let end = second(t.pointer(&cx, &ev(PointerKind::Up, (31.2, 41.6), alt))); + assert!(end.distance(Point::new(30.0, 40.0)) < 1e-9, "{end:?}"); + let zoomed = ToolContext { zoom: 2.0, ..cx }; + for (to, want) in [(51.0, 50.0), (51.5, 52.5)] { + let end = second(drag(&mut t, &zoomed, (0.0, 0.0), &[(0.0, to)], alt)); + assert!(end.distance(Point::new(0.0, want)) < 1e-9, "{to}: {end:?}"); + } + // Without Alt the pointer is used as it is. + assert_eq!(drag(&mut t, &cx, (300.0, 300.0), &[(373.0, 300.0)], Mods::default()), circle(&[(300.0, 300.0), (373.0, 300.0)])); +} + +/// Alt rounds only a diameter: a second press dragged to a third point keeps the second point +/// where it was pressed, and a second press 2.6 pt from the first point, which Alt's rounding +/// would move to 5 pt, is still a press on the first point and places nothing. +#[test] +fn alt_leaves_three_points_and_presses_on_the_first_point_alone() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let alt = Mods { alt: true, ..Mods::default() }; + let mut t = CircleTool::default(); + click(&mut t, &cx, (0.0, 0.0)); + assert_eq!(drag(&mut t, &cx, (31.2, 41.6), &[(45.0, 20.0), (60.0, 0.0)], alt), circle(&[(0.0, 0.0), (31.2, 41.6), (60.0, 0.0)])); + click(&mut t, &cx, (300.0, 300.0)); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Down, (302.6, 300.0), alt)), vec![]); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, (302.6, 300.0), alt)), vec![]); + assert!(t.ends_on_escape(&cx), "the first point stays"); +} + +/// Three different points on one line show "Circle too large" by the pointer instead of a circle; +/// a pointer back on the first point does not. +#[test] +fn points_on_one_line_say_the_circle_is_too_large() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let label = |t: &CircleTool| { + t.overlays(&cx).iter().find_map(|o| match o { + Overlay::Label { p, text, .. } => Some((*p, text.clone())), + _ => None, + }) + }; + let mut t = CircleTool::default(); + click(&mut t, &cx, (100.0, 100.0)); + t.pointer(&cx, &ev(PointerKind::Down, (200.0, 200.0), Mods::default())); + t.pointer(&cx, &ev(PointerKind::Drag, (300.0, 300.0), Mods::default())); + assert_eq!(label(&t), Some((Point::new(300.0, 300.0), "Circle too large".to_string()))); + t.pointer(&cx, &ev(PointerKind::Drag, (300.0, 290.0), Mods::default())); + assert_eq!(label(&t), None, "a circle is shown"); + t.pointer(&cx, &ev(PointerKind::Drag, (200.0, 200.0), Mods::default())); + assert_eq!(label(&t), None, "the third point is on the second"); + assert!(too_large(&[Point::new(0.0, 0.0), Point::new(4.1e6, 0.0)])); + assert!(!too_large(&[Point::new(0.0, 0.0)]) && !too_large(&[Point::new(1.0, 0.0), Point::new(1.0, 0.0)])); +} + +/// Escape drops the first point; so do a dropped press and an edit made outside the tool. A +/// second click on the first point places nothing. +#[test] +fn escape_and_outside_edits_drop_the_first_point() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = CircleTool::default(); + click(&mut t, &cx, (300.0, 300.0)); + assert_eq!(click(&mut t, &cx, (300.5, 300.0)), vec![], "a double-click places one point"); + assert!(t.ends_on_escape(&cx)); + t.key(&cx, ToolKey::Escape, Mods::default()); + assert!(!t.ends_on_escape(&cx) && t.overlays(&cx).is_empty()); + click(&mut t, &cx, (300.0, 300.0)); + t.history_moved(); + assert!(!t.ends_on_escape(&cx)); + click(&mut t, &cx, (300.0, 300.0)); + t.pointer(&cx, &ev(PointerKind::Down, (380.0, 300.0), Mods::default())); + t.drop_press(&cx); + assert!(!t.ends_on_escape(&cx)); + // After all of that, two clicks start a new circle. + click(&mut t, &cx, (10.0, 10.0)); + assert_eq!(click(&mut t, &cx, (30.0, 10.0)), circle(&[(10.0, 10.0), (30.0, 10.0)])); +} + +/// The points snap to Smart Guides: a press near the rectangle's corner anchor at (100, 100) places +/// the point on it. +#[test] +fn points_snap_to_smart_guides() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = cx(&d, &s, &p); + let mut t = CircleTool::default(); + t.pointer(&cx, &ev(PointerKind::Move, (101.0, 101.5), Mods::default())); + click(&mut t, &cx, (101.0, 101.5)); + assert_eq!(click(&mut t, &cx, (300.0, 100.0)), circle(&[(100.0, 100.0), (300.0, 100.0)])); +} + +/// A click is measured from where the pointer was pressed, not from the point it snapped to: a +/// second press pulled 1.8 pt onto the corner anchor at (100, 100) and moved 0.5 pt before the +/// release still draws the circle on that diameter. +#[test] +fn a_snapped_second_click_is_not_a_drag() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = cx(&d, &s, &p); + let mut t = CircleTool::default(); + click(&mut t, &cx, (300.0, 100.0)); + t.pointer(&cx, &ev(PointerKind::Down, (101.0, 101.5), Mods::default())); + t.pointer(&cx, &ev(PointerKind::Drag, (101.5, 101.5), Mods::default())); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, (101.5, 101.5), Mods::default())), circle(&[(300.0, 100.0), (100.0, 100.0)])); +} + +/// A second press within 3 screen points of the first point is a press on it: dragged out, it +/// draws the circle on the diameter it drags out, whether it landed on the first point or next to +/// it; a press farther away and dragged places the second and third points. +#[test] +fn a_drag_from_the_first_point_draws_the_circle_on_its_diameter() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = CircleTool::default(); + click(&mut t, &cx, (300.0, 300.0)); + let acts = drag(&mut t, &cx, (301.0, 300.0), &[(300.0, 350.0), (300.0, 400.0)], Mods::default()); + assert_eq!(acts, circle(&[(300.0, 300.0), (300.0, 400.0)])); + click(&mut t, &cx, (300.0, 300.0)); + let acts = drag(&mut t, &cx, (304.0, 300.0), &[(300.0, 350.0), (300.0, 400.0)], Mods::default()); + assert_eq!(acts, circle(&[(300.0, 300.0), (304.0, 300.0), (300.0, 400.0)])); + click(&mut t, &cx, (300.0, 300.0)); + t.pointer(&cx, &ev(PointerKind::Down, (300.0, 300.0), Mods::default())); + t.pointer(&cx, &ev(PointerKind::Drag, (300.0, 400.0), Mods::default())); + assert!(near(preview(&t.overlays(&cx)).expect("the circle is shown"), Rect::new(250.0, 300.0, 350.0, 400.0)), "{:?}", t.overlays(&cx)); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, (300.0, 400.0), Mods::default())), circle(&[(300.0, 300.0), (300.0, 400.0)])); +} + +/// A second press farther than 3 screen points from the first point that snaps to it is a press on +/// it too: the first point is the rectangle's corner anchor at (100, 100), and a press 3.2 pt away +/// snaps back to that anchor. +#[test] +fn a_second_press_that_snaps_to_the_first_point_is_a_press_on_it() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = cx(&d, &s, &p); + let mut t = CircleTool::default(); + click(&mut t, &cx, (100.0, 100.0)); + t.pointer(&cx, &ev(PointerKind::Down, (103.2, 100.0), Mods::default())); + assert_eq!(t.second(), None, "the press snapped to the first point: {:?}", t.press); + t.pointer(&cx, &ev(PointerKind::Drag, (100.0, 150.0), Mods::default())); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, (100.0, 150.0), Mods::default())), circle(&[(100.0, 100.0), (100.0, 150.0)])); +} + +/// A circle more than 50,000 screen points around is previewed solid, not dashed: three points +/// nearly on one line give a radius of about 1,250,000 pt. +#[test] +fn a_huge_circle_is_previewed_solid() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let mut t = CircleTool::default(); + click(&mut t, &cx, (0.0, 0.0)); + t.pointer(&cx, &ev(PointerKind::Down, (1000.0, 0.0), Mods::default())); + t.pointer(&cx, &ev(PointerKind::Drag, (500.0, 0.1), Mods::default())); + let o = t.overlays(&cx); + assert_eq!(preview(&o), None, "{o:?}"); + assert!(o.iter().any(|o| matches!(o, Overlay::Path { dashed: false, .. })), "{o:?}"); + // At 100% a circle 100 pt across is dashed. + t.pointer(&cx, &ev(PointerKind::Drag, (500.0, 300.0), Mods::default())); + assert!(preview(&t.overlays(&cx)).is_some()); +} + +/// The tool is in the Ellipse tool's group, after the Ellipse tool. +#[test] +fn the_circle_tool_follows_the_ellipse_tool() { + let tool = crate::create(ID); + assert_eq!(tool.id(), ID); + let group = crate::catalog::group_of(ID).unwrap(); + assert_eq!(crate::catalog::group_of("ellipse"), Some(group)); + let ids: Vec<&str> = crate::TOOL_GROUPS[group].iter().map(|t| t.id).collect(); + let ellipse = ids.iter().position(|id| *id == "ellipse").unwrap(); + assert_eq!(ids.get(ellipse + 1), Some(&ID)); +} diff --git a/crates/tools/src/lib.rs b/crates/tools/src/lib.rs index 7526717665..21c2d5157a 100644 --- a/crates/tools/src/lib.rs +++ b/crates/tools/src/lib.rs @@ -12,6 +12,7 @@ pub mod bbox; pub mod blendwidget; pub mod builder; pub mod catalog; +pub mod circle; pub mod corners; pub mod cropimage; pub mod cut; @@ -364,6 +365,7 @@ pub fn create(id: &str) -> Box<dyn Tool> { "dimension" => Box::new(dimension::DimensionTool::default()), "type" | "areaType" | "typeOnPath" | "verticalType" | "verticalAreaType" | "verticalTypeOnPath" => Box::new(text::TypeTool::new(id)), "rectangle" | "roundedRectangle" | "ellipse" | "polygon" | "star" | "lineSegment" => Box::new(shape::ShapeTool::new(id)), + circle::ID => Box::new(circle::CircleTool::default()), // Not in the toolbar: `file.place.queue` loads it. "place" => Box::new(place::PlaceTool::default()), other => symbolism::create(other) diff --git a/crates/ui-egui/src/edit_toolbar/tests.rs b/crates/ui-egui/src/edit_toolbar/tests.rs index 8983199324..b6ad39d122 100644 --- a/crates/ui-egui/src/edit_toolbar/tests.rs +++ b/crates/ui-egui/src/edit_toolbar/tests.rs @@ -207,7 +207,7 @@ fn the_commands_add_move_remove_and_reset_tools() { assert_eq!(slots(&app)[2], ["slice"]); let ellipse = slot_of(&app, "ellipse").unwrap(); app.run("toolbar.addTool", json!({"tool": "star", "slot": ellipse, "place": "group"})).unwrap(); - assert_eq!(slots(&app)[ellipse], ["ellipse", "star"]); + assert_eq!(slots(&app)[ellipse], ["ellipse", "circle", "star"]); assert!(!slots(&app)[slot_of(&app, "rectangle").unwrap()].contains(&"star")); // Onto its own group: nothing changes. let before = slots(&app); @@ -217,7 +217,7 @@ fn the_commands_add_move_remove_and_reset_tools() { assert_eq!(crate::toolbar::slots(&app)[0].0, Some("Select")); // Out: one tool, or its whole group; an emptied slot goes. app.run("toolbar.removeTool", json!({"tool": "ellipse"})).unwrap(); - assert_eq!(slots(&app)[ellipse], ["star"]); + assert_eq!(slots(&app)[ellipse], ["circle", "star"]); app.run("toolbar.removeTool", json!({"tool": "addAnchor", "group": true})).unwrap(); assert!(slot_of(&app, "pen").is_none() && slot_of(&app, "addAnchor").is_none()); // Bad params change nothing. @@ -379,7 +379,7 @@ fn tools_drag_between_the_drawer_and_the_toolbar() { let drawer = drawer_rect(&ctx).unwrap(); let (slice, _) = cell_at(&shown, drawer, "Slice Tool"); drag(&mut app, &ctx, 2.0, slice, tools[ellipse].center()); - assert_eq!(slots(&app)[ellipse], ["ellipse", "slice"]); + assert_eq!(slots(&app)[ellipse], ["ellipse", "circle", "slice"]); // A dimmed tool (in the toolbar already) doesn't drag. let before = slots(&app); let shown = frame(&mut app, &ctx, 2.9, vec![]); diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index bb039bb08e..d347439b69 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -465,6 +465,8 @@ font-technology Variable Променливи Choose a folder Избор на папка Choose… Избор… Circle Кръг + Circle Tool Инструмент Кръг + Circle too large Кръгът е твърде голям Classic Defaults Класически по подразбиране Clean Up… Почистване… Clear Изчистване diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 99f23d313c..6fea288f77 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -4525,6 +4525,8 @@ font-technology Variable Varijabilni Couldn't paste from the clipboard: {e} Nije moguće zalijepiti iz međuspremnika: {e} Channel Kanal Circle Krug + Circle Tool Alat za krug + Circle too large Krug je prevelik Clip to Art Isijeci prema crtežu Colorize Oboji Gamma Gama diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index c54311799d..e99406bffe 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -700,6 +700,8 @@ antiAlias Sharp Nítid Chrome Crom Chrome… Crom… Circle Cercle + Circle Tool Eina de cercle + Circle too large El cercle és massa gran Circle (open) Cercle (obert) Classic Clàssic Classic Defaults Valors predeterminats clàssics @@ -6149,8 +6151,8 @@ liquify-list-end {0}, {1} {0} i {1} @msg no active document no hi ha cap document actiu @msg no active perspective plane no hi ha cap pla de perspectiva actiu @msg no anchor points selected no hi ha cap punt d’ancoratge seleccionat -@msg `points` must be three [x, y] pairs of numbers `points` han de ser tres parells de nombres [x, y] -@msg direct-select three anchor points, or give `points` seleccioneu directament tres punts d’ancoratge o indiqueu `points` +@msg `points` must be two or three [x, y] pairs of numbers `points` han de ser dos o tres parells de nombres [x, y] +@msg direct-select two or three anchor points, or give `points` seleccioneu directament dos o tres punts d’ancoratge o indiqueu `points` @msg no circle passes through these points: two are the same or all three lie on one line cap cercle no passa per aquests punts: dos són iguals o tots tres són en una mateixa recta @msg no app to open files here aquí no hi ha cap aplicació per obrir fitxers @msg no artboard no hi ha tauler diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index a5d7bb948a..b217199fe0 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -4629,6 +4629,8 @@ font-technology Variable Variabilní Couldn't paste from the clipboard: {e} Nelze vložit ze schránky: {e} Channel Kanál Circle Kruh + Circle Tool Nástroj Kruh + Circle too large Kruh je příliš velký Clip to Art Oříznout podle kresby Colorize Obarvit Gamma Gama @@ -5314,8 +5316,8 @@ liquify-list-end {0}, {1} {0} a {1} @msg no active document žádný aktivní dokument @msg no active perspective plane žádná aktivní perspektivní rovina @msg no anchor points selected nejsou vybrány žádné kotevní body -@msg `points` must be three [x, y] pairs of numbers `points` musí být tři dvojice čísel [x, y] -@msg direct-select three anchor points, or give `points` vyberte přímým výběrem tři kotevní body, nebo zadejte `points` +@msg `points` must be two or three [x, y] pairs of numbers `points` musí být dvě nebo tři dvojice čísel [x, y] +@msg direct-select two or three anchor points, or give `points` vyberte přímým výběrem dva nebo tři kotevní body, nebo zadejte `points` @msg no circle passes through these points: two are the same or all three lie on one line těmito body neprochází žádná kružnice: dva jsou stejné nebo všechny tři leží na jedné přímce @msg no app to open files here zde chybí aplikace pro otevírání souborů @msg no artboard žádná pracovní plocha diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 08100f593f..de726e7860 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -7028,6 +7028,8 @@ font-technology Variable Variable Couldn't paste from the clipboard: {e} Kunne ikke indsætte fra udklipsholderen: {e} Channel Kanal Circle Cirkel + Circle Tool Cirkelværktøj + Circle too large Cirklen er for stor Clip to Art Beskær til grafik Colorize Farvelæg Gamma Gamma @@ -7503,8 +7505,8 @@ imageTrace Outline Kontur @msg no active document intet aktivt dokument @msg no active perspective plane intet aktivt perspektivplan @msg no anchor points selected ingen ankerpunkter er markeret -@msg `points` must be three [x, y] pairs of numbers `points` skal være tre talpar [x, y] -@msg direct-select three anchor points, or give `points` direkte markér tre ankerpunkter, eller angiv `points` +@msg `points` must be two or three [x, y] pairs of numbers `points` skal være to eller tre talpar [x, y] +@msg direct-select two or three anchor points, or give `points` direkte markér to eller tre ankerpunkter, eller angiv `points` @msg no circle passes through these points: two are the same or all three lie on one line ingen cirkel går gennem disse punkter: to er ens, eller alle tre ligger på én linje @msg no app to open files here ingen app til at åbne filer her @msg no artboard ingen tegneflade diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 10147b2d45..f85240675f 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -456,6 +456,8 @@ font-technology Variable Variabel Choose a folder Ordner wählen Choose… Wählen… Circle Kreis + Circle Tool Kreis-Werkzeug + Circle too large Kreis zu groß Classic Defaults Klassische Standardwerte Clean Up… Aufräumen… Clear Löschen @@ -4915,8 +4917,8 @@ liquify-list-end {0}, {1} {0} und {1} @msg no active document kein aktives Dokument @msg no active perspective plane keine aktive Perspektivebene @msg no anchor points selected keine Ankerpunkte ausgewählt -@msg `points` must be three [x, y] pairs of numbers `points` muss aus drei Zahlenpaaren [x, y] bestehen -@msg direct-select three anchor points, or give `points` wählen Sie drei Ankerpunkte direkt aus oder geben Sie `points` an +@msg `points` must be two or three [x, y] pairs of numbers `points` muss aus zwei oder drei Zahlenpaaren [x, y] bestehen +@msg direct-select two or three anchor points, or give `points` wählen Sie zwei oder drei Ankerpunkte direkt aus oder geben Sie `points` an @msg no circle passes through these points: two are the same or all three lie on one line durch diese Punkte verläuft kein Kreis: zwei sind gleich oder alle drei liegen auf einer Linie @msg no app to open files here hier gibt es keine App zum Öffnen von Dateien @msg no artboard keine Zeichenfläche diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 1ebf6e5684..a26550a5ac 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -449,6 +449,8 @@ font-technology Variable Μεταβλητές Choose a folder Επιλογή φακέλου Choose… Επιλογή… Circle Κύκλος + Circle Tool Εργαλείο κύκλου + Circle too large Ο κύκλος είναι πολύ μεγάλος Classic Defaults Κλασικές προεπιλογές Clean Up… Εκκαθάριση… Clear Εκκαθάριση @@ -4973,8 +4975,8 @@ digits Malayalam Μαλαγιάλαμ @msg no active document δεν υπάρχει ενεργό έγγραφο @msg no active perspective plane δεν υπάρχει ενεργό επίπεδο προοπτικής @msg no anchor points selected δεν έχουν επιλεγεί σημεία αγκύρωσης -@msg `points` must be three [x, y] pairs of numbers το `points` πρέπει να είναι τρία ζεύγη αριθμών [x, y] -@msg direct-select three anchor points, or give `points` επιλέξτε άμεσα τρία σημεία αγκύρωσης ή δώστε `points` +@msg `points` must be two or three [x, y] pairs of numbers το `points` πρέπει να είναι δύο ή τρία ζεύγη αριθμών [x, y] +@msg direct-select two or three anchor points, or give `points` επιλέξτε άμεσα δύο ή τρία σημεία αγκύρωσης ή δώστε `points` @msg no circle passes through these points: two are the same or all three lie on one line κανένας κύκλος δεν περνά από αυτά τα σημεία: δύο είναι ίδια ή και τα τρία βρίσκονται σε μία ευθεία @msg no app to open files here δεν υπάρχει εφαρμογή για άνοιγμα αρχείων εδώ @msg no artboard δεν υπάρχει πίνακας σχεδίασης diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index a456910a16..74e4627a9c 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -479,6 +479,8 @@ font-technology Variable Variables Choose a folder Elige una carpeta Choose… Elegir… Circle Círculo + Circle Tool Herramienta Círculo + Circle too large Círculo demasiado grande Classic Defaults Valores predeterminados clásicos Clean Up… Limpiar… Clear Borrar @@ -5019,8 +5021,8 @@ liquify-list-end {0}, {1} {0}, {1} @msg no active document no hay ningún documento activo @msg no active perspective plane no hay ningún plano de perspectiva activo @msg no anchor points selected no hay puntos de ancla seleccionados -@msg `points` must be three [x, y] pairs of numbers `points` debe ser tres pares de números [x, y] -@msg direct-select three anchor points, or give `points` seleccione directamente tres puntos de ancla o indique `points` +@msg `points` must be two or three [x, y] pairs of numbers `points` debe ser dos o tres pares de números [x, y] +@msg direct-select two or three anchor points, or give `points` seleccione directamente dos o tres puntos de ancla o indique `points` @msg no circle passes through these points: two are the same or all three lie on one line ningún círculo pasa por estos puntos: dos son iguales o los tres están en una misma línea @msg no app to open files here aquí no hay ninguna aplicación para abrir archivos @msg no artboard no hay mesa de trabajo diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index bff46fc0d7..170db8da57 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -4548,6 +4548,8 @@ font-technology Variable Muuttuvat Couldn't paste from the clipboard: {e} Leikepöydältä ei voitu liittää: {e} Channel Kanava Circle Ympyrä + Circle Tool Ympyrätyökalu + Circle too large Ympyrä on liian suuri Clip to Art Rajaa kuvitukseen Colorize Väritä Gamma Gamma @@ -5243,8 +5245,8 @@ liquify-list-end {0}, {1} {0} ja {1} @msg no active document ei aktiivista asiakirjaa @msg no active perspective plane ei aktiivista perspektiivitasoa @msg no anchor points selected ankkuripisteitä ei ole valittu -@msg `points` must be three [x, y] pairs of numbers `points` on annettava kolmena lukuparina [x, y] -@msg direct-select three anchor points, or give `points` valitse suoraan kolme ankkuripistettä tai anna `points` +@msg `points` must be two or three [x, y] pairs of numbers `points` on annettava kahtena tai kolmena lukuparina [x, y] +@msg direct-select two or three anchor points, or give `points` valitse suoraan kaksi tai kolme ankkuripistettä tai anna `points` @msg no circle passes through these points: two are the same or all three lie on one line näiden pisteiden kautta ei kulje ympyrää: kaksi pisteistä on samoja tai kaikki kolme ovat samalla suoralla @msg no app to open files here täällä ei ole sovellusta tiedostojen avaamiseen @msg no artboard ei piirtoalustaa diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 3be3497f97..9ca4919a2e 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -480,6 +480,8 @@ font-technology Variable Variables Choose a folder Choisissez un dossier Choose… Choisir… Circle Cercle + Circle Tool Outil Cercle + Circle too large Cercle trop grand Classic Defaults Valeurs par défaut classiques Clean Up… Nettoyer… Clear Effacer @@ -4981,8 +4983,8 @@ liquify-list-end {0}, {1} {0} et {1} @msg no active document aucun document actif @msg no active perspective plane aucun plan de perspective actif @msg no anchor points selected aucun point d’ancrage sélectionné -@msg `points` must be three [x, y] pairs of numbers `points` doit contenir trois paires de nombres [x, y] -@msg direct-select three anchor points, or give `points` sélectionnez trois points d’ancrage avec l’outil Sélection directe, ou indiquez `points` +@msg `points` must be two or three [x, y] pairs of numbers `points` doit contenir deux ou trois paires de nombres [x, y] +@msg direct-select two or three anchor points, or give `points` sélectionnez deux ou trois points d’ancrage avec l’outil Sélection directe, ou indiquez `points` @msg no circle passes through these points: two are the same or all three lie on one line aucun cercle ne passe par ces points : deux sont identiques ou les trois sont alignés @msg no app to open files here aucune application pour ouvrir des fichiers ici @msg no artboard aucun plan de travail diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index c427fc527c..532fcb06cb 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -562,6 +562,8 @@ Chosen: {n} of {total} પસંદ કરેલ: {total} માંથી {n} Chrome… ક્રોમ… Circle વર્તુળ + Circle Tool વર્તુળ ટૂલ + Circle too large વર્તુળ ખૂબ મોટું છે Circle: વર્તુળ: Classic ક્લાસિક Clean Up સાફ કરો diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index cbfb4f51d1..3bfe38fb3e 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -820,6 +820,8 @@ antiAlias Sharp शार्प Chrome क्रोम Chrome… क्रोम… Circle वृत्त + Circle Tool वृत्त टूल + Circle too large वृत्त बहुत बड़ा है Circle (open) सर्किल (ओपन) Circle: वृत्त: Classic क्लासिक @@ -7631,8 +7633,8 @@ liquify-list-end {0}, {1} {0} और {1} @msg no active document कोई सक्रिय डॉक्यूमेंट @msg no active perspective plane कोई सक्रिय पर्सपेक्टिव विमान नहीं @msg no anchor points selected कोई एंकर पॉइंट सिलेक्ट नहीं है -@msg `points` must be three [x, y] pairs of numbers `points` में संख्याओं के तीन [x, y] जोड़े होने चाहिए -@msg direct-select three anchor points, or give `points` तीन एंकर पॉइंट्स डायरेक्ट-सिलेक्ट करें, या `points` दें +@msg `points` must be two or three [x, y] pairs of numbers `points` में संख्याओं के दो या तीन [x, y] जोड़े होने चाहिए +@msg direct-select two or three anchor points, or give `points` दो या तीन एंकर पॉइंट्स डायरेक्ट-सिलेक्ट करें, या `points` दें @msg no circle passes through these points: two are the same or all three lie on one line इन पॉइंट्स से होकर कोई वृत्त नहीं गुज़रता: दो एक जैसे हैं या तीनों एक ही रेखा पर हैं @msg no app to open files here यहां फ़ाइलों को ओपन करने के लिए कोई ऐप नहीं है @msg no appearance item {index} कोई उपस्थिति आइटम {index} diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 0f81a72036..cfc6c224a3 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -641,6 +641,8 @@ font-technology Variable Változó Choose a folder Válassz mappát Choose… Kiválasztás… Circle Kör + Circle Tool Kör eszköz + Circle too large A kör túl nagy Circle (open) Kör (nyitott) Classic Defaults Klasszikus alapértékek Clean Up… Tisztítás… @@ -5682,8 +5684,8 @@ liquify-list-end {0}, {1} {0} és {1} @msg no active document nincs aktív dokumentum @msg no active perspective plane nincs aktív perspektivikus sík @msg no anchor points selected nincs kijelölt horgonypont -@msg `points` must be three [x, y] pairs of numbers a `points` három [x, y] számpár legyen -@msg direct-select three anchor points, or give `points` jelölj ki közvetlen kijelöléssel három horgonypontot, vagy add meg a `points` értéket +@msg `points` must be two or three [x, y] pairs of numbers a `points` két vagy három [x, y] számpár legyen +@msg direct-select two or three anchor points, or give `points` jelölj ki közvetlen kijelöléssel két vagy három horgonypontot, vagy add meg a `points` értéket @msg no circle passes through these points: two are the same or all three lie on one line ezeken a pontokon nem halad át kör: kettő egybeesik, vagy mindhárom egy egyenesen van @msg no app to open files here itt nincs fájlmegnyitó alkalmazás @msg no artboard nincs rajztábla diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 28ea2b5ab3..0526f18380 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -4280,6 +4280,8 @@ font-technology Variable Variabel Couldn't paste from the clipboard: {e} Tidak dapat menempel dari papan klip: {e} Channel Saluran Circle Lingkaran + Circle Tool Alat lingkaran + Circle too large Lingkaran terlalu besar Clip to Art Pangkas ke karya seni Colorize Warnai Gamma Gamma diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 8f2ed3216c..066a4ef6fd 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -481,6 +481,8 @@ font-technology Variable Variabili Choose a folder Scegli una cartella Choose… Scegli… Circle Cerchio + Circle Tool Strumento Cerchio + Circle too large Cerchio troppo grande Classic Defaults Valori predefiniti classici Clean Up… Pulisci… Clear Cancella @@ -5049,8 +5051,8 @@ liquify-list-end {0}, {1} {0} e {1} @msg no active document nessun documento attivo @msg no active perspective plane nessun piano prospettico attivo @msg no anchor points selected nessun punto di ancoraggio selezionato -@msg `points` must be three [x, y] pairs of numbers `points` deve essere composto da tre coppie di numeri [x, y] -@msg direct-select three anchor points, or give `points` seleziona con Selezione diretta tre punti di ancoraggio oppure indica `points` +@msg `points` must be two or three [x, y] pairs of numbers `points` deve essere composto da due o tre coppie di numeri [x, y] +@msg direct-select two or three anchor points, or give `points` seleziona con Selezione diretta due o tre punti di ancoraggio oppure indica `points` @msg no circle passes through these points: two are the same or all three lie on one line nessun cerchio passa per questi punti: due coincidono oppure tutti e tre sono allineati @msg no app to open files here nessuna app per aprire file qui @msg no artboard nessuna tavola da disegno diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index c429f204a1..597abda551 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -1297,6 +1297,8 @@ antiAlias Sharp シャープ Choose a folder フォルダーを選択 Choose… 選択… Circle 円 + Circle Tool 円ツール + Circle too large 円が大きすぎます Clear All Tabs すべてのタブを消去 Above Text テキストの上 Position Panel Above Text テキストの上にパネルを配置 @@ -4843,8 +4845,8 @@ swatch Bright Violet ビビッドバイオレット @msg image would be too large; lower the resolution 画像が大きくなりすぎるため、解像度を下げてください @msg clipboard is empty クリップボードが空です @msg no anchor points selected アンカーポイントが選択されていません -@msg `points` must be three [x, y] pairs of numbers `points` は 3 組の数値 [x, y] にしてください -@msg direct-select three anchor points, or give `points` アンカーポイントを 3 つダイレクト選択するか、`points` を指定してください +@msg `points` must be two or three [x, y] pairs of numbers `points` は 2 組または 3 組の数値 [x, y] にしてください +@msg direct-select two or three anchor points, or give `points` アンカーポイントを 2 つまたは 3 つダイレクト選択するか、`points` を指定してください @msg no circle passes through these points: two are the same or all three lie on one line これらの点を通る円はありません: 2 つの点が同じか、3 点すべてが一直線上にあります @msg select at least two objects オブジェクトを 2 つ以上選択してください @msg exit isolation mode first 先に分離モードを終了してください diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 414f45171c..0eb74ca1c0 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -6346,6 +6346,8 @@ font-technology Variable ცვლადი Couldn't paste from the clipboard: {e} გაცვლის ბუფერიდან ჩასმა ვერ მოხერხდა: {e} Channel არხი Circle წრე + Circle Tool წრის ხელსაწყო + Circle too large წრე ზედმეტად დიდია Clip to Art ნახატზე მოჭრა Colorize გაფერადება Gamma გამა @@ -6828,8 +6830,8 @@ font-technology Variable ცვლადი @msg no active document აქტიური დოკუმენტი არ არის @msg no active perspective plane აქტიური პერსპექტივის სიბრტყე არ არის @msg no anchor points selected საყრდენი წერტილები მონიშნული არ არის -@msg `points` must be three [x, y] pairs of numbers `points` უნდა იყოს რიცხვების სამი [x, y] წყვილი -@msg direct-select three anchor points, or give `points` პირდაპირი მონიშვნით მონიშნეთ სამი საყრდენი წერტილი ან მიუთითეთ `points` +@msg `points` must be two or three [x, y] pairs of numbers `points` უნდა იყოს რიცხვების ორი ან სამი [x, y] წყვილი +@msg direct-select two or three anchor points, or give `points` პირდაპირი მონიშვნით მონიშნეთ ორი ან სამი საყრდენი წერტილი ან მიუთითეთ `points` @msg no circle passes through these points: two are the same or all three lie on one line ამ წერტილებზე წრეწირი არ გადის: ორი ერთნაირია ან სამივე ერთ წრფეზე მდებარეობს @msg no app to open files here აქ ფაილების გასახსნელი აპი არ არის @msg no artboard სამუშაო დაფა არ არის diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index dbda53243f..83219f8de8 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -1287,6 +1287,8 @@ antiAlias Sharp 날카롭게 Choose a folder 폴더 선택 Choose… 선택… Circle 원 + Circle Tool 점 기준 원 도구 + Circle too large 원이 너무 큽니다 Clear All Tabs 모든 탭 지우기 Above Text 문자 위 Position Panel Above Text 패널을 문자 위에 배치 @@ -4770,8 +4772,8 @@ theme Appearance 외관 @msg image would be too large; lower the resolution 이미지가 너무 커집니다. 해상도를 낮추세요 @msg clipboard is empty 클립보드가 비어 있습니다 @msg no anchor points selected 선택한 앵커 포인트가 없습니다 -@msg `points` must be three [x, y] pairs of numbers `points`는 숫자 쌍 [x, y] 세 개여야 합니다 -@msg direct-select three anchor points, or give `points` 앵커 포인트 세 개를 직접 선택하거나 `points`를 지정하세요 +@msg `points` must be two or three [x, y] pairs of numbers `points`는 숫자 쌍 [x, y] 두 개 또는 세 개여야 합니다 +@msg direct-select two or three anchor points, or give `points` 앵커 포인트 두 개 또는 세 개를 직접 선택하거나 `points`를 지정하세요 @msg no circle passes through these points: two are the same or all three lie on one line 이 점들을 지나는 원이 없습니다: 두 점이 같거나 세 점이 모두 한 직선 위에 있습니다 @msg select at least two objects 개체를 두 개 이상 선택하세요 @msg exit isolation mode first 먼저 격리 모드를 종료하세요 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 69aef91cfc..f40a61047c 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -4902,6 +4902,8 @@ font-technology Variable Variabel Couldn't paste from the clipboard: {e} Kon niet vanaf het klembord plakken: {e} Channel Kanaal Circle Cirkel + Circle Tool Cirkelgereedschap + Circle too large Cirkel te groot Clip to Art Clippen op artwork Colorize Inkleuren Gamma Gamma @@ -5376,8 +5378,8 @@ imageTrace Outline Contour @msg no active document geen actief document @msg no active perspective plane geen actief perspectiefvlak @msg no anchor points selected geen ankerpunten geselecteerd -@msg `points` must be three [x, y] pairs of numbers `points` moet uit drie getallenparen [x, y] bestaan -@msg direct-select three anchor points, or give `points` selecteer met directe selectie drie ankerpunten of geef `points` op +@msg `points` must be two or three [x, y] pairs of numbers `points` moet uit twee of drie getallenparen [x, y] bestaan +@msg direct-select two or three anchor points, or give `points` selecteer met directe selectie twee of drie ankerpunten of geef `points` op @msg no circle passes through these points: two are the same or all three lie on one line er gaat geen cirkel door deze punten: twee zijn gelijk of alle drie liggen op één lijn @msg no app to open files here hier is geen app om bestanden mee te openen @msg no artboard geen tekengebied diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 0147515ffe..52e33d639a 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -4470,6 +4470,8 @@ font-technology Variable Zmienne Couldn't paste from the clipboard: {e} Nie udało się wkleić ze schowka: {e} Channel Kanał Circle Okrąg + Circle Tool Narzędzie Okrąg + Circle too large Okrąg jest za duży Clip to Art Przytnij do kompozycji Colorize Koloruj Gamma Gamma @@ -5137,8 +5139,8 @@ liquify-list-end {0}, {1} {0} i {1} @msg no active document brak aktywnego dokumentu @msg no active perspective plane brak aktywnej płaszczyzny perspektywy @msg no anchor points selected nie zaznaczono punktów kontrolnych -@msg `points` must be three [x, y] pairs of numbers `points` musi zawierać trzy pary liczb [x, y] -@msg direct-select three anchor points, or give `points` zaznacz bezpośrednio trzy punkty kontrolne lub podaj `points` +@msg `points` must be two or three [x, y] pairs of numbers `points` musi zawierać dwie lub trzy pary liczb [x, y] +@msg direct-select two or three anchor points, or give `points` zaznacz bezpośrednio dwa lub trzy punkty kontrolne lub podaj `points` @msg no circle passes through these points: two are the same or all three lie on one line przez te punkty nie przechodzi żaden okrąg: dwa są takie same albo wszystkie trzy leżą na jednej prostej @msg no app to open files here brak aplikacji do otwierania plików @msg no artboard brak obszaru kompozycji diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 8201db7ab6..5ae5b28f19 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -446,6 +446,8 @@ antiAlias Sharp Nítido Choose a folder Escolher uma pasta Choose… Escolher… Circle Círculo + Circle Tool Ferramenta Círculo + Circle too large Círculo grande demais Clean Up… Limpar… Clear Limpar Clear All Tabs Limpar Todas as Paradas de Tabulação @@ -4323,8 +4325,8 @@ axis Both Ambos @msg no active document nenhum documento ativo @msg no active perspective plane nenhum plano de perspectiva ativo @msg no anchor points selected nenhum ponto de ancoragem selecionado -@msg `points` must be three [x, y] pairs of numbers `points` deve ter três pares de números [x, y] -@msg direct-select three anchor points, or give `points` selecione diretamente três pontos de ancoragem ou informe `points` +@msg `points` must be two or three [x, y] pairs of numbers `points` deve ter dois ou três pares de números [x, y] +@msg direct-select two or three anchor points, or give `points` selecione diretamente dois ou três pontos de ancoragem ou informe `points` @msg no circle passes through these points: two are the same or all three lie on one line nenhum círculo passa por esses pontos: dois são iguais ou os três estão na mesma reta @msg no app to open files here nenhum aplicativo para abrir arquivos aqui @msg no artboard nenhuma prancheta diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index d1593508d3..3dc089a76d 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -477,6 +477,8 @@ font-technology Variable Вариативные Choose a folder Выберите папку Choose… Выбрать… Circle Круг + Circle Tool Инструмент «Круг» + Circle too large Круг слишком большой Classic Defaults Классические значения по умолчанию Clean Up… Очистить… Clear Очистить @@ -5043,8 +5045,8 @@ liquify-list-end {0}, {1} {0} и {1} @msg no active document нет активного документа @msg no active perspective plane нет активной плоскости перспективы @msg no anchor points selected опорные точки не выделены -@msg `points` must be three [x, y] pairs of numbers `points` должен содержать три пары чисел [x, y] -@msg direct-select three anchor points, or give `points` выделите прямым выделением три опорные точки или задайте `points` +@msg `points` must be two or three [x, y] pairs of numbers `points` должен содержать две или три пары чисел [x, y] +@msg direct-select two or three anchor points, or give `points` выделите прямым выделением две или три опорные точки или задайте `points` @msg no circle passes through these points: two are the same or all three lie on one line через эти точки не проходит ни одна окружность: две точки совпадают или все три лежат на одной прямой @msg no app to open files here здесь нет приложения для открытия файлов @msg no artboard нет монтажной области diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 5c0420fcd3..5e852da822 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -467,6 +467,8 @@ font-technology Variable Variabla Choose a folder Välj en mapp Choose… Välj… Circle Cirkel + Circle Tool Cirkelverktyg + Circle too large Cirkeln är för stor Classic Defaults Klassiska standardvärden Clean Up… Rensa upp… Clear Rensa @@ -4916,8 +4918,8 @@ liquify-list-end {0}, {1} {0} och {1} @msg no active document inget aktivt dokument @msg no active perspective plane inget aktivt perspektivplan @msg no anchor points selected inga ankarpunkter är markerade -@msg `points` must be three [x, y] pairs of numbers `points` måste vara tre talpar [x, y] -@msg direct-select three anchor points, or give `points` direktmarkera tre ankarpunkter eller ange `points` +@msg `points` must be two or three [x, y] pairs of numbers `points` måste vara två eller tre talpar [x, y] +@msg direct-select two or three anchor points, or give `points` direktmarkera två eller tre ankarpunkter eller ange `points` @msg no circle passes through these points: two are the same or all three lie on one line ingen cirkel går genom de här punkterna: två är samma punkt eller så ligger alla tre på en linje @msg no app to open files here det finns ingen app för att öppna filer här @msg no artboard ingen rityta diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 910a7fc5b1..de1d7280f1 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -461,6 +461,8 @@ font-technology Variable Değişken Choose a folder Bir klasör seçin Choose… Seç… Circle daire + Circle Tool Daire Aracı + Circle too large Daire çok büyük Classic Defaults Klasik Varsayılanlar Clean Up… Temizleme… Clear Temizle @@ -4736,8 +4738,8 @@ liquify-list-end {0}, {1} {0} ve {1} @msg no active document etkin belge yok @msg no active perspective plane aktif perspektif düzlemi yok @msg no anchor points selected bağlantı noktası seçilmedi -@msg `points` must be three [x, y] pairs of numbers `points` üç [x, y] sayı çifti olmalıdır -@msg direct-select three anchor points, or give `points` üç bağlantı noktasını doğrudan seçin veya `points` verin +@msg `points` must be two or three [x, y] pairs of numbers `points` iki veya üç [x, y] sayı çifti olmalıdır +@msg direct-select two or three anchor points, or give `points` iki veya üç bağlantı noktasını doğrudan seçin veya `points` verin @msg no circle passes through these points: two are the same or all three lie on one line bu noktalardan geçen bir çember yok: ikisi aynı ya da üçü de aynı doğru üzerinde @msg no app to open files here burada dosyaları açacak uygulama yok @msg no artboard çalışma yüzeyi yok diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index dbd6d2609e..e82439dca3 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -475,6 +475,8 @@ font-technology Variable Варіативні Choose a folder Виберіть папку Choose… Вибрати… Circle Коло + Circle Tool Інструмент «Коло» + Circle too large Коло завелике Classic Defaults Класичні значення за промовчанням Clean Up… Очистити… Clear Очистити @@ -5033,8 +5035,8 @@ liquify-list-end {0}, {1} {0} і {1} @msg no active document немає активного документа @msg no active perspective plane немає активної площини перспективи @msg no anchor points selected опорні точки не виділені -@msg `points` must be three [x, y] pairs of numbers `points` має містити три пари чисел [x, y] -@msg direct-select three anchor points, or give `points` виділіть три опорні точки прямим виділенням або задайте `points` +@msg `points` must be two or three [x, y] pairs of numbers `points` має містити дві або три пари чисел [x, y] +@msg direct-select two or three anchor points, or give `points` виділіть дві або три опорні точки прямим виділенням або задайте `points` @msg no circle passes through these points: two are the same or all three lie on one line через ці точки не проходить жодне коло: дві точки збігаються або всі три лежать на одній прямій @msg no app to open files here тут немає програми для відкриття файлів @msg no artboard немає монтажної області diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 519c5d8f0d..0f088fec2b 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -557,6 +557,8 @@ font-technology Variable Biến thiên Choose the file to relink each linked file to. Files with the size and contents saved with the link come first. Chọn tệp để liên kết lại từng tệp liên kết. Các tệp có kích thước và nội dung đã lưu cùng liên kết được hiển thị trước. Choose… Chọn… Circle Hình tròn + Circle Tool Công cụ Hình tròn + Circle too large Hình tròn quá lớn Classic Cổ điển Classic Defaults Mặc định cổ điển Clean Up… Dọn dẹp… @@ -5365,8 +5367,8 @@ liquify-list-end {0}, {1} {0} và {1} @msg no active document không có tài liệu đang hoạt động @msg no active perspective plane không có mặt phẳng phối cảnh đang hoạt động @msg no anchor points selected chưa chọn điểm neo -@msg `points` must be three [x, y] pairs of numbers `points` phải là ba cặp số [x, y] -@msg direct-select three anchor points, or give `points` hãy chọn trực tiếp ba điểm neo hoặc cung cấp `points` +@msg `points` must be two or three [x, y] pairs of numbers `points` phải là hai hoặc ba cặp số [x, y] +@msg direct-select two or three anchor points, or give `points` hãy chọn trực tiếp hai hoặc ba điểm neo hoặc cung cấp `points` @msg no circle passes through these points: two are the same or all three lie on one line không có đường tròn nào đi qua các điểm này: hai điểm trùng nhau hoặc cả ba điểm thẳng hàng @msg no app to open files here không có ứng dụng để mở tệp ở đây @msg no artboard không có bảng vẽ diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index c6696a9ec6..ed027b9f23 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -428,6 +428,8 @@ antiAlias Sharp 锐利 Choose a folder 选择文件夹 Choose… 选择… Circle 圆形 + Circle Tool 圆形工具 + Circle too large 圆形过大 Classic Defaults 经典默认 Clean Up… 清理… Clear 清除 @@ -4541,8 +4543,8 @@ imageTrace Outline 轮廓 @msg image would be too large; lower the resolution 图像将过大;请降低分辨率 @msg clipboard is empty 剪贴板为空 @msg no anchor points selected 未选择锚点 -@msg `points` must be three [x, y] pairs of numbers `points` 必须是三对数字 [x, y] -@msg direct-select three anchor points, or give `points` 请直接选择三个锚点,或提供 `points` +@msg `points` must be two or three [x, y] pairs of numbers `points` 必须是两对或三对数字 [x, y] +@msg direct-select two or three anchor points, or give `points` 请直接选择两个或三个锚点,或提供 `points` @msg no circle passes through these points: two are the same or all three lie on one line 没有圆经过这些点:有两点相同,或三点共线 @msg select at least two objects 请至少选择两个对象 @msg exit isolation mode first 请先退出隔离模式 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 1480422931..d5d613a7d8 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -443,6 +443,8 @@ font-technology Variable 可變 Choose a folder 選擇資料夾 Choose… 選擇… Circle 圓形 + Circle Tool 圓形工具 + Circle too large 圓形過大 Classic Defaults 經典預設值 Clean Up… 清除… Clear 清除 @@ -2074,8 +2076,8 @@ file-filter Templates 範本 @msg image would be too large; lower the resolution 影像會過大;請降低解析度 @msg clipboard is empty 剪貼簿是空的 @msg no anchor points selected 未選取錨點 -@msg `points` must be three [x, y] pairs of numbers `points` 必須是三組數字 [x, y] -@msg direct-select three anchor points, or give `points` 請以直接選取方式選取三個錨點,或提供 `points` +@msg `points` must be two or three [x, y] pairs of numbers `points` 必須是兩組或三組數字 [x, y] +@msg direct-select two or three anchor points, or give `points` 請以直接選取方式選取兩個或三個錨點,或提供 `points` @msg no circle passes through these points: two are the same or all three lie on one line 沒有圓通過這些點:有兩點相同,或三點共線 @msg select at least two objects 請選取至少兩個物件 @msg exit isolation mode first 請先結束隔離模式 diff --git a/crates/ui-egui/src/icon_data.rs b/crates/ui-egui/src/icon_data.rs index f521e45c22..bc0cfe3510 100644 --- a/crates/ui-egui/src/icon_data.rs +++ b/crates/ui-egui/src/icon_data.rs @@ -58,6 +58,7 @@ pub static ICONS: &[(&str, &[u8])] = &[ ("dc-cap-square", include_bytes!("../../../assets/icons/dc-cap-square.svg")), ("dc-center-hide", include_bytes!("../../../assets/icons/dc-center-hide.svg")), ("dc-center-show", include_bytes!("../../../assets/icons/dc-center-show.svg")), + ("dc-circle-points", include_bytes!("../../../assets/icons/dc-circle-points.svg")), ("dc-clear", include_bytes!("../../../assets/icons/dc-clear.svg")), ("dc-color-guide", include_bytes!("../../../assets/icons/dc-color-guide.svg")), ("dc-contour", include_bytes!("../../../assets/icons/dc-contour.svg")), diff --git a/crates/ui-egui/src/icons.rs b/crates/ui-egui/src/icons.rs index e352653279..c4a67fdef6 100644 --- a/crates/ui-egui/src/icons.rs +++ b/crates/ui-egui/src/icons.rs @@ -44,6 +44,7 @@ pub fn tool_icon(name: &str) -> &'static str { "tool-rect" => "square", "tool-rounded-rect" => "dc-rounded-rect", "tool-ellipse" => "dc-ellipse", + "tool-circle" => "dc-circle-points", "tool-polygon" => "dc-polygon", "tool-star" => "star", "tool-flare" => "dc-flare", diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index 56de30acff..3c78f12df0 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -38,7 +38,7 @@ pub const BASIC: &[(&str, &[&[&str]])] = &[ "Shapes", &[ &["rectangle", "roundedRectangle", "star", "lineSegment", "arc", "spiral", "rectangularGrid", "polarGrid", "flare"], - &["ellipse"], + &["ellipse", "circle"], &["polygon"], &["shaper"], ], diff --git a/crates/ui-egui/src/toolbar/tests.rs b/crates/ui-egui/src/toolbar/tests.rs index 37613c72e8..708e5e9807 100644 --- a/crates/ui-egui/src/toolbar/tests.rs +++ b/crates/ui-egui/src/toolbar/tests.rs @@ -853,7 +853,7 @@ fn window_float_tools_floats_and_puts_back_a_group() { assert!(app.ui.floating_flyouts.is_empty() && check(&app) == Some(false)); assert_eq!(app.run("window.floatTools", json!({"tool": "pen", "floating": false})).unwrap(), json!(false)); // A tool alone in its slot, an unknown tool, a bad flag. - assert!(app.run("window.floatTools", json!({"tool": "ellipse"})).is_err()); + assert!(app.run("window.floatTools", json!({"tool": "polygon"})).is_err()); assert!(app.run("window.floatTools", json!({"tool": "nope"})).is_err()); assert!(app.run("window.floatTools", json!({})).is_err()); assert!(app.run("window.floatTools", json!({"tool": "pen", "floating": "yes"})).is_err()); diff --git a/docs/mcp.md b/docs/mcp.md index 4c1b661f42..bdfa886286 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -6176,17 +6176,32 @@ slider (`ui.menuDialog {command: "object.path.smooth"}`, dialog `smoothSlider` w Auto-Smooth level, and the slider previews the result until `ui.dialog.confirm`; `ui.smoothAuto` moves the open slider back to the Auto-Smooth level. -## Circle through three points +## Circle through two or three points -`shape.circleThroughPoints {points?: [[x, y], [x, y], [x, y]]}` draws the circle whose edge passes through three -points, as a live ellipse with the current paint, and selects it. Without `points`, it uses the three selected anchor -points, from one path or several: anchor points selected with Direct Selection, or all the anchor points of a path -selected whole, such as a triangle. The ends of selected segments do not count. The result is `{id, cx, cy, radius}`, -and one undo removes the circle. The circle is not pixel-aligned, even while the document's -[Align New Objects to Pixel Grid](#align-new-objects-to-pixel-grid) is on, so it stays through the points. The command -returns an error and draws nothing when two points are the same or the three lie on one line (twice the triangle's area -at most 10⁻¹⁰ of its longest side squared), when `points` is not three pairs of numbers, and when `points` is left out -and the selection does not hold exactly three anchor points of paths. +`shape.circleThroughPoints {points?: [[x, y], [x, y]] or [[x, y], [x, y], [x, y]]}` draws the circle whose edge passes +through the points, as a live ellipse with the current paint, and selects it. Two points are the ends of a diameter. +Without `points`, it uses the two or three selected anchor points, from one path or several: anchor points selected with +Direct Selection, or all the anchor points of a path selected whole, such as a triangle. The ends of selected segments +do not count. The result is `{id, cx, cy, radius}`, and one undo removes the circle. The circle is not pixel-aligned, +even while the document's [Align New Objects to Pixel Grid](#align-new-objects-to-pixel-grid) is on, so it stays +through the points. The command returns an error and draws nothing when two points are the same or the three lie on +one line (twice the triangle's area at most 10⁻¹⁰ of its longest side squared), when the circle would reach past the +canvas (4,000,000 pt from the origin), when `points` is not two or three pairs of numbers, and when `points` is left +out and the selection does not hold two or three anchor points of paths. + +The Circle tool, after the Ellipse tool in its toolbar group, draws with this command. A drag from one point to +another, or a click on each, draws the circle with the two points as the ends of a diameter. A click on a first point, +then a press on a second point dragged to a third, draws the circle through the three. Shift keeps the second point at +45° steps from the first, measured from General › Constrain Angle. For a circle on two points, Alt rounds the diameter +to the nearest tick of the rulers at the current zoom, in the General unit (every 5 pt at 100% in points); the three +points of a circle through three are not rounded. Each point snaps to Smart Guides. Until +the release, the tool shows the circle as a dashed outline (solid once it is more than 50,000 screen points around) +with its points, a small cross at its center, a line from +the center to each point and, with Measurement Labels on, the diameter by the pointer. Three different points on one +line, or a circle past the canvas, show "Circle too large" by the pointer instead, and the release draws nothing. +Escape, a dropped press, and an edit, Undo or Redo made outside the tool drop the first point. A second press within 3 +screen points of the first point, or one that snaps to it, is a press on it: let go there (a double-click), it places no second point, and +dragged out, it draws the circle on the diameter it drags out. With the Ellipse tool, the first two Shift-clicks place points, and the third draws the circle through the three with this command. After two points the tool previews the circle through them and the pointer as a dashed outline. Once a From 647478f9a622f72edef3760527b172e5bf59aef4 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 17 Nov 2026 13:40:46 -0800 Subject: [PATCH 133/176] Docs: qualify the CMYK JPEG and DeviceCMYK claims for PDF export and import A CMYK JPEG loses its ICC_PROFILE segments in some DeviceCMYK cases, masked CMYK images keep their inks on PDF import, and the none rule needs no CMYK destination of another profile. --- docs/mcp.md | 4 ++-- docs/target-app-parity.md | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/docs/mcp.md b/docs/mcp.md index f0ee9007aa..94e8308d67 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1349,7 +1349,7 @@ the image at, and all paint that one image. A 16-bit PNG that is not resampled, recompressed or converted keeps its 16 bits a sample in PDF 1.5 and later files, and is written at 8 bits in PDF 1.3 and 1.4 files. CMYK images stay CMYK (DeviceCMYK, or ICC-based with the CMYK profile when colours are tagged, as in PDF/X-3 and -PDF/X-4, where an image in the output intent's profile is DeviceCMYK): a CMYK JPEG neither resampled nor recompressed is written unchanged, and the others' ink amounts are +PDF/X-4, where an image in the output intent's profile is DeviceCMYK): a CMYK JPEG neither resampled nor recompressed is written unchanged except that its `ICC_PROFILE` segments are removed when `output.profiles` is `none` (except in PDF/A, and in PDF/X-3 and PDF/X-4 files that do not write CMYK colors as DeviceCMYK) and in PDF/X-3 and PDF/X-4 when they are the CMYK output intent's profile and CMYK colors are DeviceCMYK, and the others' ink amounts are resampled and compressed again (CMYK JPEG or ZIP). `output.conversion` converts them like CMYK colours: `destination` to another CMYK profile or to RGB, `preserveNumbers` (and PDF/X-1a) keeps their numbers in a CMYK destination. `document.pdfSettings` lists the options that differ from the preset and the warnings without writing a file. @@ -1462,7 +1462,7 @@ Imported colours keep their model: DeviceCMYK and CMYK ICC colours stay CMYK (a file painted mostly in CMYK opens as a CMYK document), DeviceGray is Gray, and Separation and DeviceN inks become spot swatches the art links to at its tint (gradient stops too). CMYK images (DeviceCMYK, or ICC-based with four components) keep their ink amounts: a CMYK JPEG as it is, any other as a CMYK TIFF -(masked CMYK images, and ones with 1, 2 or 4 bits per sample, open in RGB with a warning). In a file with a CMYK +(masked CMYK images keep their inks, the mask coming in as an opacity mask; ones with 1, 2 or 4 bits per sample open in RGB with a warning). In a file with a CMYK `/GTS_PDFX` output intent, a DeviceCMYK image carries the output intent's profile, except where it is drawn with a `/DefaultCMYK` in the resources in scope. Placing a CMYK TIFF keeps it CMYK too. `colorMode: "rgb" | "cmyk"` opens any file in that mode instead, its colours converted as `file.documentColorMode` does diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f838798ce9..41c1508015 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1927,8 +1927,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Save as Template writes a PDF-compatible `.ait` as well as a `.vctemplate`, which stays the default: the save panel and the web build's Save as Template dialog list both, and New from Template opens the `.ait` as an untitled document with its layers and art (`file.saveAsTemplate {format: "ait"}`, or a path ending in `.ait`). Save as Template always writes a file named with its template type's extension: `file.saveAsTemplate` saves a path ending in another format's extension (`card.png`) as `card.vctemplate` (or `card.ait`), the desktop save panel does the same with a Save As format's extension typed in it (`card.pdf` is saved as `card.vctemplate`), and `file.saveAs` and `document.save` refuse `ait` with an error that names `file.saveAsTemplate`. A `.ait` is PDF-compatible only: `aiVersion: "7"` is an error for it, and the web build's dialog shows no Version row for it. Exports refuse a `.ait` with an error that names `file.saveAsTemplate`, and `vectorcraft-cli convert in.pdf out.ait` and `run --export out.ait` write the template as `file.saveAsTemplate` does. - - SVG/SVGZ in and out with SVG Options, Preserve Editing, symbols, filters, rich text and physical units (SVG type under a transform or `viewBox` scale opens at the size it draws at, the scale moved into its size, leading, baseline shift and strokes, a stretch, skew or rotation kept as its transform: #396; a top-level group with a clip path, such as a clipped Inkscape layer, opens as a layer with a clipping mask, its name kept: #420; hidden objects written hidden on Save and `convert`, and `data-*` attributes kept as the objects' own data: #522; top-level groups open as layers named from `data-name`, else the id, also when one more group (a transform on all the art, a `<switch>`) wraps them, hidden ones hidden, and a file whose art sits loose under a root `<svg>` with an id (or `data-name`), as one-layer exports write it, opens with its one layer named from it; nested groups stay groups, except the sublayers VectorCraft writes, marked `data-vc-layer`, and Inkscape sublayers, which open as sublayers in their layer's colour: #372); PDF and PDF-compatible `.ai` in and out (layers, with hidden ones kept hidden with their art and nested ones as sublayers, on pages of up to 64 million operators, art whose layer can't be told going to a hidden, non-printing layer rather than showing or printing: #419; strokes kept live, a fill and a stroke of one outline as one object; a type object's stroke written as each glyph's outline stroked back on the type, so it stays one editable object; lines wrapped in a frame (each wrapped line ending in a space, one left edge, leading and font) back as one area type object, left aligned or justified with its paragraph spacing, where laying it out breaks the lines where the file does; glyphs set apart by gaps wider than a space (a barcode's digit groups) keeping their places; layers stacked as the pages mark them even when one first paints on a later page, art ending a layer's marked content or a clip closing in a later layer kept in its own layer, and layers with no art kept empty: #508; art reaching past a plain PDF's page clipped to its crop box, as PDF viewers show it, each such object in a clip group of its own (a PDF-compatible `.ai` opens whole: #675); a `.ai` on its trim boxes with the bleed boxes round them as the document's bleed, as Crop To › Trim opens a PDF (#1266); masks, editable text with type set along a curve coming back as type on a path, each artboard's art on its own page only, an `.ai`'s white page under its layers left out rather than coming in as art, spot colours, presets, security, marks and bleed, ICC output intents, raster effects, subset fonts, PDF/X, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3). CMYK images keep their ink amounts from PDF import (and from placed CMYK TIFFs) to PDF export: a CMYK JPEG passes through unchanged, others stay CMYK (DeviceCMYK, or ICC-based CMYK in PDF/X-3/X-4 when not in the output intent's profile) unless the Output settings convert them; the canvas shows them through the working CMYK profile (#320). Overprint is kept from PDF import (opened, the PDF part of an `.ai`, placed) to PDF export: the graphics state's `/OP` and `/op` become the overprint of fills, strokes and type, so a spot colour over a process colour still overprints; a page whose overprint can't be read for certain knocks out with a note, as does `/OPM 0` being read as nonzero overprint (#1388; hand-written fixtures, `pdf/src/tests/import_overprint.rs`). A masked CMYK image (`/SMask`, `/Mask` or a colour key) keeps its inks too, its alpha coming in as a greyscale opacity mask. - - SVG/SVGZ in and out with SVG Options, Preserve Editing, symbols, filters, rich text and physical units (SVG type under a transform or `viewBox` scale opens at the size it draws at, the scale moved into its size, leading, baseline shift and strokes, a stretch, skew or rotation kept as its transform: #396; a top-level group with a clip path, such as a clipped Inkscape layer, opens as a layer with a clipping mask, its name kept: #420; hidden objects written hidden on Save and `convert`, and `data-*` attributes kept as the objects' own data: #522; top-level groups open as layers named from `data-name`, else the id, also when one more group (a transform on all the art, a `<switch>`) wraps them, hidden ones hidden, and a file whose art sits loose under a root `<svg>` with an id (or `data-name`), as one-layer exports write it, opens with its one layer named from it; nested groups stay groups, except the sublayers VectorCraft writes, marked `data-vc-layer`, and Inkscape sublayers, which open as sublayers in their layer's colour: #372); PDF and PDF-compatible `.ai` in and out (layers, with hidden ones kept hidden with their art and nested ones as sublayers, on pages of up to 64 million operators, art whose layer can't be told going to a hidden, non-printing layer rather than showing or printing: #419; strokes kept live, a fill and a stroke of one outline as one object; a type object's stroke written as each glyph's outline stroked back on the type, so it stays one editable object; lines wrapped in a frame (each wrapped line ending in a space, one left edge, leading and font) back as one area type object, left aligned or justified with its paragraph spacing, where laying it out breaks the lines where the file does; glyphs set apart by gaps wider than a space (a barcode's digit groups) keeping their places; layers stacked as the pages mark them even when one first paints on a later page, art ending a layer's marked content or a clip closing in a later layer kept in its own layer, and layers with no art kept empty: #508; art reaching past a plain PDF's page clipped to its crop box, as PDF viewers show it, each such object in a clip group of its own (a PDF-compatible `.ai` opens whole: #675); a `.ai` on its trim boxes with the bleed boxes round them as the document's bleed, as Crop To › Trim opens a PDF (#1266); masks, editable text with type set along a curve coming back as type on a path, each artboard's art on its own page only, an `.ai`'s white page under its layers left out rather than coming in as art, spot colours, presets, security, marks and bleed, ICC output intents, raster effects, subset fonts, PDF/X, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3). CMYK images keep their ink amounts from PDF import (and from placed CMYK TIFFs and the images in an `.ai` or EPS file's editing data, an alpha channel coming in as a grayscale opacity mask) to PDF export: a CMYK JPEG passes through unchanged, others stay CMYK (DeviceCMYK, or ICC-based CMYK in PDF/X-3/X-4 when not in the output intent's profile) unless the Output settings convert them; the canvas shows them through the working CMYK profile (#320). Overprint is kept from PDF import (opened, the PDF part of an `.ai`, placed) to PDF export: the graphics state's `/OP` and `/op` become the overprint of fills, strokes and type, so a spot colour over a process colour still overprints; a page whose overprint can't be read for certain knocks out with a note, as does `/OPM 0` being read as nonzero overprint (#1388; hand-written fixtures, `pdf/src/tests/import_overprint.rs`). A masked CMYK image (`/SMask`, `/Mask` or a colour key) keeps its inks too, its alpha coming in as a greyscale opacity mask. + - SVG/SVGZ in and out with SVG Options, Preserve Editing, symbols, filters, rich text and physical units (SVG type under a transform or `viewBox` scale opens at the size it draws at, the scale moved into its size, leading, baseline shift and strokes, a stretch, skew or rotation kept as its transform: #396; a top-level group with a clip path, such as a clipped Inkscape layer, opens as a layer with a clipping mask, its name kept: #420; hidden objects written hidden on Save and `convert`, and `data-*` attributes kept as the objects' own data: #522; top-level groups open as layers named from `data-name`, else the id, also when one more group (a transform on all the art, a `<switch>`) wraps them, hidden ones hidden, and a file whose art sits loose under a root `<svg>` with an id (or `data-name`), as one-layer exports write it, opens with its one layer named from it; nested groups stay groups, except the sublayers VectorCraft writes, marked `data-vc-layer`, and Inkscape sublayers, which open as sublayers in their layer's colour: #372); PDF and PDF-compatible `.ai` in and out (layers, with hidden ones kept hidden with their art and nested ones as sublayers, on pages of up to 64 million operators, art whose layer can't be told going to a hidden, non-printing layer rather than showing or printing: #419; strokes kept live, a fill and a stroke of one outline as one object; a type object's stroke written as each glyph's outline stroked back on the type, so it stays one editable object; lines wrapped in a frame (each wrapped line ending in a space, one left edge, leading and font) back as one area type object, left aligned or justified with its paragraph spacing, where laying it out breaks the lines where the file does; glyphs set apart by gaps wider than a space (a barcode's digit groups) keeping their places; layers stacked as the pages mark them even when one first paints on a later page, art ending a layer's marked content or a clip closing in a later layer kept in its own layer, and layers with no art kept empty: #508; art reaching past a plain PDF's page clipped to its crop box, as PDF viewers show it, each such object in a clip group of its own (a PDF-compatible `.ai` opens whole: #675); a `.ai` on its trim boxes with the bleed boxes round them as the document's bleed, as Crop To › Trim opens a PDF (#1266); masks, editable text with type set along a curve coming back as type on a path, each artboard's art on its own page only, an `.ai`'s white page under its layers left out rather than coming in as art, spot colours, presets, security, marks and bleed, ICC output intents, raster effects, subset fonts, PDF/X, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3). CMYK images keep their ink amounts from PDF import (and from placed CMYK TIFFs) to PDF export: a CMYK JPEG passes through with its compressed samples unchanged (its `ICC_PROFILE` segments are removed when `output.profiles` is `none` (except in PDF/A, and in PDF/X-3 and PDF/X-4 files that do not write CMYK colors as DeviceCMYK) and in PDF/X-3 and PDF/X-4 when they are the CMYK output intent's profile and CMYK colors are DeviceCMYK), others stay CMYK (DeviceCMYK, or ICC-based CMYK in PDF/X-3/X-4 when not in the output intent's profile) unless the Output settings convert them; the canvas shows them through the working CMYK profile (#320). Overprint is kept from PDF import (opened, the PDF part of an `.ai`, placed) to PDF export: the graphics state's `/OP` and `/op` become the overprint of fills, strokes and type, so a spot colour over a process colour still overprints; a page whose overprint can't be read for certain knocks out with a note, as does `/OPM 0` being read as nonzero overprint (#1388; hand-written fixtures, `pdf/src/tests/import_overprint.rs`). A masked CMYK image (`/SMask`, `/Mask` or a colour key) keeps its inks too, its alpha coming in as a greyscale opacity mask. + - SVG/SVGZ in and out with SVG Options, Preserve Editing, symbols, filters, rich text and physical units (SVG type under a transform or `viewBox` scale opens at the size it draws at, the scale moved into its size, leading, baseline shift and strokes, a stretch, skew or rotation kept as its transform: #396; a top-level group with a clip path, such as a clipped Inkscape layer, opens as a layer with a clipping mask, its name kept: #420; hidden objects written hidden on Save and `convert`, and `data-*` attributes kept as the objects' own data: #522; top-level groups open as layers named from `data-name`, else the id, also when one more group (a transform on all the art, a `<switch>`) wraps them, hidden ones hidden, and a file whose art sits loose under a root `<svg>` with an id (or `data-name`), as one-layer exports write it, opens with its one layer named from it; nested groups stay groups, except the sublayers VectorCraft writes, marked `data-vc-layer`, and Inkscape sublayers, which open as sublayers in their layer's colour: #372); PDF and PDF-compatible `.ai` in and out (layers, with hidden ones kept hidden with their art and nested ones as sublayers, on pages of up to 64 million operators, art whose layer can't be told going to a hidden, non-printing layer rather than showing or printing: #419; strokes kept live, a fill and a stroke of one outline as one object; a type object's stroke written as each glyph's outline stroked back on the type, so it stays one editable object; lines wrapped in a frame (each wrapped line ending in a space, one left edge, leading and font) back as one area type object, left aligned or justified with its paragraph spacing, where laying it out breaks the lines where the file does; glyphs set apart by gaps wider than a space (a barcode's digit groups) keeping their places; layers stacked as the pages mark them even when one first paints on a later page, art ending a layer's marked content or a clip closing in a later layer kept in its own layer, and layers with no art kept empty: #508; art reaching past a plain PDF's page clipped to its crop box, as PDF viewers show it, each such object in a clip group of its own (a PDF-compatible `.ai` opens whole: #675); a `.ai` on its trim boxes with the bleed boxes round them as the document's bleed, as Crop To › Trim opens a PDF (#1266); masks, editable text with type set along a curve coming back as type on a path, each artboard's art on its own page only, an `.ai`'s white page under its layers left out rather than coming in as art, spot colours, presets, security, marks and bleed, ICC output intents, raster effects, subset fonts, PDF/X, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3). CMYK images keep their ink amounts from PDF import (and from placed CMYK TIFFs and the images in an `.ai` or EPS file's editing data, an alpha channel coming in as a grayscale opacity mask) to PDF export: a CMYK JPEG passes through with its compressed samples unchanged (its `ICC_PROFILE` segments are removed when `output.profiles` is `none` (except in PDF/A, and in PDF/X-3 and PDF/X-4 files that do not write CMYK colors as DeviceCMYK) and in PDF/X-3 and PDF/X-4 when they are the CMYK output intent's profile and CMYK colors are DeviceCMYK), others stay CMYK (DeviceCMYK, or ICC-based CMYK in PDF/X-3/X-4 when not in the output intent's profile) unless the Output settings convert them; the canvas shows them through the working CMYK profile (#320). Overprint is kept from PDF import (opened, the PDF part of an `.ai`, placed) to PDF export: the graphics state's `/OP` and `/op` become the overprint of fills, strokes and type, so a spot colour over a process colour still overprints; a page whose overprint can't be read for certain knocks out with a note, as does `/OPM 0` being read as nonzero overprint (#1388; hand-written fixtures, `pdf/src/tests/import_overprint.rs`). A masked CMYK image (`/SMask`, `/Mask` or a colour key) keeps its inks too, its alpha coming in as a greyscale opacity mask. In imported PDF type, a space glyph the file draws between two words also keeps the next word where the file has it when the gap beside the space is wide, as VectorCraft's own export draws a tracked space: the space gets tracking of its own, and the wrapped lines of a justified paragraph still come back as one area type object when the word gaps on each line are alike (part of #2384). Letter-spaced PDF type, whether set with character spacing (`Tc`) or glyph by glyph, keeps its word spaces and gains none between its letters: the spacing a line's letters share is taken off each gap before a gap reads as a space. That holds on a line that also shows where its words break, with spaces the file draws or gaps wider than the rest; evenly spaced glyphs alone, which could be words of one letter, keep every gap as a space, as do glyphs set more than half an em apart, such as figures in columns. A function-based PDF shading (type 1) whose colour changes along one axis only, as a browser writes a repeating linear gradient, comes in as a linear gradient over its domain, each hard colour change two stops at one offset; one whose colour changes in two directions comes in as its average colour, with a warning. Either paints only over the shading's domain. Both came in as a flat grey that wasn't in the file (#3621). Each such shading is read once per import, and all of them within one budget of 200,000 function evaluations, so a file filling thousands of paths with long functions still opens in about a second (it took minutes); past the budget they come in as their average colour, then grey, with a warning. @@ -2105,7 +2105,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - File › Revert also drops what was started for the content it discards: a file being read for Place, for the place cursor or dropped on the canvas, a bitmap being read for Paste, and a paste waiting at its Swatch Conflict dialog are not placed or pasted in the reverted document, and the status bar says the document was reverted. Edits made while a file is read, a Revert that fails or that a batch rolls back, and a Revert of another document leave the read to finish as before (`crates/ui-egui/src/placing/tests.rs`). - The pixels of a PNG, JPEG, GIF or WebP file that Place decodes to check them are kept in the image store the renderers share, so the canvas's first frame with the placed image draws them without decoding the file again on the UI thread: File › Place, a file dropped on the canvas, a click or drag of the place cursor, `file.place`, and Paste of such an image. A CMYK JPEG is still decoded when it is first drawn (`crates/ui-egui/src/placing.rs`, `crates/render/src/tests.rs`). - A photo whose EXIF orientation turns or flips it (a camera held upright or upside down) is placed and opened upright, as it was taken; the image is stored as it is seen (#4284). A quarter turn swaps the resolution's axes, so the image keeps its physical size. TIFFs read without the image decoder (grayscale with extra channels, CCITT Group 3, CMYK with one plane per ink) follow their Orientation tag too, and a turned CMYK JPEG or TIFF keeps its inks, at the 8 or 16 bits the file has, as a CMYK TIFF. - - PDF export writes a CMYK image that keeps its numbers in an `ICCBased` color space holding, byte for byte, the CMYK profile the image carries (a CMYK TIFF's tag 34675, or a CMYK JPEG's `ICC_PROFILE` APP2 segments) when `output.profiles` is `all` or `taggedSource`, and in PDF/A-2b, PDF/X-3 and PDF/X-4 unless it is `destination`, except in PDF/X-3 and PDF/X-4 when that profile is the CMYK output intent's, or when `none` makes every CMYK color DeviceCMYK (#1954) ([the help page](https://helpx.adobe.com/illustrator/desktop/save-and-export/export-files-to-different-formats/pdf-marks-bleeds-and-color-output-options.html)). This covers a CMYK JPEG embedded as it is, one the Compression settings resample or compress again, a TIFF written again, and an image written with its mask as its soft mask. With `none`, and in PDF/X-1a, the image is DeviceCMYK and a JPEG's own profile is left out, so PDF/X-1a export writes a CMYK JPEG that carries a profile. Pixels the Output settings convert are never tagged with the profile of their old numbers. A profile tags an image only when its size, signature, class, CMYK color space and tag table are well formed and it is at most 16 MiB (VectorCraft's own limit). Transparency in a tagged CMYK document blends in the document's CMYK profile; when the file holds no space of that profile it blends in DeviceCMYK, or keeps its RGB space in PDF/A, and never in an image's own profile (`crates/pdf/src/tests/cmykimages.rs`, `export::writer::tests`). + - PDF export writes a CMYK image that keeps its numbers in an `ICCBased` color space holding, byte for byte, the CMYK profile the image carries (a CMYK TIFF's tag 34675, or a CMYK JPEG's `ICC_PROFILE` APP2 segments) when `output.profiles` is `all` or `taggedSource`, and in PDF/A-2b, PDF/X-3 and PDF/X-4 unless it is `destination`, except in PDF/X-3 and PDF/X-4 when that profile is the CMYK output intent's, or when `none` makes every CMYK color DeviceCMYK, which it does only without a CMYK destination of another profile (#1954) ([the help page](https://helpx.adobe.com/illustrator/desktop/save-and-export/export-files-to-different-formats/pdf-marks-bleeds-and-color-output-options.html)). This covers a CMYK JPEG embedded as it is, one the Compression settings resample or compress again, a TIFF written again, and an image written with its mask as its soft mask. With `none`, and in PDF/X-1a, the image is DeviceCMYK and a JPEG's own profile is left out, so PDF/X-1a export writes a CMYK JPEG that carries a profile. In PDF/X-3 and PDF/X-4 with `none` and a CMYK destination of another profile, a CMYK image that keeps its numbers keeps its own profile, and one the conversion changes is untagged. Pixels the Output settings convert are never tagged with the profile of their old numbers. A profile tags an image only when its size, signature, class, CMYK color space and tag table are well formed and it is at most 16 MiB (VectorCraft's own limit). Transparency in a tagged CMYK document blends in the document's CMYK profile; when the file holds no space of that profile it blends in DeviceCMYK, or keeps its RGB space in PDF/A, and never in an image's own profile (`crates/pdf/src/tests/cmykimages.rs`, `export::writer::tests`). - When the Output settings convert an image's colors ([the help page](https://helpx.adobe.com/illustrator/desktop/save-and-export/export-files-to-different-formats/pdf-marks-bleeds-and-color-output-options.html)), PDF export leaves out an image whose pixels can't be decoded or written in the destination's colors, with the warning "an image couldn't be converted to the Output destination and is missing from the picture", in every standard, instead of writing it in its own colors. This covers a CMYK image with more than 2^26 pixels, the most VectorCraft reads CMYK inks for, and a color image that could be embedded as it is but is more than VectorCraft decodes. A color image whose pixel data can't be read is left out with the warning "an image couldn't be decoded and is missing from the picture", as without a conversion. Gray images, whose pixels are not converted, images in a file that converts no colors, and a gray or RGB image that an sRGB destination would convert from its ICC profile (it keeps the profile, with a warning) are written as before, and an image that can't be written at all still gets the warning that it couldn't be decoded (`crates/pdf/src/tests/cmykimages.rs`, `crates/pdf/src/tests/compression.rs`). - PDF export with `output.profiles` set to `none` (Don't Include Profiles) writes no image with the ICC profile it carries, as [the help page](https://helpx.adobe.com/illustrator/desktop/save-and-export/export-files-to-different-formats/pdf-marks-bleeds-and-color-output-options.html) describes for that setting: gray and RGB PNG, JPEG and TIFF images embedded as they are, resampled or compressed again, and CMYK JPEG images. A JPEG kept as it is loses its `ICC_PROFILE` APP2 segments, its other segments and compressed samples unchanged. PDF/A-2b, PDF/X-3 and PDF/X-4 files keep the profiles they tag images with. Left unset (the default, `"default"`, listed as Default in Save PDF), the setting writes device colors while gray and RGB images keep their profiles, as before; that default is VectorCraft's own rule (`a_set_dont_include_profiles_removes_image_profiles`, `a_set_dont_include_profiles_takes_a_cmyk_jpegs_profile_out`). - PDF import keeps the CMYK profile of an image in a four-component `ICCBased` color space, whose stream holds the profile ([ISO 32000-1, §8.6.5.5](https://opensource.adobe.com/dc-acrobat-sdk-docs/pdfstandards/PDF32000_2008.pdf#page=157)), byte for byte with the image's ink amounts, so PDF export can write the image in it again. A CMYK TIFF carries it as tag 34675, whatever the image's Decode array and bit depth ([ICC.1:2010, Annex B](https://www.color.org/specification/ICC1v43_2010-12.pdf)). A CMYK JPEG kept as it is carries it in `ICC_PROFILE` APP2 segments in place of a profile of its own, with its compressed samples unchanged, and one whose segments can't hold it is stored as a CMYK TIFF carrying it. A profile that isn't well formed, isn't of CMYK colors or is over 16 MiB (VectorCraft's own limit) leaves the image's inks as they are, untagged. DeviceCMYK and DeviceN images carry no profile, and a CMYK TIFF's tag 34675 is read up to 16 MiB. EPS and PostScript import does not keep one: PostScript defines no `ICCBased` profile stream (`crates/pdf/src/tests/cmykimages.rs`, `cmyk::tests`). From d04b8b3f21e24b2aaf2d83f3d9e13da00cea2133 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 17 Nov 2026 13:47:51 -0800 Subject: [PATCH 134/176] Layers: a repeated Locate reveals the row it already highlighted Running Locate Object or Locate Layer again on the row it already highlighted wrote the same highlight, so the Layers panel did not open the layers around the row or scroll to it: a sublayer whose layer was closed since stayed hidden. layer.locate now leaves a one-time request on the document (DocState::locate_reveal) that the panel takes on its next frame, opening the layers around the located row and scrolling to it whether or not the highlight changed. The request is not saved and adds no undo step, and the panel drops it when the row is no longer highlighted. --- crates/engine/src/cmd/layerpanel.rs | 3 +- crates/engine/src/doc_state.rs | 5 +++ crates/engine/src/tests/layers.rs | 7 ++++ crates/ui-egui/src/panels/layers.rs | 8 ++++ crates/ui-egui/src/panels/layers/tests.rs | 47 +++++++++++++++++++++++ docs/mcp.md | 4 +- docs/target-app-parity.md | 2 +- 7 files changed, 72 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/layerpanel.rs b/crates/engine/src/cmd/layerpanel.rs index 4710966004..5400e66728 100644 --- a/crates/engine/src/cmd/layerpanel.rs +++ b/crates/engine/src/cmd/layerpanel.rs @@ -132,7 +132,7 @@ pub fn specs() -> Vec<CommandSpec> { "Locate Object", ["Window", "Layers"], None, - "{id?, layersOnly?} (default: the last selected object) highlight the object's row; the Layers panel opens the layers around it and scrolls to it → {id, ancestry: [layer…, id]}. layersOnly (default false; the panel sends true while Show Layers Only is on, as Locate Layer) highlights the innermost layer or sublayer holding the object instead, or a layer id itself → {id: layer, objectId, ancestry: [layer…]}", + "{id?, layersOnly?} (default: the last selected object) highlight the object's row; the Layers panel opens the layers around it and scrolls to it, also when the row was already highlighted →{id, ancestry: [layer…, id]}. layersOnly (default false; the panel sends true while Show Layers Only is on, as Locate Layer) highlights the innermost layer or sublayer holding the object instead, or a layer id itself → {id: layer, objectId, ancestry: [layer…]}", has_doc, locate ), @@ -446,6 +446,7 @@ fn locate(s: &mut Session, p: &Value) -> Result<Value> { } let row = ancestry.last().copied().ok_or(EngineError::NoNode(id))?; st.layer_rows = vec![row]; + st.locate_reveal = Some(row); st.revision += 1; let ancestry: Vec<u64> = ancestry.iter().map(|i| i.0).collect(); Ok(if layers_only { json!({ "id": row.0, "objectId": id.0, "ancestry": ancestry }) } else { json!({ "id": id.0, "ancestry": ancestry }) }) diff --git a/crates/engine/src/doc_state.rs b/crates/engine/src/doc_state.rs index 9cbdfb6827..90b2b7db23 100644 --- a/crates/engine/src/doc_state.rs +++ b/crates/engine/src/doc_state.rs @@ -25,6 +25,10 @@ pub struct DocState { /// Panel state, not art selection: not saved, not undoable (`layer.setCurrent`, /// `layer.highlight`). pub layer_rows: Vec<NodeId>, + /// The row the last Locate Object or Locate Layer (`layer.locate`) highlighted, until the + /// Layers panel takes it: the panel opens the layers around that row and scrolls to it, also + /// when the row was already highlighted. Panel state: not saved, not undoable. + pub locate_reveal: Option<NodeId>, /// The variable highlighted in the Variables panel: what its Delete, Options… and Select /// Bound Object act on. Panel state, not art selection: not saved, not undoable /// (`variable.highlight`). A name, so renaming a variable moves the highlight with it. @@ -318,6 +322,7 @@ impl DocState { revision: 1, active_layer, layer_rows: vec![], + locate_reveal: None, variables_highlight: None, variables_sort: Default::default(), isolation: None, diff --git a/crates/engine/src/tests/layers.rs b/crates/engine/src/tests/layers.rs index 186c5de6c1..f70f26ba1e 100644 --- a/crates/engine/src/tests/layers.rs +++ b/crates/engine/src/tests/layers.rs @@ -914,6 +914,12 @@ fn locate_layer_highlights_the_layer_holding_the_object() { let r = run(&mut s, "layer.locate", json!({"layersOnly": true})); assert_eq!(r, json!({"id": sub.0, "objectId": b.0, "ancestry": [layer.0, sub.0]}), "the group's sublayer"); assert_eq!(s.doc().unwrap().highlighted_rows(), vec![sub]); + assert_eq!(s.doc().unwrap().locate_reveal, Some(sub), "the Layers panel reveals the located row"); + s.doc_mut().unwrap().locate_reveal = None; + let undo = s.doc().unwrap().history.undo.len(); + run(&mut s, "layer.locate", json!({"layersOnly": true})); + assert_eq!(s.doc().unwrap().locate_reveal, Some(sub), "again for a row already highlighted"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo, "no undo step"); assert_eq!(run(&mut s, "layer.locate", json!({"id": c.0, "layersOnly": true}))["id"], layer.0, "art directly in a layer"); assert_eq!(s.doc().unwrap().highlighted_rows(), vec![layer]); let r = run(&mut s, "layer.locate", json!({"id": sub.0, "layersOnly": true})); @@ -924,6 +930,7 @@ fn locate_layer_highlights_the_layer_holding_the_object() { for p in [json!({"id": b.0, "layersOnly": "yes"}), json!({"id": 999_999, "layersOnly": true})] { assert!(s.execute("layer.locate", &p).is_err(), "{p}"); assert_eq!(s.doc().unwrap().highlighted_rows(), vec![g], "{p}"); + assert_eq!(s.doc().unwrap().locate_reveal, Some(g), "{p}"); } run(&mut s, "select.none", json!({})); assert!(s.execute("layer.locate", &json!({"layersOnly": true})).is_err(), "nothing selected"); diff --git a/crates/ui-egui/src/panels/layers.rs b/crates/ui-egui/src/panels/layers.rs index 6e8c2648fa..293c12460a 100644 --- a/crates/ui-egui/src/panels/layers.rs +++ b/crates/ui-egui/src/panels/layers.rs @@ -221,6 +221,14 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { reveal = rows.first().copied(); ui.data_mut(|d| d.insert_temp(key("seen"), rows.clone())); } + // Locate Object or Locate Layer (`layer.locate`): the located row is revealed each time, also + // when it was already highlighted and a layer around it was closed since or the list scrolled + // away. A request for a row no longer highlighted is dropped. + let locate = app.session.active_mut().and_then(|st| st.locate_reveal.take()).filter(|id| rows.contains(id)); + if let Some(id) = locate { + open_around(app, &doc, &[id]); + reveal = Some(id); + } let highlighted = reveal.is_some(); // A new active layer (a canvas selection highlights no row): reveal it too, unless a row // highlighted in the panel holds the view. diff --git a/crates/ui-egui/src/panels/layers/tests.rs b/crates/ui-egui/src/panels/layers/tests.rs index 11d0d70842..e53afe4d16 100644 --- a/crates/ui-egui/src/panels/layers/tests.rs +++ b/crates/ui-egui/src/panels/layers/tests.rs @@ -2177,6 +2177,53 @@ fn with_show_layers_only_locate_object_becomes_locate_layer() { assert!(has(&row_menu, "Locate Layer") && !has(&row_menu, "Locate Object"), "{row_menu:?}"); } +/// Locate Layer or Locate Object run again on the row it already highlighted reveals that row +/// again: the layers around it that were closed since open, once per Locate. +#[test] +fn a_repeated_locate_reveals_the_row_it_already_highlighted() { + let (mut app, [layer, sub, g, b, _, _]) = nested(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let draw = |app: &mut VectorcraftApp| { + super::super::tests_appearance::frame_events(&ctx, app, vec![], show).into_iter().map(|(t, _)| t.trim().to_string()).collect::<Vec<_>>() + }; + let open = |app: &VectorcraftApp, id: NodeId| app.session.active().unwrap().layers_open.contains(id); + let close = |app: &mut VectorcraftApp, ids: &[NodeId]| { + for id in ids { + app.session.active_mut().unwrap().layers_open.set(*id, false); + } + }; + app.session.execute("select.set", &json!({"ids": [b.0]})).unwrap(); + + // Locate Layer: the sublayer stays highlighted while its layer is closed, and Locate Layer again opens it. + app.ui.layers_panel.layers_only = true; + app.session.execute("layer.locate", &json!({"layersOnly": true})).unwrap(); + draw(&mut app); + assert_eq!(rows_of(&app), vec![sub]); + close(&mut app, &[layer]); + assert!(!draw(&mut app).iter().any(|t| t == "Sub"), "the closed layer hides the sublayer"); + app.session.execute("layer.locate", &json!({"layersOnly": true})).unwrap(); + assert!(draw(&mut app).iter().any(|t| t == "Sub"), "the sublayer's row shows again"); + assert!(open(&app, layer), "the layer around the sublayer opens again"); + assert_eq!(rows_of(&app), vec![sub]); + // Once per Locate: a later frame leaves a layer closed after that alone. + close(&mut app, &[layer]); + draw(&mut app); + assert!(!open(&app, layer), "a frame without a Locate opens nothing"); + + // Locate Object: the same for the object's row inside a closed sublayer and group. + app.ui.layers_panel.layers_only = false; + app.session.execute("layer.locate", &json!({})).unwrap(); + draw(&mut app); + assert_eq!(rows_of(&app), vec![b]); + close(&mut app, &[sub, g]); + draw(&mut app); + app.session.execute("layer.locate", &json!({})).unwrap(); + draw(&mut app); + assert!(open(&app, layer) && open(&app, sub) && open(&app, g), "the layers and group around the object open again"); + assert_eq!(rows_of(&app), vec![b]); +} + /// ≡ › Save Selection lists the saved selections: choosing one recalls it, Update Selection /// makes it hold the selected objects, and Save Selection… opens the name dialog. #[test] diff --git a/docs/mcp.md b/docs/mcp.md index 9fde9c1887..de60eae1d0 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5429,8 +5429,8 @@ and `layerRows`, the rows highlighted in the panel. locked or nested art included, dialog `confirm` asks "Delete this layer and its artwork?" for one layer, else "Delete the selected items and their artwork?"; OK deletes the rows it asked about in that document, one undo step, and Cancel keeps them; an empty layer, a layer with only guides, and groups or objects alone are deleted at once), - `layer.locate {id?, layersOnly?}` (highlights the selected object's row; the panel opens the rows around it; - `layersOnly: true`, which the panel sends while Show Layers Only is on, as Locate Layer, highlights the innermost + `layer.locate {id?, layersOnly?}` (highlights the selected object's row; the panel opens the rows around it and + scrolls to it on every call, also when the row was already highlighted; `layersOnly: true`, which the panel sends while Show Layers Only is on, as Locate Layer, highlights the innermost layer or sublayer holding the object instead, or a layer `id` itself, and returns `{id, objectId, ancestry}`) and `layer.clippingMask.toggle`. - **Panel menu**: `layer.duplicate {ids?}`, `layer.merge {ids?}` (into the layer highlighted last, keeping the diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index b26069f0f0..0dead1ac58 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1391,7 +1391,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Layer Options for several highlighted rows shows the first row's settings, and OK changes only the settings set in the dialog: each row keeps its own color, Template, Lock, Show, Print, Preview and Dim Images otherwise (`crates/ui-egui/src/dialogs/layer_options.rs` tests). As VectorCraft's own rule, a layer color (`layer.setProps`, `layer.new`, `layer.newSublayer`) or a Live Paint Gap Preview Color (`livePaint.gapOptions`) given as a hex color with an alpha part (`#rrggbbaa` or `#rgba`) is an error and changes nothing, instead of being set without its alpha. Regression tests: `a_layer_color_with_an_alpha_part_is_refused` in `crates/engine/src/tests/layers.rs` and `a_gap_color_with_an_alpha_part_is_refused` in `crates/engine/src/tests/build.rs`. Panel Options › Locate Selected Objects (beyond Illustrator, off by default): when the last selected object changes on the canvas or by a command, the panel opens the layers and groups around it and scrolls to its row, as Locate Object does, without highlighting the row; when Show Layers Only, a search or the filter leaves the object without a row, the panel opens no rows for it and scrolls as with the option off. - With Panel Options › Show Layers Only on, Locate Object is named Locate Layer and highlights the layer that holds the selected object instead of the object's own row, which that mode does not list (help page: https://helpx.adobe.com/illustrator/desktop/manage-layers/create-and-organize-layers/locate-objects-in-the-layers-panel.html). As VectorCraft's own rules, the bottom bar's button and a row's menu are renamed too, the innermost sublayer holding the object is the one highlighted, a layer row locates itself, and the panel opens the layers around it (`locate_layer_highlights_the_layer_holding_the_object` in `crates/engine/src/tests/layers.rs`, `with_show_layers_only_locate_object_becomes_locate_layer` in `crates/ui-egui/src/panels/layers/tests.rs`). + With Panel Options › Show Layers Only on, Locate Object is named Locate Layer and highlights the layer that holds the selected object instead of the object's own row, which that mode does not list (help page: https://helpx.adobe.com/illustrator/desktop/manage-layers/create-and-organize-layers/locate-objects-in-the-layers-panel.html). As VectorCraft's own rules, the bottom bar's button and a row's menu are renamed too, the innermost sublayer holding the object is the one highlighted, a layer row locates itself, and the panel opens the layers around it. Locate Object or Locate Layer run again on the row it already highlighted opens the layers around that row again and scrolls to it, VectorCraft's own rule (`locate_layer_highlights_the_layer_holding_the_object` in `crates/engine/src/tests/layers.rs`, `with_show_layers_only_locate_object_becomes_locate_layer` and `a_repeated_locate_reveals_the_row_it_already_highlighted` in `crates/ui-egui/src/panels/layers/tests.rs`). - **Drawing aids:** Smart Guides and snapping (moving, with the Selection, Group Selection or Direct Selection tool, and resizing by the bounding-box handles with the Selection or Free Transform tool, Shift and Alt too: the dragged corner or side lands on the other objects' anchors and centres ("anchor", "center") or lines up with their edges and centres (a line and "align"); with Smart Guides › Spacing Guides, a moved selection that lines up with nothing along an axis lands as far from its neighbour as two other objects of its row or column are apart, or halfway between its two neighbours, the equal gaps marked; with View › Snap to Grid on, a moved selection lands on the grid instead, by whichever of its edges is nearest a gridline on each axis (the center does not snap), #740, #1816; the Rotate, Scale, Shear and Reflect tools drag from the anchor they grab and snap the pointer the same way, so a corner dragged onto another object's anchor scales exactly onto it, #482; anchors dragged with Direct Selection: the one pressed on lands on other anchors, its own path's that stay put among them, on path segments or in line with them, the others following, Shift keeps 45° steps, and with Smart Guides off Snap to Point pulls it onto anchors; the Artboard tool snaps artboards, and their bleed, to other artboards, bleeds and art, the grid or whole pixels while moving, copying and resizing them, and the Transform panel shows and edits the active artboard's X/Y/W/H; drawn points, #506: hovering shows where the press goes, the point lands on the other objects' anchors, centres and paths ("anchor", "center", "path") or lines up with their anchors, edges and centres ("align"), the Pen's on the path being drawn too, near a construction guide through the anchor before it on that guide (Preferences › Smart Guides › Construction Guides and Angles), and with Shift kept to its 45° step or a square's diagonal it slides along that way into line; the targets are gathered once per document state, from the art in the window, and the anchors, centres and lines near the pointer are found by bisection, so hovering never rescans the document), guides dragged out of the rulers (#451: they snap as moved guides do, Shift to the ruler's ticks; with the Artboard tool they are artboard guides, which run across their artboard only and move, copy and delete with it, `guide.add {artboard}`) that the Selection, Direct Selection and Group Selection tools then pick and drag (#414: the selected guides highlight and move together, Alt copies them, Shift snaps the dragged one to the ticks, otherwise it snaps to pixels, the grid or the edges, centres (so the sides' midpoints) and anchors of the art and the artboards, or with Smart Guides off Snap to Point pulls it onto anchors; Shift-clicked they join the selected art, and Shift-added art keeps them, so guides and art are selected together in either order, Delete then deleting both in one step; the arrow keys nudge them, Delete deletes them, dragging one back onto its ruler deletes it, Lock Guides and Hide Guides leave them alone; `guide.list`, `guide.select`, `guide.move` and `guide.remove` reach agents), a right-click on either ruler or the origin box to pick the document's units (the current one checked; `document.setUnits`, one undo step, #528), and Draw Normal / Behind / Inside modes. Smart Guides: a point drawn with the Pen or a shape tool, and an anchor dragged with Direct Selection, snaps to where paths and ruler guides cross, labelled "intersect" (#1658, part of #1602; a moved selection's own anchors don't, except the anchor the Selection tool grabbed it by). A selection the Selection tool grabs by one of its anchors snaps that anchor onto the other objects' paths ("path"), and where a path crosses another path or a ruler guide ("intersect"), in the order Direct Selection uses for a dragged anchor; when the anchor lands on a path, the selection's bounds do not also line up with other objects (#7411). The archived 2007 [user guide](https://help.adobe.com/archive/en_US/illustrator/cs3/illustrator_cs3_help.pdf#page=55) (page 49) says Smart Guides align the pointer of a moved object to existing paths. Snapping onto paths only when the selection was grabbed by an anchor is VectorCraft's own rule; a selection grabbed anywhere else still lines its bounds up. Tests: `select::tests::a_move_grabbed_by_an_anchor_lands_it_on_another_path`, `a_move_grabbed_by_an_anchor_lands_it_where_paths_cross` and `a_move_grabbed_by_an_anchor_lands_it_where_a_path_crosses_a_ruler_guide`. With Smart Guides › Measurement Labels on, the Line Segment tool labels the segment being drawn with its distance, angle and X and Y offsets (`D`, `Angle`, `dX`, `dY`), and the Pen, Curvature and Smart Pen tools label their rubber band the same way when Enable Rubber Band is on (#2983). A move that Shift keeps level, upright or diagonal stays on that line when it snaps, with the Selection, Group Selection or Direct Selection tool. It slides along the line until the selection lands on the grid or on whole pixels, lines up with the other objects or is spaced evenly with them, or until the line passes an anchor or crosses a ruler guide near the point the selection was grabbed by. A level or upright move snaps along its own axis only. Snap to Last Location: with Smart Guides on and Preferences › Smart Guides › Snap to Last Location on (off by default, VectorCraft's own choice), a selection moved by dragging with the Selection, Group Selection or Direct Selection tool, Shift too, goes back to where the move began while it is within Snapping Tolerance of it, labeled "last location"; an Alt copy is not pulled back onto its original, and with View › Snap to Grid or Snap to Pixel on the move snaps to the grid or to whole pixels instead (`prefs.set` key `snapToLastLocation`). The public [Smart Guides options](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/smart-guides-options.html) page lists the option as snapping objects back to their previous position; the distance, the label, the copy rule and the grid and pixel rule are VectorCraft's own. Tests: `select::tests::snap_to_last_location_puts_a_move_back_where_it_began`, `select::tests::snap_to_pixel_wins_over_snap_to_last_location`, `direct::tests::snap_to_last_location_puts_a_path_moved_by_its_anchor_back`, `direct::tests::snap_to_pixel_wins_over_snap_to_last_location_for_a_path_moved_by_its_anchor`, `tests_prefs::snap_to_last_location_puts_a_dragged_square_back`. From 7142cca3e9d1acc7084d2712b54c8447db32ade5 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 17 Nov 2026 13:47:31 -0800 Subject: [PATCH 135/176] .ai save: parse each art style text once per save Saving a .ai file checks every art style it writes by reading it back with the reader's style parser. Each object check parsed its style text twice (once to read the appearance and once for the outline check), a brushed style a third time, and a linked object first searched every written style by name and copied its text. With thousands of objects on a few styles, the same text was parsed tens of thousands of times. The writer now keeps each style text's parse for the whole save, a text the reader does not parse included, and reads it on each object: the object's own gradient, the outline check, the brush check and the appearance comparison still run per object. The own gradient is applied to a copy of the parse, and that copy is the compared appearance; the outline and brush checks read the kept parse. Panel styles are found by their place in the written list. The output is unchanged. - import: parse_art_style, read_parsed_style and parsed_moves_with split the parse from the reading; BrushesRead::style_reads takes the parse. - Tests: the parse count of a save does not grow with the number of objects on the same styles; the program, header, warnings and private data are the same as with a parse at every check; one parse read on two objects gives each its own gradient. An ignored test times the save of 40 graphic styles, 20,000 linked rectangles and 5,000 paths with their own Outer Glow. --- crates/eps/src/ai_editing/tests.rs | 160 ++++++++++++++++++++ crates/eps/src/ai_editing/writer.rs | 2 +- crates/eps/src/ai_editing/writer/brushes.rs | 4 +- crates/eps/src/ai_editing/writer/styles.rs | 77 +++++++--- crates/eps/src/import.rs | 10 +- crates/eps/src/import/ai.rs | 6 +- crates/eps/src/import/ai/brush.rs | 16 +- crates/eps/src/import/ai/read.rs | 2 +- crates/eps/src/import/ai/read/ops.rs | 41 +++-- crates/eps/src/import/ai/style.rs | 8 + crates/eps/src/import/ai/style/tests.rs | 12 +- 11 files changed, 282 insertions(+), 56 deletions(-) diff --git a/crates/eps/src/ai_editing/tests.rs b/crates/eps/src/ai_editing/tests.rs index 4a261f2582..3ddc8636c8 100644 --- a/crates/eps/src/ai_editing/tests.rs +++ b/crates/eps/src/ai_editing/tests.rs @@ -7150,6 +7150,166 @@ fn art_styles_are_written_in_their_forms() { assert!(!two.contains("%AI9_BeginArtStyleList"), "{two}"); } +/// A document with `k` of each object a save checks a style on, on rows 20 pt apart: objects linked +/// to a new document's graphic style and to one of the document's own, objects with the same drop +/// shadow, two objects with different gradients under a drop shadow on the same outline, and paths +/// with a Calligraphic brush and a drop shadow. +fn checked_styles_document(k: usize) -> Document { + let mut doc = Document::new(400.0, 20.0 * k as f64 + 20.0); + vectorcraft_brush::store(&mut doc, &brush_library()); + let lit_ap = Appearance { effects: vec![drop_shadow()], ..Appearance::basic(solid(Color::rgb(0.2, 0.5, 0.9)), solid(Color::BLACK), 1.0) }; + let mut lit = vectorcraft_doc::GraphicStyle::new("Lit", lit_ap); + lit.id = 40; + doc.graphic_styles.push(lit); + let ramp = |c: Color| { + let stops = vec![GradientStop::new(0.0, Color::WHITE), GradientStop::new(1.0, c)]; + Paint::Gradient(Box::new(GradientPaint::new(Gradient { kind: GradientKind::Linear, stops, ..Gradient::default() }))) + }; + for i in 0..k { + let y = 10.0 + 20.0 * i as f64; + for (x, name) in [(10.0, "Sunshine"), (60.0, "Lit")] { + let g = doc.graphic_style(name).unwrap().clone(); + let ap = g.appearance_on(&Node::group(vectorcraft_doc::NodeId(0), vec![])).into_owned(); + let mut n = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(x, y, x + 40.0, y + 15.0)), ap); + n.extras_mut().graphic_style = Some(g.id); + put(&mut doc, n); + } + let n = styled_rect(&mut doc, "Shadowed", Rect::new(110.0, y, 150.0, y + 15.0), solid(Color::BLACK), Paint::None, vec![drop_shadow()]); + put(&mut doc, n); + for c in [Color::BLACK, Color::rgb(0.9, 0.2, 0.1)] { + let n = styled_rect(&mut doc, "Graded", Rect::new(160.0, y, 200.0, y + 15.0), ramp(c), Paint::None, vec![drop_shadow()]); + put(&mut doc, n); + } + let stroke = Appearance::basic(Paint::None, solid(Color::rgb(1.0, 0.0, 0.0)), 2.0); + let mut line = Node::path(doc.alloc_id(), shapes::line((210.0, y).into(), (380.0, y + 10.0).into()), stroke); + line.appearance.stroke_mut().unwrap().brush = Some("Nib".into()); + line.appearance.effects = vec![drop_shadow()]; + put(&mut doc, line); + } + doc +} + +/// A save parses each style text once, however many objects it checks with it: the panel's styles, +/// objects linked to them, objects with the same style of their own and brushed paths. Each object +/// is still checked: every linked object keeps its link, each graded object reads back with its own +/// gradient, and each brushed path with its brush. +#[test] +fn a_save_parses_each_style_text_once() { + let parses = |doc: &Document| { + crate::import::ART_STYLE_PARSES.set(0); + let out = export_ai_editing(doc, &opts()).unwrap(); + (crate::import::ART_STYLE_PARSES.get(), String::from_utf8(out.program).unwrap().replace("\r\n", "\n")) + }; + let (one, _) = parses(&checked_styles_document(1)); + let doc = checked_styles_document(4); + let (four, p) = parses(&doc); + assert!(one > 0); + assert_eq!(four, one, "parses with one of each object and with four"); + for linked in ["1 (Sunshine) XW\n", "1 (Lit) XW\n"] { + assert_eq!(p.matches(linked).count(), 4, "{linked}"); + } + let back = read_back(&doc); + let kids = back.layers[0].children().unwrap(); + let paints: Vec<&Paint> = + kids.iter().filter(|n| n.name.as_deref() == Some("Graded")).filter_map(|n| n.appearance.fill().map(|f| &f.paint)).collect(); + let graded: Vec<&Paint> = doc.layers[0] + .children() + .unwrap() + .iter() + .filter(|n| n.name.as_deref() == Some("Graded")) + .map(|n| &n.appearance.fill().unwrap().paint) + .collect(); + assert_eq!(paints.len(), 8); + for (got, want) in paints.iter().zip(&graded) { + let (Paint::Gradient(got), Paint::Gradient(want)) = (got, want) else { panic!("a gradient fill: {got:?}") }; + assert_eq!(got.gradient.stops, want.gradient.stops); + } + let brushed: Vec<&Arc<Node>> = kids.iter().filter(|n| n.appearance.stroke().and_then(|s| s.brush.as_deref()) == Some("Nib")).collect(); + assert_eq!(brushed.len(), 4); + assert!(brushed.iter().all(|n| n.appearance.effects.len() == 1 && matches!(n.kind, NodeKind::Path { .. }))); +} + +/// A save that keeps each style text's parse writes the same program, header, warnings and private +/// data as one that parses the text again at every check. +#[test] +fn a_save_writes_the_same_with_each_style_text_parsed_once() { + let save = |doc: &Document, reparse: bool| { + writer::REPARSE.set(reparse); + let out = export_ai_editing(doc, &opts()).unwrap(); + let private = private_data(doc, &opts()).unwrap(); + writer::REPARSE.set(false); + (out.program, out.header, out.warnings, private.0.data, private.1) + }; + for doc in [styles_document(), checked_styles_document(4), brushes_document()] { + let (once, again) = (save(&doc, false), save(&doc, true)); + assert!(once == again, "{}", String::from_utf8_lossy(&once.0)); + } +} + +/// The CPU time of saving a document with 40 graphic styles, 20,000 rectangles linked to them in +/// turn and 5,000 paths with an Outer Glow of their own in 20 settings, with each style text's parse +/// kept and with the text parsed again at every check: the median of 7 runs of each, alternating. +/// Run with `cargo test -p vectorcraft-eps --lib -- --ignored --nocapture style_parse_time`. +#[test] +#[ignore = "timing; run by hand"] +fn style_parse_time() { + let mut doc = Document::new(2000.0, 2000.0); + let mut ids = vec![]; + for i in 0..40u32 { + let shade = i as f32 / 40.0; + let mut ap = Appearance::basic(solid(Color::rgb(shade, 0.4, 1.0 - shade)), solid(Color::BLACK), 1.0 + f64::from(i % 4)); + let round = fx("stylize.roundCorners", serde_json::json!({"radius": 2.0 + f64::from(i % 5)})); + ap.effects = vec![fx("stylize.dropShadow", serde_json::json!({"x": f64::from(i % 7), "y": 4.0})), round]; + let mut g = vectorcraft_doc::GraphicStyle::new(format!("Style {i}"), ap); + g.id = 100 + i; + ids.push(g.id); + doc.graphic_styles.push(g); + } + for i in 0..20_000usize { + let g = doc.graphic_style_by_id(ids[i % ids.len()]).unwrap().clone(); + let ap = g.appearance_on(&Node::group(vectorcraft_doc::NodeId(0), vec![])).into_owned(); + let (x, y) = ((i % 200) as f64 * 10.0, (i / 200) as f64 * 10.0); + let mut n = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(x, y, x + 8.0, y + 8.0)), ap); + n.extras_mut().graphic_style = Some(g.id); + put(&mut doc, n); + } + for i in 0..5_000usize { + let glow = fx("stylize.outerGlow", serde_json::json!({"blur": 1.0 + (i % 20) as f64})); + let (x, y) = ((i % 100) as f64 * 20.0, 1000.0 + (i / 100) as f64 * 20.0); + let n = styled_rect(&mut doc, "Glow", Rect::new(x, y, x + 15.0, y + 15.0), solid(Color::BLACK), Paint::None, vec![glow]); + put(&mut doc, n); + } + // The CPU time this thread has run, in nanoseconds: Linux's scheduler statistics, else the clock. + let start = std::time::Instant::now(); + let cpu = || { + std::fs::read_to_string("/proc/thread-self/schedstat") + .ok() + .and_then(|s| s.split_whitespace().next().and_then(|n| n.parse::<u64>().ok())) + .unwrap_or_else(|| u64::try_from(start.elapsed().as_nanos()).unwrap_or(u64::MAX)) + }; + let mut times: [Vec<u64>; 2] = [vec![], vec![]]; + let mut parses = [0, 0]; + let mut outputs: [Vec<u8>; 2] = [vec![], vec![]]; + for _ in 0..7 { + for (k, reparse) in [(0, true), (1, false)] { + writer::REPARSE.set(reparse); + crate::import::ART_STYLE_PARSES.set(0); + let t = cpu(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + times[k].push(cpu() - t); + parses[k] = crate::import::ART_STYLE_PARSES.get(); + outputs[k] = out.program; + } + } + writer::REPARSE.set(false); + assert!(outputs[0] == outputs[1]); + for (k, label) in [(0, "parsed at every check"), (1, "parsed once")] { + times[k].sort_unstable(); + let ms: Vec<String> = times[k].iter().map(|t| format!("{:.1}", *t as f64 / 1e6)).collect(); + println!("{label}: median {:.1} ms CPU, {} parses, runs {}", times[k][3] as f64 / 1e6, parses[k], ms.join(" ")); + } +} + /// Objects whose appearance the reader wouldn't read with their style are written as their /// drawn look, with the warnings they were written with before; graphic styles it wouldn't read /// are left out with a warning; and a document without effects or styles of its own has no art diff --git a/crates/eps/src/ai_editing/writer.rs b/crates/eps/src/ai_editing/writer.rs index f268bcbaf6..39c3157350 100644 --- a/crates/eps/src/ai_editing/writer.rs +++ b/crates/eps/src/ai_editing/writer.rs @@ -37,7 +37,7 @@ pub(super) use envelopes::ENVELOPES; pub(super) use meshes::MESHES; pub(super) use styles::{LARGE_CANVAS_STYLES, style_links, styled_definitions, styled_objects}; #[cfg(test)] -pub(super) use styles::{PANEL_EMPTY, PANEL_STYLES, STYLE_LINKS, WARPED_IMAGES, same_appearance}; +pub(super) use styles::{PANEL_EMPTY, PANEL_STYLES, REPARSE, STYLE_LINKS, WARPED_IMAGES, same_appearance}; pub(super) use texts::wraps_held; pub(super) use images::PAYLOAD; diff --git a/crates/eps/src/ai_editing/writer/brushes.rs b/crates/eps/src/ai_editing/writer/brushes.rs index 986d60ef9c..239668a09a 100644 --- a/crates/eps/src/ai_editing/writer/brushes.rs +++ b/crates/eps/src/ai_editing/writer/brushes.rs @@ -565,14 +565,14 @@ impl Writer<'_> { /// Does the reader read the brushed strokes of style text `text` with their brushes on them? pub(super) fn brushed_style_reads(&mut self, text: &str) -> bool { self.brush_set(); - let section = super::styles::known_style("x", text); + let Some(parsed) = self.styles.parsed.get(text) else { return false }; let written = &self.brush_set.written; let read = self.brush_set.read.get_or_insert_with(|| { let brushes: Vec<(&str, &str, &str, Option<&Node>)> = written.iter().map(|b| (b.plugin, b.brush.name.as_str(), b.params.as_str(), b.art.as_ref())).collect(); crate::import::BrushesRead::new(&brushes) }); - read.style_reads(section.as_bytes(), "x") + read.style_reads(parsed) } /// The brushes' art in a non-printing block, then the brush manager's order and the brushes in diff --git a/crates/eps/src/ai_editing/writer/styles.rs b/crates/eps/src/ai_editing/writer/styles.rs index 50aa4df931..0af8e313fa 100644 --- a/crates/eps/src/ai_editing/writer/styles.rs +++ b/crates/eps/src/ai_editing/writer/styles.rs @@ -2,9 +2,9 @@ //! object itself on `%_` lines and `1 (style) XW`; the styles they name and the Graphic Styles //! panel's styles in `%AI9_BeginArtStyles`, and the panel's order in `%AI9_BeginArtStyleList` (see //! [`crate::ai_editing`] for the form). Each style is read back before it is written -//! ([`crate::import::read_art_style`]: the `.ai` reader's style parser and its reading of a graphic +//! ([`crate::import::read_parsed_style`]: the `.ai` reader's style parser and its reading of a graphic //! style, with the object's own gradient): one that reads back differently is not written, and the -//! object is written as its drawn look alone. +//! object is written as its drawn look alone. Each style text is parsed once per save ([`Parsed`]). use std::collections::{HashMap, HashSet}; use std::fmt::Write; @@ -126,7 +126,7 @@ fn candidate(n: &Node) -> bool { /// Is `n` an image, embedded or linked, without an opacity mask whose appearance is one Warp, with /// no fills or strokes that paint and no effects on them: an image the reader reads with its Warp -/// live ([`crate::import::read_art_style`]'s `image_warp`)? +/// live ([`crate::import::read_parsed_style`]'s `image_warp`)? fn warped_image(n: &Node) -> bool { matches!(n.kind, NodeKind::Image(_)) && n.extras().mask.is_none() @@ -162,8 +162,8 @@ fn plain_member(n: &Node) -> bool { pub(in crate::ai_editing) struct Styles { /// Every style, in the order written: its name and text. known: Vec<(String, String)>, - /// The panel's styles written, by the graphic style's id. - panel: HashMap<u32, String>, + /// The panel's styles written, by the graphic style's id: each one's place in [`Self::known`]. + panel: HashMap<u32, usize>, /// The panel's styles written, in its order. listed: Vec<String>, /// The names styles have, and the name of each object style by its text. @@ -172,6 +172,35 @@ pub(in crate::ai_editing) struct Styles { next_anon: u64, /// How many objects were written with the graphic style they are linked to. pub(super) links_written: usize, + /// Every style text checked so far, as the reader parses it. + pub(super) parsed: Parsed, +} + +/// Style texts as the reader parses them ([`crate::import::parse_art_style`]), each parsed once +/// however many styles and objects are checked with it; a text the reader doesn't parse is kept +/// as `None`. +#[derive(Default)] +pub(super) struct Parsed(HashMap<String, Option<crate::import::ParsedStyle>>); + +#[cfg(test)] +thread_local! { + /// While set on this thread, [`Parsed`] keeps nothing: every check parses its style text again. + pub(in crate::ai_editing) static REPARSE: std::cell::Cell<bool> = const { std::cell::Cell::new(false) }; +} + +impl Parsed { + /// Style text `text` as the reader parses it (`None` when it doesn't). + pub(super) fn get(&mut self, text: &str) -> Option<&crate::import::ParsedStyle> { + #[cfg(test)] + if REPARSE.get() { + self.0.remove(text); + } + if !self.0.contains_key(text) { + let parsed = crate::import::parse_art_style(known_style("x", text).as_bytes(), "x"); + self.0.insert(text.to_owned(), parsed); + } + self.0.get(text).and_then(Option::as_ref) + } } impl Styles { @@ -652,7 +681,7 @@ impl Writer<'_> { continue; } let xy = Xy { blend: g.blend, opacity: g.opacity.clamp(0.0, 1.0), isolate: g.isolate, knockout: g.knockout, shape: false }; - let text = self.style_text(&g.appearance, xy, None).filter(|t| panel_reads(g, t)); + let text = self.style_text(&g.appearance, xy, None).filter(|t| panel_reads(g, t, &mut self.styles.parsed)); let Some(text) = text else { self.warn(PANEL_STYLES); continue; @@ -669,7 +698,7 @@ impl Writer<'_> { continue; } if g.id != 0 { - self.styles.panel.insert(g.id, g.name.clone()); + self.styles.panel.insert(g.id, self.styles.known.len()); } self.styles.listed.push(g.name.clone()); self.styles.known.push((g.name.clone(), text)); @@ -701,14 +730,13 @@ impl Writer<'_> { } let doc = self.doc; if let Some(id) = orig.extras().graphic_style - && let Some(name) = self.styles.panel.get(&id).cloned() + && let Some((name, text)) = self.styles.panel.get(&id).and_then(|i| self.styles.known.get(*i)) && let Some(g) = doc.graphic_style_by_id(id) && g.transparency_matches(orig) && g.appearance_on(orig).approx_eq(&orig.appearance) - && let Some(text) = self.styles.known.iter().find(|(n, _)| *n == name).map(|(_, t)| t.clone()) - && object_reads(orig, &text) + && object_reads(orig, text, &mut self.styles.parsed) { - return Some(name); + return Some(name.clone()); } let brushed = brushed(orig); if (orig.appearance.effects.is_empty() && !brushed) || !(own_style_holds(&orig.appearance) || warped_image(orig)) { @@ -720,7 +748,7 @@ impl Writer<'_> { let rule = object_rule(orig); let text = self .style_text(&orig.appearance, Xy::of(orig), path.as_ref().map(|p| (p, rule))) - .filter(|t| object_reads(orig, t) && (!brushed || self.brushed_style_reads(t))); + .filter(|t| object_reads(orig, t, &mut self.styles.parsed) && (!brushed || self.brushed_style_reads(t))); let Some(text) = text else { if let Some(mark) = saved.0 { self.gradient_rollback(mark); @@ -784,7 +812,12 @@ impl Writer<'_> { if !self.take_objects(1 + own) { return; } - let linked = orig.extras().graphic_style.and_then(|id| self.styles.panel.get(&id)).is_some_and(|p| p == name); + let linked = orig + .extras() + .graphic_style + .and_then(|id| self.styles.panel.get(&id)) + .and_then(|i| self.styles.known.get(*i)) + .is_some_and(|(p, _)| p == name); if linked { self.styles.links_written += 1; } else if brushed(orig) { @@ -937,13 +970,12 @@ fn own_style_holds(ap: &Appearance) -> bool { } /// Does the reader read graphic style `g` from style text `text` as it is? It leaves out a graphic -/// style with a brush on a stroke that paints. -fn panel_reads(g: &GraphicStyle, text: &str) -> bool { +/// style with a brush on a stroke that paints. `parsed` holds the texts already parsed. +fn panel_reads(g: &GraphicStyle, text: &str, parsed: &mut Parsed) -> bool { if g.appearance.items.iter().any(|i| matches!(i, AppearanceItem::Stroke(s) if s.brush.is_some() && !s.paint.is_none())) { return false; } - let section = known_style("x", text); - let Some(read) = crate::import::read_art_style(section.as_bytes(), "x", None) else { return false }; + let Some(read) = parsed.get(text).and_then(|st| crate::import::read_parsed_style(st, None)) else { return false }; // The opacity within the written number's precision. read.transparency.is_some_and(|t| (t.0 - g.opacity).abs() <= 1e-4 && (t.1, t.2, t.3) == (g.blend, g.isolate, g.knockout)) && same_appearance(&read.appearance, &g.appearance) @@ -952,19 +984,20 @@ fn panel_reads(g: &GraphicStyle, text: &str) -> bool { /// Does the reader read object `n` written with style text `text` as it is: a path or compound /// path with a style it reads on any object, filled by the non-zero rule when the style fills it, /// or a group with no fills or strokes of its own, with effects that move the outline only where the -/// reader reads them ([`crate::import::style_moves_with`]), or an image ([`warped_image`]) with a +/// reader reads them ([`crate::import::parsed_moves_with`]), or an image ([`warped_image`]) with a /// style of one Warp? The reader takes such an image's Warp where it draws as its drawn look. -fn object_reads(n: &Node, text: &str) -> bool { - let section = known_style("x", text); +/// `parsed` holds the texts already parsed. +fn object_reads(n: &Node, text: &str, parsed: &mut Parsed) -> bool { + let Some(st) = parsed.get(text) else { return false }; let own = n.appearance.fill().map(|f| &f.paint).filter(|p| matches!(p, Paint::Gradient(_))); - let Some(mut read) = crate::import::read_art_style(section.as_bytes(), "x", own) else { return false }; + let Some(mut read) = crate::import::read_parsed_style(st, own) else { return false }; let group = matches!(n.kind, NodeKind::Group { .. }); let image = matches!(n.kind, NodeKind::Image(_)); if (image && !(read.image_warp && warped_image(n))) || (!image && !read.simple) || (group && !read.appearance.items.is_empty()) || (!group && read.pathfinder) - || !crate::import::style_moves_with(section.as_bytes(), "x", n) + || !crate::import::parsed_moves_with(st, n) { return false; } diff --git a/crates/eps/src/import.rs b/crates/eps/src/import.rs index 0d451ec9da..ba38492f77 100644 --- a/crates/eps/src/import.rs +++ b/crates/eps/src/import.rs @@ -89,14 +89,14 @@ use obj::PsError; pub use ai::NameEncoding; #[cfg(test)] pub(crate) use ai::objects_read; +#[cfg(test)] +pub(crate) use ai::{ART_STYLE_PARSES, ENVELOPE_DRAWN, ENVELOPE_TYPE_DRAWN}; pub(crate) use ai::{ BLEND_BUDGET, BLEND_PLUGIN, BRUSH_MANAGER, BrushesRead, DEFORM_PLUGIN, EnvelopeGridPoint, MAX_BLEND_KEYS, MAX_BLEND_OBJECTS, - MAX_CHECKED as ENVELOPE_CHECKS, MAX_EDITING_OBJECTS, MAX_GRADIENT_STOPS, MAX_LISTED, MAX_LISTED_NAME, MAX_MESH_SIDE, MAX_SYMBOLS, blend_reads, - brush_plugin_name, brushes_kept, envelope_outline, envelope_upright, mesh_reads, read_art_style, read_brush_object, read_style_list, - style_moves_with, symbol_art_member, turn_brush_art_over, warp_number, + MAX_CHECKED as ENVELOPE_CHECKS, MAX_EDITING_OBJECTS, MAX_GRADIENT_STOPS, MAX_LISTED, MAX_LISTED_NAME, MAX_MESH_SIDE, MAX_SYMBOLS, ParsedStyle, + blend_reads, brush_plugin_name, brushes_kept, envelope_outline, envelope_upright, mesh_reads, parse_art_style, parsed_moves_with, + read_brush_object, read_parsed_style, read_style_list, symbol_art_member, turn_brush_art_over, warp_number, }; -#[cfg(test)] -pub(crate) use ai::{ENVELOPE_DRAWN, ENVELOPE_TYPE_DRAWN}; pub(crate) use ate::{MAX_BYTES as MAX_TEXT_DOCUMENT, MAX_FRAMES, MAX_SEGMENTS, MAX_STORY, MAX_VALUES as MAX_TEXT_VALUES, record_version}; pub use native::{AiLayers, ai_alone, ai_alone_on_page, ai_alone_with, ai_layers_alone, ai_opened_artboard, is_loss, layered_ai, layered_ai_from}; pub(crate) use native::{MAX_TEXT, MAX_WRAP_WORK, scale_document, scale_symbols}; diff --git a/crates/eps/src/import/ai.rs b/crates/eps/src/import/ai.rs index 78990f9db7..5b170b239e 100644 --- a/crates/eps/src/import/ai.rs +++ b/crates/eps/src/import/ai.rs @@ -57,13 +57,15 @@ pub use read::read; #[cfg(test)] pub(crate) use read::with_image_limits; pub(crate) use read::{ - BLEND_BUDGET, MAX_NODES as MAX_EDITING_OBJECTS, MAX_SYMBOLS, join_and, read_art_style, read_over_page, read_program, read_style_list, slot_frame, - slot_of, style_moves_with, symbol_art_member, + BLEND_BUDGET, MAX_NODES as MAX_EDITING_OBJECTS, MAX_SYMBOLS, ParsedStyle, join_and, parse_art_style, parsed_moves_with, read_over_page, + read_parsed_style, read_program, read_style_list, slot_frame, slot_of, symbol_art_member, }; pub use read::{ BindingRef, Brushes, PaletteSwatches, PlacedPage, Structure, Symbols, active_artboard, artboards, bindings_note, brushes, graphic_styles, palette, read_beside, read_in, symbols, variables, }; +#[cfg(test)] +pub(crate) use style::ART_STYLE_PARSES; pub(crate) use read::is_look_slot; pub(crate) use style::{MAX_LISTED, MAX_LISTED_NAME, warp_number}; diff --git a/crates/eps/src/import/ai/brush.rs b/crates/eps/src/import/ai/brush.rs index ef45364de5..afef3af634 100644 --- a/crates/eps/src/import/ai/brush.rs +++ b/crates/eps/src/import/ai/brush.rs @@ -799,14 +799,16 @@ impl BrushesRead { Self { drafts, by_name, bending } } - /// Does the reader read every stroke of art style `style` in `section` (the text between - /// `%AI9_BeginArtStyles` and its end) that names a brush with that brush on it, at the brush's - /// own settings? A style the reader doesn't read, or that names a brush no object gives, or an - /// Art brush in a style with effects, isn't read so. - pub(crate) fn style_reads(&self, section: &[u8], style: &str) -> bool { + /// Does the reader read every stroke of art style `parsed` ([`crate::import::parse_art_style`]) + /// that names a brush with that brush on it, at the brush's own settings? A style the reader + /// doesn't read, or that names a brush no object gives, or an Art brush in a style with effects, + /// isn't read so. + pub(crate) fn style_reads(&self, parsed: &crate::import::ParsedStyle) -> bool { use super::style::StyleItem; - let styles = super::style::art_styles(section); - let Some(st) = styles.get(style).filter(|st| st.plain) else { return false }; + let st = &parsed.style; + if !st.plain { + return false; + } st.items.iter().all(|item| match item { StyleItem::Stroke { brush: Some((name, settings)), .. } => { let Some(draft) = self.by_name.get(name).and_then(|i| self.drafts.get(*i)) else { return false }; diff --git a/crates/eps/src/import/ai/read.rs b/crates/eps/src/import/ai/read.rs index 27a10033db..cc43157bcb 100644 --- a/crates/eps/src/import/ai/read.rs +++ b/crates/eps/src/import/ai/read.rs @@ -155,7 +155,7 @@ pub use document::{ }; pub(crate) use document::{slot_frame, slot_of}; use graph::Graph; -pub(crate) use ops::{read_art_style, read_style_list, style_moves_with}; +pub(crate) use ops::{ParsedStyle, parse_art_style, parsed_moves_with, read_parsed_style, read_style_list}; #[cfg(test)] pub(crate) use raster::with_image_limits; pub(crate) use types::BLEND_BUDGET; diff --git a/crates/eps/src/import/ai/read/ops.rs b/crates/eps/src/import/ai/read/ops.rs index 39499b064d..5283762a51 100644 --- a/crates/eps/src/import/ai/read/ops.rs +++ b/crates/eps/src/import/ai/read/ops.rs @@ -1453,16 +1453,30 @@ pub(crate) fn read_style_list(section: &[u8]) -> Vec<String> { crate::import::ai::style::art_style_list(section).iter().map(|raw| obj::text(raw)).filter(|name| !name.is_empty()).collect() } -/// Art style `name` of `section` as the reader reads it ([`StyleRead`]): [`appearance_from_art_style`], -/// with a style's one gradient fill as `own_gradient`, the object's own gradient, as [`styled`] reads -/// it on objects other than type. A stroke that names a brush is read with that brush's name, as -/// [`styled`] reads it on a path or compound path when the Brushes panel keeps that brush at those -/// settings, which [`crate::import::ai::brush::BrushesRead::style_reads`] checks. `None` when the section -/// doesn't define it, the reader doesn't read it, or it paints with a pattern or a gradient that -/// isn't the object's own. -pub(crate) fn read_art_style(section: &[u8], name: &str, own_gradient: Option<&Paint>) -> Option<StyleRead> { +/// An art style as the reader parses it ([`parse_art_style`]), which a writer reads on any number of +/// objects ([`read_parsed_style`], [`parsed_moves_with`], +/// [`crate::import::ai::brush::BrushesRead::style_reads`]). +#[derive(Clone, Debug)] +pub(crate) struct ParsedStyle { + pub(in crate::import::ai) style: crate::import::ai::style::ArtStyle, +} + +/// Art style `name` of `section` (the text between `%AI9_BeginArtStyles` and its end) as the reader +/// parses it. `None` when the section doesn't define it. +pub(crate) fn parse_art_style(section: &[u8], name: &str) -> Option<ParsedStyle> { + crate::import::ai::style::art_styles(section).remove(name).map(|style| ParsedStyle { style }) +} + +/// Art style `parsed` as the reader reads it ([`StyleRead`]): [`appearance_from_art_style`], with a +/// style's one gradient fill as `own_gradient`, the object's own gradient, as [`styled`] reads it on +/// objects other than type. A stroke that names a brush is read with that brush's name, as [`styled`] +/// reads it on a path or compound path when the Brushes panel keeps that brush at those settings, +/// which [`crate::import::ai::brush::BrushesRead::style_reads`] checks. `None` when the reader doesn't +/// read it, or it paints with a pattern or a gradient that isn't the object's own. `parsed` is left as +/// it is, for the next object. +pub(crate) fn read_parsed_style(parsed: &ParsedStyle, own_gradient: Option<&Paint>) -> Option<StyleRead> { use crate::import::ai::style::StyleItem; - let mut st = crate::import::ai::style::art_styles(section).remove(name)?; + let mut st = parsed.style.clone(); if st.items.iter().filter(|i| matches!(i, StyleItem::Gradient { .. })).count() == 1 { let own = own_gradient?; for item in &mut st.items { @@ -1491,11 +1505,10 @@ pub(crate) fn read_art_style(section: &[u8], name: &str, own_gradient: Option<&P Some(StyleRead { appearance, simple: st.simple, image_warp: st.image_warp, pathfinder: st.pathfinder, transparency: st.transparency }) } -/// Is art style `name` of `section` read on `object` as far as an effect that moves the outline -/// goes: the style has none, or `object` is one [`moves_with`] reads it on, as [`styled`] checks? -/// `false` when the section doesn't define it. -pub(crate) fn style_moves_with(section: &[u8], name: &str, object: &Node) -> bool { - crate::import::ai::style::art_styles(section).remove(name).is_some_and(|st| !st.moves_outline() || moves_with(object, &st)) +/// Is art style `parsed` read on `object` as far as an effect that moves the outline goes: the style +/// has none, or `object` is one [`moves_with`] reads it on, as [`styled`] checks? +pub(crate) fn parsed_moves_with(parsed: &ParsedStyle, object: &Node) -> bool { + !parsed.style.moves_outline() || moves_with(object, &parsed.style) } /// A style's stroke as an appearance item (`None` for a fill). diff --git a/crates/eps/src/import/ai/style.rs b/crates/eps/src/import/ai/style.rs index e0068a52be..0d87028ec0 100644 --- a/crates/eps/src/import/ai/style.rs +++ b/crates/eps/src/import/ai/style.rs @@ -419,8 +419,16 @@ fn closes(data: &[u8]) -> bool { false } +#[cfg(test)] +thread_local! { + /// How many times [`art_styles`] has parsed a section on this thread. + pub(crate) static ART_STYLE_PARSES: std::cell::Cell<u64> = const { std::cell::Cell::new(0) }; +} + /// [`art_styles_in`], names read in the default encoding. pub(super) fn art_styles(data: &[u8]) -> HashMap<String, ArtStyle> { + #[cfg(test)] + ART_STYLE_PARSES.set(ART_STYLE_PARSES.get() + 1); art_styles_in(data, &mut Names::default()) } diff --git a/crates/eps/src/import/ai/style/tests.rs b/crates/eps/src/import/ai/style/tests.rs index c4b006fe2a..2b48fd268b 100644 --- a/crates/eps/src/import/ai/style/tests.rs +++ b/crates/eps/src/import/ai/style/tests.rs @@ -1445,7 +1445,8 @@ fn warp_numbers_are_the_dialogs_order() { /// and nothing for styles it doesn't read. #[test] fn a_style_is_read_as_a_writer_checks_it() { - let read = |data: &str, own: Option<&Paint>| crate::import::read_art_style(data.as_bytes(), "Odd", own); + let parse = |data: &str, name: &str| crate::import::parse_art_style(data.as_bytes(), name); + let read = |data: &str, own: Option<&Paint>| parse(data, "Odd").and_then(|st| crate::import::read_parsed_style(&st, own)); let style = |kids: &[String]| format!("/KnownStyle :\n(Odd) /Name ,\n/ActiveStyle :\n{}", compound("Chain Style Filter", kids)); let gradient = fill("Bb\n1 (G) 0 0 0 1 1 0 0 1 0 0 1 Bg\n0 BB"); let stack = compound("Stack Style Filter", std::slice::from_ref(&gradient)); @@ -1456,11 +1457,18 @@ fn a_style_is_read_as_a_writer_checks_it() { assert_eq!(got.appearance.items[0].paint(), &own); assert_eq!(got.transparency.map(|t| (t.0, t.1)), Some((0.5, BlendMode::Multiply))); assert!(got.simple && !got.pathfinder); + // One parse read on two objects: each takes its own gradient, and the parse is left as it was. + let parsed = parse(&data, "Odd").unwrap(); + let black = Paint::solid(vectorcraft_color::Color::BLACK); + let first = crate::import::read_parsed_style(&parsed, Some(&own)).unwrap(); + let second = crate::import::read_parsed_style(&parsed, Some(&black)).unwrap(); + assert_eq!((first.appearance.items[0].paint(), second.appearance.items[0].paint()), (&own, &black)); + assert_eq!(parsed.style, parse(&data, "Odd").unwrap().style); // A gradient that isn't the object's own, a pattern, another name, two gradients: nothing. assert!(read(&data, None).is_none()); let pattern = style(&[compound("Stack Style Filter", &[fill("(Dots) 0 0 1 1 0 0 0 0 0 [1 0 0 1 0 0] p")])]); assert!(read(&pattern, None).is_none()); - assert!(crate::import::read_art_style(data.as_bytes(), "Even", Some(&own)).is_none()); + assert!(parse(&data, "Even").is_none()); assert!(read(&style(&[compound("Stack Style Filter", &[gradient.clone(), gradient])]), Some(&own)).is_none()); // Damaged text: every cut of the style, and stray bytes, without a panic. for cut in 0..data.len() { From 0727e8fb5fbe0bfe9b5a54f3b536e1a536600ecc Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 17 Nov 2026 13:37:25 -0800 Subject: [PATCH 136/176] New Document: a profile's redefined Default Graphic Style sets the starting fill and stroke When a New Document profile's Default Graphic Style differs from the shipped one (white fill, 1 pt black stroke), file.new resets new art in documents from that profile to the style's fills, strokes and effects, not linked to the style. Default Fill and Stroke (paint.default, D) gives the defaults and the selected art the same look in those documents; type still gets a black fill and no stroke. A profile with the shipped style leaves the current fill and stroke as they were. Part of #8350 --- crates/engine/src/cmd/newart.rs | 36 +++++++++++++++++- crates/engine/src/cmd/newdoc.rs | 4 ++ crates/engine/src/cmd/paint.rs | 11 +++++- crates/engine/src/tests/newdoc.rs | 63 +++++++++++++++++++++++++++++++ docs/mcp.md | 9 +++++ docs/target-app-parity.md | 1 + 6 files changed, 120 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/newart.rs b/crates/engine/src/cmd/newart.rs index ce8029e71b..84812dad97 100644 --- a/crates/engine/src/cmd/newart.rs +++ b/crates/engine/src/cmd/newart.rs @@ -7,12 +7,16 @@ //! panel's New Art Has Basic Appearance off, the whole appearance of the last selection. With the //! option on (the default) an inherited appearance gives new art its top stroke's options only, //! and a change of selection loads only the proxies. `paint.default` resets it. +//! +//! A document whose Default Graphic Style no longer has the shipped look (a New Document profile +//! redefined it) gives the reset that style's fills, strokes and effects instead, and `file.new` +//! resets new art when it opens such a document. use std::borrow::Cow; use serde_json::{Value, json}; use vectorcraft_color::{BlendMode, Paint}; -use vectorcraft_doc::{Appearance, AppearanceItem, FillLayer, GraphicStyle, Node, NodeKind, StrokeLayer}; +use vectorcraft_doc::{Appearance, AppearanceItem, ColorMode, DEFAULT_GRAPHIC_STYLE, Document, FillLayer, GraphicStyle, Node, NodeKind, StrokeLayer}; use vectorcraft_tools::PaintDefaults; use super::gradient::unplaced; @@ -263,7 +267,35 @@ fn describe(s: &mut Session, _: &Value) -> Result<Value> { })) } -/// The defaults for new art reset (`paint.default`): white fill, 1 pt black stroke, no template. +/// The defaults for new art reset (`paint.default`): white fill, 1 pt black stroke, no template; +/// in a document whose Default Graphic Style was redefined, that style's fills, strokes and effects +/// at full opacity, not linked to the style. pub(crate) fn reset(s: &mut Session) { s.paint = PaintDefaults::default(); + let style = s.doc().ok().and_then(|st| redefined_default_style(&st.doc)).cloned(); + if let Some(g) = style { + let ap = if g.unit_box { g.appearance } else { unplace_all(g.appearance) }; + s.take_new_art(ap, 1.0, BlendMode::Normal, None, false); + } +} + +/// `d`'s Default Graphic Style when its fills, strokes, effects or transparency differ from the +/// shipped style's (white fill, 1 pt black stroke), the shipped colors converted to `d`'s color mode +/// as a New Document profile's are. +pub(crate) fn redefined_default_style(d: &Document) -> Option<&GraphicStyle> { + let g = d.graphic_styles.iter().find(|g| g.name == DEFAULT_GRAPHIC_STYLE)?; + let same = + |o: &GraphicStyle| (&o.appearance, o.opacity, o.blend, o.isolate, o.knockout) == (&g.appearance, g.opacity, g.blend, g.isolate, g.knockout); + if same(&GraphicStyle::new(DEFAULT_GRAPHIC_STYLE, Appearance::default_art())) { + return None; + } + if d.color_mode != ColorMode::Rgb { + let mut shipped = Document::new_with_mode(1.0, 1.0, ColorMode::Rgb); + shipped.graphic_styles.retain(|o| o.name == DEFAULT_GRAPHIC_STYLE); + super::colormgmt::set_color_mode(&mut shipped, d.color_mode, true, None, super::colormgmt::Grays::Profile); + if shipped.graphic_styles.first().is_some_and(same) { + return None; + } + } + Some(g) } diff --git a/crates/engine/src/cmd/newdoc.rs b/crates/engine/src/cmd/newdoc.rs index 2a8d074617..e74a570a5b 100644 --- a/crates/engine/src/cmd/newdoc.rs +++ b/crates/engine/src/cmd/newdoc.rs @@ -814,6 +814,10 @@ pub(crate) fn file_new(s: &mut Session, p: &Value) -> Result<Value> { // The profile's links keep their relative paths, which name places from the profile's file, as // a new document from a history state keeps its source's. s.doc_mut()?.links_from = links_from; + // A profile whose Default Graphic Style was redefined gives new art in the document that style. + if super::newart::redefined_default_style(&s.doc()?.doc).is_some() { + super::newart::reset(s); + } // Overprint Preview is the engine's (the UI turns Pixel Preview on from `previewMode`). Both // are views of the whole app, so Default leaves them as they are. if settings.preview_mode == PreviewMode::Overprint { diff --git a/crates/engine/src/cmd/paint.rs b/crates/engine/src/cmd/paint.rs index 2421b71d77..20b3f18de2 100644 --- a/crates/engine/src/cmd/paint.rs +++ b/crates/engine/src/cmd/paint.rs @@ -48,7 +48,7 @@ pub fn specs() -> Vec<CommandSpec> { "Default Fill and Stroke", [], Some("D"), - "{ids?|id?} white fill and 1 pt black stroke for the selection and the defaults; type gets black fill and no stroke. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke, and on a graph label the black fill and no stroke of its characters for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (exceptions: docs/mcp.md)", + "{ids?|id?} white fill and 1 pt black stroke for the selection and the defaults (in a document whose Default Graphic Style differs from the shipped one, as a New Document profile can redefine it: that style's fills, strokes and effects, without its opacity or a link to it); type gets black fill and no stroke. On a path directly in a graph series, the graph also stores the paint, weight, opacity and blend mode of the topmost visible fill and stroke, and on a graph label the black fill and no stroke of its characters for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (exceptions: docs/mcp.md)", has_doc, default_paint ), @@ -1035,6 +1035,8 @@ fn default_paint(s: &mut Session, p: &Value) -> Result<Value> { if !ids.is_empty() { // When every object comes out as it was, the document and its undo history stay as they are. let before = s.doc()?.doc.clone(); + // A redefined Default Graphic Style gives other art its fills, strokes and effects, placed on each object. + let style = super::newart::redefined_default_style(&before).cloned(); super::overprint::edit_counted(s, "Default Fill and Stroke", |d| { for id in &ids { let Some(n) = d.node_mut(*id) else { continue }; @@ -1045,7 +1047,12 @@ fn default_paint(s: &mut Session, p: &Value) -> Result<Value> { r.style.stroke = Paint::None; } } - _ => n.appearance = Appearance::default_art().into(), + _ => { + n.appearance = match &style { + Some(g) => g.appearance_on(n).into_owned().into(), + None => Appearance::default_art().into(), + } + } } } let kept = super::appearance::capture_series_writes(&before, d, &ids, (true, true), (true, true), false, false); diff --git a/crates/engine/src/tests/newdoc.rs b/crates/engine/src/tests/newdoc.rs index 9e20de0ad1..04e075f312 100644 --- a/crates/engine/src/tests/newdoc.rs +++ b/crates/engine/src/tests/newdoc.rs @@ -637,6 +637,69 @@ fn an_edited_profile_starts_the_documents_of_its_category() { let _ = std::fs::remove_dir_all(&dir); } +/// The fill, stroke and weight of `id` in the active document. +fn look(s: &Session, id: u64) -> (vectorcraft_color::Paint, vectorcraft_color::Paint, Option<f64>) { + let n = s.doc().unwrap().doc.node(vectorcraft_doc::NodeId(id)).cloned().unwrap(); + (n.appearance.fill_paint(), n.appearance.stroke_paint(), n.appearance.stroke().map(|st| st.width)) +} + +#[test] +fn a_redefined_default_graphic_style_in_a_profile_is_the_default_fill_and_stroke() { + use vectorcraft_color::Paint; + let (mut s, dir) = with_profiles("default-style"); + // The Print profile's Default Graphic Style becomes no fill and a 0.25 pt red stroke. + s.execute("file.newProfiles.edit", &json!({"name": "Print"})).unwrap(); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap(); + s.execute("paint.setFill", &json!({"none": true})).unwrap(); + s.execute("paint.setStroke", &json!({"color": "#ff0000"})).unwrap(); + s.execute("stroke.set", &json!({"weight": 0.25})).unwrap(); + s.execute("graphicStyle.redefine", &json!({"name": "Default Graphic Style"})).unwrap(); + s.execute("document.save", &json!({})).unwrap(); + let style = s.doc().unwrap().doc.graphic_styles[0].clone(); + let red = style.appearance.stroke_paint(); + assert!(matches!(red, Paint::Solid { .. }), "{red:?}"); + assert_eq!(style.appearance.stroke().map(|st| st.width), Some(0.25), "{style:?}"); + // The Mobile profile is saved as shipped. + s.execute("file.newProfiles.edit", &json!({"name": "Mobile"})).unwrap(); + s.execute("document.save", &json!({})).unwrap(); + s.execute("select.none", &json!({})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#00ff00"})).unwrap(); + let green = s.paint.fill.clone(); + + // A document from the Print profile starts with the style's fill, stroke and weight, and its art takes them. + s.execute("file.new", &json!({"profile": "Print", "colorMode": "cmyk"})).unwrap(); + assert_eq!((s.paint.fill.clone(), s.paint.stroke.clone(), s.paint.stroke_width), (Paint::None, red.clone(), 0.25)); + let id = s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 60, "height": 60})).unwrap()["id"].as_u64().unwrap(); + assert_eq!(look(&s, id), (Paint::None, red.clone(), Some(0.25))); + // Default Fill and Stroke gives the selection and the defaults that look again, as one undo step. + s.execute("paint.setFill", &json!({"color": "#0000ff"})).unwrap(); + s.execute("stroke.set", &json!({"weight": 3})).unwrap(); + let steps = s.doc().unwrap().history.undo.len(); + s.execute("paint.default", &json!({})).unwrap(); + assert_eq!(look(&s, id), (Paint::None, red.clone(), Some(0.25))); + assert_eq!((s.paint.fill.clone(), s.paint.stroke_width), (Paint::None, 0.25)); + assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1); + // Nothing to change: no undo step. + let step = s.doc().unwrap().history.step(); + s.execute("paint.default", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().history.step(), step); + // The new art is not linked to the style. + assert!(s.doc().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().extras().graphic_style.is_none()); + + // A profile with the shipped style, here converted to CMYK, leaves the fill and stroke the user chose. + s.execute("select.none", &json!({})).unwrap(); + s.execute("paint.setFill", &json!({"color": "#00ff00", "keepModel": true})).unwrap(); + s.execute("file.new", &json!({"profile": "Mobile", "colorMode": "cmyk"})).unwrap(); + assert_eq!(s.doc().unwrap().doc.color_mode, ColorMode::Cmyk); + assert_eq!(s.paint.fill, green); + // So does a document without a profile, and Default Fill and Stroke there gives white and 1 pt black. + s.execute("file.new", &json!({})).unwrap(); + assert_eq!(s.paint.fill, green); + s.execute("paint.default", &json!({})).unwrap(); + assert_eq!(s.paint, vectorcraft_tools::PaintDefaults::default()); + let _ = std::fs::remove_dir_all(&dir); +} + #[test] fn the_profile_follows_the_preset_access_and_reset() { let (mut s, dir) = with_profiles("choice"); diff --git a/docs/mcp.md b/docs/mcp.md index 4c1b661f42..7504085737 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7512,6 +7512,15 @@ starts with one empty layer. The grid comes from Preferences › Guides & Grid, preset's color mode differs from the profile's, the profile's colors are converted as `file.documentColorMode` converts them. +A profile also sets the default fill and stroke of its documents (VectorCraft's own rule). When the profile's Default +Graphic Style differs from the shipped one (white fill, 1 pt black stroke, with the shipped colors converted to the +document's color mode), `file.new` resets new art to that style's fills, strokes and effects, at full opacity and not +linked to the style, and `paint.default` (Default Fill and Stroke) gives the defaults and the selected art the same +look; type still gets a black fill and no stroke. With the shipped style, `file.new` leaves the fill and stroke as they +were. For example, to start with no fill and a 0.25 pt red stroke: edit the profile with `file.newProfiles.edit`, draw a +path with that fill and stroke, select it, run `graphicStyle.redefine {name: "Default Graphic Style"}`, delete the +path and save. + A built-in preset names its category's profile in `file.newPresets` (`profile`). Saved and Recent presets keep the profile of the preset they were made from. `file.new {profile: "Print"}` picks a profile for any settings, and `profile: null` starts with the defaults. A document made without a preset starts with the defaults. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index ef83de54ad..bc4dd8e9e7 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -820,6 +820,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **New Document's units:** the dialog opens in Preferences › Units › General, also on a Recent entry made in other units (an entry in pixels, or a saved preset in the units it was saved in, keeps its units), so File › New and New Without Dialog make documents in the General unit. Units chosen in the Units menu stay when another tab or preset is chosen and when a card is clicked or double-clicked; without such a choice, clicking another Recent or Saved card brings back the units that card was made in (#7944). These are VectorCraft's own rules. Tests: `the_dialog_opens_in_the_general_units_over_a_recent_entry`, `a_recent_saved_preset_keeps_its_units_and_name`, `units_chosen_in_the_menu_survive_tabs_and_presets` and `units_set_over_a_popup_stay_chosen` in `dialogs/new_document.rs`; `a_recent_card_keeps_the_units_chosen_in_the_menu` and `a_double_clicked_card_keeps_the_units_chosen_in_the_menu` in `panels/tests_units.rs`. - **New Document's More Settings and Save Preset:** More Settings opens a pop-up over New Document with only Number of Artboards, the artboard layout, Change to Right-to-Left Layout, Spacing and Columns; Done, Escape or a click outside closes it and keeps the values. Save Preset turns the top of Preset Details into a Save Document Preset heading with the preset's name, Cancel and Save, and hides the document's name, Close and Create until the preset is saved or canceled; nothing in that mode creates a document. Save Preset's default name is the first "Preset N" no saved preset has. VectorCraft's own layout. Harness tests in `dialogs/new_document.rs` cover both. - **New Document profiles:** each built-in category's presets start documents from that category's profile, a native document holding the starting swatches, graphic styles, brushes, symbols and other assets, the ruler and Document Setup options and the print settings ([Create a custom new document profile](https://helpx.adobe.com/illustrator/desktop/add-and-import-files/start-a-new-file/create-a-custom-new-document-profile.html)). New Document's Manage Profiles pop-up opens a profile to edit and resets one to the shipped profile (`file.newProfiles`, `file.newProfiles.edit`, `file.newProfiles.reset`; `file.new {profile}`). The profiles live in VectorCraft's own `New Document Profiles` folder next to the preferences; a profile that cannot be read or is larger than 64 MiB leaves the defaults and is reported. Tests: `tests::newdoc::an_edited_profile_starts_the_documents_of_its_category`, `the_profile_follows_the_preset_access_and_reset`, `profile_errors_name_the_file_by_its_name_outside_the_read_roots`, `a_damaged_or_oversized_profile_leaves_the_defaults_and_is_reported`, `profile_names_are_checked_and_editing_needs_the_folder`, `dialogs::new_document::tests::manage_profiles_edits_and_resets_the_profiles`. +- **Default fill and stroke from a profile:** when a New Document profile's Default Graphic Style is redefined (for example no fill and a 0.25 pt red stroke), documents from that profile start new art with that style's fills, strokes and effects, and Default Fill and Stroke (`paint.default`, D) gives the defaults and the selection the same look in those documents (VectorCraft's own rule). Test: `tests::newdoc::a_redefined_default_graphic_style_in_a_profile_is_the_default_fill_and_stroke`. - **Control bar with the Artboard tool:** while the Artboard tool is in use, the Control bar shows the active artboard's controls in place of the object controls: Preset, Portrait and Landscape, New Artboard, Delete Artboard, the Name field, Artboard Options, Rearrange All Artboards, the Transform link, Move and Scale Artwork with Artboard and, while the bar has room, the reference point with X and Y, and W and H with the Constrain Width and Height Proportions link. Each runs the command its Properties or Transform panel counterpart runs (`artboard.setProps`, `artboard.new`, `artboard.delete`, `tool.options {tool: "artboard"}`), and the reference point is the one the Transform panel uses. In an 800-point window the controls up to the Transform link fit, Move and Scale Artwork with Artboard show as their boxes alone with their names in tooltips, and the link opens the Transform panel with the artboard's position and size. Pointer and key tests in `panels/artboards.rs` cover the controls, W about the reference point, the orientation and the name. Public reference: [Using multiple artboards](https://web.archive.org/web/20210925094818/https://helpx.adobe.com/illustrator/using/using-multiple-artboards.html) (archived copy). - **Names of new and renamed artboards, brushes and patterns:** `artboard.new` and `artboard.setProps` trim the white space around the name they are given, as the Artboards panel's rename does, and a blank name gives the artboard its default name, Artboard N for the Nth artboard. `brush.new`, `brush.duplicate`, `brush.options`, `object.pattern.make`, `object.pattern.saveCopy` and `pattern.options` trim the name as the Brush Options dialog and the Pattern Options panel do, and compare the trimmed name with the names there are; a blank name gives the name each command gives when there is none, and Brush Options and Pattern Options keep the name. Tests in `tests/panelcmds.rs`, `tests/brushsym.rs` and `tests/pattern.rs` cover each command. Public references: [Using multiple artboards](https://web.archive.org/web/20210925094818/https://helpx.adobe.com/illustrator/using/using-multiple-artboards.html), [Brushes](https://web.archive.org/web/20251018101754/https://helpx.adobe.com/illustrator/using/brushes.html) and [Create and edit patterns](https://web.archive.org/web/20211031180358/https://helpx.adobe.com/illustrator/using/create-edit-patterns.html) (archived copies). - **Repeated brush names in a file:** a document or brush library file whose brushes repeat a name opens with the first brush of that name as stored and each later one numbered, as "Name 2", "Name 3" and so on, skipping names the file already has. Strokes that name the brush keep drawing the first one, and `brush.list`, `brush.options`, `brush.delete`, `brush.library` and the Brushes panel then reach each brush by its own name. This numbering is VectorCraft's own rule. Tests in `crates/brush/src/tests.rs`, `tests/brushsym.rs` and `tests/brushlib.rs` cover it. From 576efd77055b61c23c0032d2e89e9ed2b1981038 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 17 Nov 2026 14:05:32 -0800 Subject: [PATCH 137/176] Document Setup: a grid color box opens the picker on a hex edit made just before A click on a Transparency Grid color box whose press and release arrive in one frame, while that color's hex field holds an edit, ends the edit in the same frame. The box now records only which color was clicked, and the Color Picker opens after the row on the color Document Setup holds then, so it opens on the edited color and an unchanged OK keeps it. Before, the picker opened on the color from before the edit and its OK wrote that color back over the edit. A hex field's edit also replaces its color in the pair Document Setup holds when it commits, so a Grid Colors preset chosen in the same frame keeps its other color. --- crates/ui-egui/src/dialogs/document_setup.rs | 98 +++++++++++++++++--- 1 file changed, 87 insertions(+), 11 deletions(-) diff --git a/crates/ui-egui/src/dialogs/document_setup.rs b/crates/ui-egui/src/dialogs/document_setup.rs index f1fa79018c..9124fce05a 100644 --- a/crates/ui-egui/src/dialogs/document_setup.rs +++ b/crates/ui-egui/src/dialogs/document_setup.rs @@ -180,17 +180,18 @@ fn grid_color_box_id(index: usize) -> egui::Id { egui::Id::unique(("grid-color-box", index)) } +/// The grid colors' hex codes that Document Setup `d` holds now (empty strings for entries that are +/// not strings). +fn grid_colors(d: &Dialog) -> Vec<String> { + d.fields.get("gridColors").and_then(Value::as_array).map(|a| a.iter().map(|c| c.as_str().unwrap_or("").to_string()).collect()).unwrap_or_default() +} + fn transparency(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { let t = Tokens::get(ui.ctx()); widgets::subheader(ui, tl!("Transparency Grid")); let sizes: Vec<(&str, &str)> = GridSize::ALL.iter().map(|g| (g.id(), g.label())).collect(); choice(ui, d, "gridSize", tl!("Grid Size:"), &sizes); - let colors: Vec<String> = d - .fields - .get("gridColors") - .and_then(Value::as_array) - .map(|a| a.iter().map(|c| c.as_str().unwrap_or("").to_string()).collect()) - .unwrap_or_default(); + let colors = grid_colors(d); let preset = GRID_COLOR_PRESETS .iter() .find(|(_, pair)| colors.len() == 2 && colors.iter().zip(pair).all(|(h, c)| h.eq_ignore_ascii_case(&c.to_hex()))) @@ -203,7 +204,10 @@ fn transparency(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { }); // The two colours (the first is also the paper colour): editing either makes them Custom. A // click on a color's box, or Space or Enter with the keyboard on it, opens the Color Picker on - // that color (white when its hex is not a color), and the picker's OK sets that color. + // that color (white when its hex is not a color), and the picker's OK sets that color. The + // picker opens after the row, on the color Document Setup holds then: a press on a box ends a + // hex field's editing in the same frame, and that field's edit is the color the picker opens on. + // A hex field's edit replaces its own color in the pair Document Setup holds when it commits. let mut pick = None; widgets::label_row(ui, "", LABEL, |ui| { for i in 0..2 { @@ -218,7 +222,7 @@ fn transparency(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { inp.consume_key(egui::Modifiers::NONE, egui::Key::Space) | inp.consume_key(egui::Modifiers::NONE, egui::Key::Enter) }); if resp.clicked() || keyed { - pick = Some((i, colour.unwrap_or(vectorcraft_color::Color::WHITE))); + pick = Some(i); } if resp.hovered() { ui.ctx().set_cursor_icon(egui::CursorIcon::PointingHand); @@ -231,7 +235,7 @@ fn transparency(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { ui.painter().rect_stroke(chip.expand(2.0), 3.0, ui.visuals().selection.stroke, egui::StrokeKind::Outside); } if let Some(c) = widgets::hex_field_named(ui, ("grid-color", i), Some(&name), hex).and_then(|h| vectorcraft_color::Color::from_hex(&h)) { - let mut v = colors.clone(); + let mut v = grid_colors(d); v.resize(2, "#ffffff".into()); v[i] = c.to_hex(); d.fields.insert("gridColors".into(), json!(v)); @@ -239,8 +243,9 @@ fn transparency(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { ui.add_space(10.0); } }); - if let Some((i, c)) = pick { - *d = super::color_picker::over_list_entry(d, "gridColors", i, c); + if let Some(i) = pick { + let c = grid_colors(d).get(i).and_then(|h| vectorcraft_color::Color::from_hex(h.trim_start_matches('#'))); + *d = super::color_picker::over_list_entry(d, "gridColors", i, c.unwrap_or(vectorcraft_color::Color::WHITE)); } ui.add_space(4.0); check(ui, d, "simulatePaper", tl!("Simulate Colored Paper")); @@ -771,6 +776,77 @@ mod tests { } } + /// Clicks the hex field that shows `digits` and types `typed` over its text, leaving the edit + /// pending; returns the field's id. + fn type_into_hex_field(app: &mut VectorcraftApp, ctx: &egui::Context, digits: &str, typed: &str) -> egui::Id { + let texts = dialog_frame(app, ctx, vec![]); + let at = texts.iter().find(|(t, _)| t == digits).unwrap_or_else(|| panic!("no field {digits}: {texts:?}")).1.center(); + let button = |pressed| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Default::default() }; + dialog_frame(app, ctx, vec![Event::PointerMoved(at), button(true)]); + dialog_frame(app, ctx, vec![button(false)]); + let field = ctx.memory(|m| m.focused()).unwrap_or_else(|| panic!("field {digits} has no focus")); + dialog_frame(app, ctx, vec![Event::Text(typed.into())]); + assert_eq!(ctx.memory(|m| m.focused()), Some(field), "the edit in {digits} is pending"); + field + } + + /// A click on a grid color's box whose press and release come in one frame, while that + /// color's hex field holds an edit, opens the Color Picker on the edited color: the press + /// commits the edit before the picker opens. The picker's unchanged OK keeps the edit, and the + /// other color stays as it was. + #[test] + fn a_grid_color_box_clicked_during_a_hex_edit_opens_the_picker_on_the_edit() { + for index in [0, 1] { + let (mut app, ctx) = transparency_tab(); + type_into_hex_field(&mut app, &ctx, LIGHT[index].trim_start_matches('#'), "123456"); + let at = ctx.read_response(super::grid_color_box_id(index)).unwrap_or_else(|| panic!("no box {index}")).rect.center(); + let button = |pressed| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Default::default() }; + dialog_frame(&mut app, &ctx, vec![Event::PointerMoved(at), button(true), button(false)]); + let case = format!("box {index}"); + assert_picker_over_setup(&app, "#123456", &case); + let mut pair = LIGHT; + pair[index] = "#123456"; + assert_eq!(dialog_grid(&crate::dialogs::parent(app.ui.dialog.as_ref().unwrap()).unwrap()), pair.map(hex).to_vec(), "{case}"); + crate::dialogs::confirm(&mut app).unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.kind.as_str(), dialog_grid(d)), (super::KIND, pair.map(hex).to_vec()), "{case}"); + } + } + + /// A hex field's edit that commits in the frame a Grid Colors preset is chosen replaces only + /// its own color in the preset's pair: the other color is the preset's. The test gives the + /// field the focus while the Grid Colors menu is open, then chooses a preset with a click whose + /// press and release come in one frame. + #[test] + fn a_hex_edit_committed_with_a_preset_choice_keeps_the_presets_other_color() { + let field = { + let (mut app, ctx) = transparency_tab(); + type_into_hex_field(&mut app, &ctx, "ffffff", "123456") + }; + let (mut app, ctx) = transparency_tab(); + let click = |app: &mut VectorcraftApp, label: &str, frames: usize| { + let texts = dialog_frame(app, &ctx, vec![]); + let at = texts.iter().find(|(t, _)| t == label).unwrap_or_else(|| panic!("no {label}: {texts:?}")).1.center(); + let button = |pressed| Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Default::default() }; + if frames == 1 { + dialog_frame(app, &ctx, vec![Event::PointerMoved(at), button(true), button(false)]); + } else { + dialog_frame(app, &ctx, vec![Event::PointerMoved(at), button(true)]); + dialog_frame(app, &ctx, vec![button(false)]); + } + }; + click(&mut app, "Light", 2); + ctx.memory_mut(|m| m.request_focus(field)); + dialog_frame(&mut app, &ctx, vec![]); + let select_all = Event::Key { key: egui::Key::A, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::COMMAND }; + dialog_frame(&mut app, &ctx, vec![select_all, Event::Text("123456".into())]); + assert_eq!(ctx.memory(|m| m.focused()), Some(field), "the edit is pending"); + let texts: Vec<String> = dialog_frame(&mut app, &ctx, vec![]).into_iter().map(|(t, _)| t).collect(); + assert!(texts.iter().any(|t| t == "123456") && texts.iter().any(|t| t == "Blue"), "{texts:?}"); + click(&mut app, "Blue", 1); + assert_eq!(dialog_grid(app.ui.dialog.as_ref().unwrap()), ["#123456", "#c4dcff"].map(hex).to_vec()); + } + /// The picker's OK sets nothing when the dialog under it has no such color or is gone: it is /// an error, and the picker stays open. #[test] From a97b22fa32fb1b52f43bfffc705c3a95aaac5ea5 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 17 Nov 2026 14:15:41 -0800 Subject: [PATCH 138/176] Contextual Task Bar: images selected with vector art are worked out once per revision The bar chooses Make Clipping Mask over Unite when the selection holds images together with other objects. It counted the images among every selected object on each frame it drew. The answer is now kept for the document's revision, as the Smooth tool's check already is, and the walk stops once it has seen an image and another object. An id with no object still counts as another object, so the bar offers the same actions as before. With 131,072 rectangles selected, 120 frames took 2.52 s counting and 18 us with the kept answer; the first frame after a change takes the same 20 ms as one count. --- crates/ui-egui/src/canvas.rs | 4 +- crates/ui-egui/src/canvas/task_bar.rs | 30 ++++- crates/ui-egui/src/tests/taskbar.rs | 179 ++++++++++++++++++++++++++ 3 files changed, 207 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 70c8834c2d..a1da882f61 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -69,9 +69,9 @@ pub(crate) use panes::{consolidate, note_drop, noted_cursor, pane, release_on_no pub(crate) use raster::{KeptFrame, color_image, color_image_owned, render_job}; use raster::{changed_pixels, frame_ppp, pixel_region, upload}; pub use selection_marks::SelectionMarks; -#[cfg(test)] -pub(crate) use task_bar::chip_paints; use task_bar::task_bar; +#[cfg(test)] +pub(crate) use task_bar::{chip_paints, images_with_other_art}; pub(crate) use task_bar::{has_colors, task_bar_rect, task_bar_shows_fonts, task_bar_shows_type}; #[cfg(test)] use tool_overlays::{DIAL_RADIUS, HiddenMarks}; diff --git a/crates/ui-egui/src/canvas/task_bar.rs b/crates/ui-egui/src/canvas/task_bar.rs index e49fa9bfc7..c133c003f8 100644 --- a/crates/ui-egui/src/canvas/task_bar.rs +++ b/crates/ui-egui/src/canvas/task_bar.rs @@ -92,6 +92,31 @@ fn smooth_tool_on_paths(app: &VectorcraftApp, ctx: &egui::Context) -> bool { found } +/// Whether the selection holds images together with other objects, for which the bar offers Make +/// Clipping Mask: at least one selected object is an image and at least one is not (a selected id +/// with no object counts as not an image). The walk stops once it has seen both. The answer is kept +/// in `ctx` for the document's revision, as [`smooth_tool_on_paths`] keeps its own. +pub(crate) fn images_with_other_art(st: &vectorcraft_engine::DocState, ctx: &egui::Context) -> bool { + let id = task_bar_id().with("mixed"); + let key = (st.uid, st.revision); + if let Some((k, found)) = ctx.data(|d| d.get_temp::<((u64, u64), bool)>(id)) + && k == key + { + return found; + } + let (mut image, mut other) = (false, false); + let found = st.selection.objects.iter().any(|id| { + if st.doc.node(*id).is_some_and(|o| matches!(o.kind, NodeKind::Image(_))) { + image = true; + } else { + other = true; + } + image && other + }); + ctx.data_mut(|d| d.insert_temp(id, (key, found))); + found +} + /// Whether the bar shows its blank canvas actions, Draw (Pencil) and Place Image: a selection tool is /// in use and the active document has no artwork, only layers and guides. fn blank_canvas(app: &VectorcraftApp) -> bool { @@ -192,10 +217,7 @@ pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) { _ => None, }); // Images and vector art selected together: a clipping mask is the likely next step. - let mixed = n > 1 && { - let images = st.selection.objects.iter().filter_map(|id| st.doc.node(*id)).filter(|o| matches!(o.kind, NodeKind::Image(_))).count(); - images > 0 && images < n - }; + let mixed = n > 1 && images_with_other_art(st, ui.ctx()); // An Image Trace object: the group the engine names "Image Trace", its source image first. let is_trace = is_group && first.as_ref().is_some_and(|f| { diff --git a/crates/ui-egui/src/tests/taskbar.rs b/crates/ui-egui/src/tests/taskbar.rs index 8230969c97..bc4734db5a 100644 --- a/crates/ui-egui/src/tests/taskbar.rs +++ b/crates/ui-egui/src/tests/taskbar.rs @@ -215,6 +215,185 @@ fn an_image_with_vector_art_offers_make_clipping_mask() { assert!(has(&texts, "Unite") && !has(&texts, "Make Clipping Mask"), "{texts:?}"); } +/// Places a 2 by 2 pixel image from `dir` and returns its id. +fn place_image(app: &mut VectorcraftApp, dir: &crate::tests_folder::Folder) -> u64 { + let raw = [0u8, 128, 255, 255].repeat(4); + let image = craft_image_codecs::Image::from_raw(2, 2, craft_image_codecs::ChannelLayout::Rgba, craft_image_codecs::SampleType::U8, raw).unwrap(); + let png = craft_image_codecs::encode(&image, craft_image_codecs::Format::Png, &craft_image_codecs::EncodeOptions::default()).unwrap(); + let path = dir.file("tile.png", &png); + app.services.read = Some(Box::new(|p: &str| std::fs::read(p).map_err(|e| e.to_string()))); + app.run("file.place", json!({"path": path, "link": false})).unwrap(); + let img = app.session.active().unwrap().selection.objects[0].0; + assert!(matches!(kind(app, img), NodeKind::Image(_))); + img +} + +/// Whether the bar offers Make Clipping Mask, worked out by counting the selected images: some of +/// the selected ids, but not all, are images. +fn mixed_by_count(st: &vectorcraft_engine::DocState) -> bool { + let n = st.selection.len(); + let images = st.selection.objects.iter().filter_map(|id| st.doc.node(*id)).filter(|o| matches!(o.kind, NodeKind::Image(_))).count(); + images > 0 && images < n +} + +/// Sets the selected objects and anchors directly, as no command can select an id with no object, +/// and moves the document's revision as every selection change does. +fn set_selection(app: &mut VectorcraftApp, ids: &[u64], anchors: &[u64]) { + let st = app.session.active_mut().unwrap(); + st.selection.objects = ids.iter().map(|i| NodeId(*i)).collect(); + st.selection.anchors = anchors.iter().map(|i| (NodeId(*i), [(0, 0)].into_iter().collect())).collect(); + st.revision += 1; +} + +/// The task bar's check for images selected with other objects gives the count's answer for every +/// selection: empty, one object, paths only, images only, images with paths or type, an id +/// selected twice, anchors picked out, and ids with no object. +#[test] +fn images_with_other_art_matches_the_image_count() { + let mut app = app(); + let dir = crate::tests_folder::Folder::new("ui-taskbar-mixed"); + let img = place_image(&mut app, &dir); + let img2 = place_image(&mut app, &dir); + let a = id(app.run("shape.rectangle", json!({"x": 10, "y": 200, "width": 40, "height": 40})).unwrap()); + let b = id(app.run("shape.rectangle", json!({"x": 30, "y": 210, "width": 40, "height": 40})).unwrap()); + let t = id(app.run("text.create", json!({"x": 60, "y": 80, "text": "Hello"})).unwrap()); + let stale = 1_000_000; + assert!(app.session.active().unwrap().doc.node(NodeId(stale)).is_none()); + let ctx = egui::Context::default(); + let cases: [(&[u64], &[u64], bool); 17] = [ + (&[], &[], false), + (&[a], &[], false), + (&[img], &[], false), + (&[a, b], &[], false), + (&[img, img2], &[], false), + (&[img, a], &[], true), + (&[a, img], &[], true), + (&[a, b, img], &[], true), + (&[img, t], &[], true), + (&[img, img], &[], false), + (&[img, img, a], &[], true), + (&[img, a], &[a], true), + (&[a, b], &[a, b], false), + (&[img, stale], &[], true), + (&[img, img2, stale], &[], true), + (&[a, stale], &[], false), + (&[stale, stale], &[], false), + ]; + for (ids, anchors, mixed) in cases { + set_selection(&mut app, ids, anchors); + let st = app.session.active().unwrap(); + assert_eq!(mixed_by_count(st), mixed, "{ids:?} with anchors on {anchors:?}: the count"); + assert_eq!(canvas::images_with_other_art(st, &ctx), mixed, "{ids:?} with anchors on {anchors:?}"); + } +} + +/// The check is worked out once for each revision of the document: an unchanged revision gives the +/// kept answer, and a selection change, which moves the revision, works it out again. +#[test] +fn images_with_other_art_is_kept_for_the_revision() { + let mut app = app(); + let dir = crate::tests_folder::Folder::new("ui-taskbar-mixed-kept"); + let img = place_image(&mut app, &dir); + let a = id(app.run("shape.rectangle", json!({"x": 10, "y": 200, "width": 40, "height": 40})).unwrap()); + let b = id(app.run("shape.rectangle", json!({"x": 30, "y": 210, "width": 40, "height": 40})).unwrap()); + select(&mut app, &[img, a]); + let ctx = egui::Context::default(); + assert!(canvas::images_with_other_art(app.session.active().unwrap(), &ctx)); + // Changing the objects behind the revision's back shows the kept answer is used. + app.session.active_mut().unwrap().selection.objects = vec![NodeId(a), NodeId(b)]; + assert!(canvas::images_with_other_art(app.session.active().unwrap(), &ctx), "the revision's answer is kept"); + select(&mut app, &[a, b]); + assert!(!canvas::images_with_other_art(app.session.active().unwrap(), &ctx), "a new revision works it out again"); + select(&mut app, &[b, img]); + assert!(canvas::images_with_other_art(app.session.active().unwrap(), &ctx)); + // Another context keeps its own answer. + assert!(canvas::images_with_other_art(app.session.active().unwrap(), &egui::Context::default())); +} + +/// The CPU time this thread has used, where the system reports it (Linux), else none. +fn cpu_time() -> Option<std::time::Duration> { + std::fs::read_to_string("/proc/thread-self/schedstat") + .ok() + .and_then(|s| s.split_whitespace().next()?.parse::<u64>().ok()) + .map(std::time::Duration::from_nanos) +} + +/// Runs `f` and returns the CPU time it used (zero where the system does not report it) and the +/// time it took. +fn timed(f: impl FnOnce()) -> (std::time::Duration, std::time::Duration) { + let (cpu, wall) = (cpu_time(), std::time::Instant::now()); + f(); + let wall = wall.elapsed(); + (cpu_time().zip(cpu).map_or_else(Default::default, |(b, a)| b.saturating_sub(a)), wall) +} + +/// Times the image check on a selection of 131,072 rectangles: 120 frames with an unchanged +/// revision, counting each frame as before against the kept answer, and the first frame after a +/// change. Each cell is the median of 7 runs, CPU time then elapsed time. Run with +/// `cargo test -p vectorcraft-ui-egui --lib images_with_other_art_timing -- --ignored --nocapture`. +#[test] +#[ignore = "a timing run on a large selection"] +fn images_with_other_art_timing() { + let dir = crate::tests_folder::Folder::new("ui-taskbar-mixed-timing"); + let doubled = |app: &mut VectorcraftApp, times: usize| { + for _ in 0..times { + app.run("select.all", json!({})).unwrap(); + app.run("edit.duplicate", json!({})).unwrap(); + } + app.run("select.all", json!({})).unwrap(); + }; + let rects = |app: &mut VectorcraftApp| { + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap(); + doubled(app, 17); + }; + let mut variants: Vec<(&str, VectorcraftApp)> = vec![]; + let mut none = app(); + rects(&mut none); + variants.push(("131,072 rectangles", none)); + let mut one = app(); + rects(&mut one); + place_image(&mut one, &dir); + one.run("select.all", json!({})).unwrap(); + variants.push(("131,072 rectangles and 1 image", one)); + let mut images = app(); + place_image(&mut images, &dir); + doubled(&mut images, 9); + variants.push(("512 images", images)); + let median = |mut v: Vec<(std::time::Duration, std::time::Duration)>| { + let mut wall: Vec<_> = v.iter().map(|t| t.1).collect(); + v.sort(); + wall.sort(); + format!("{:.2?} / {:.2?}", v[v.len() / 2].0, wall[wall.len() / 2]) + }; + println!("| Selection | Count, 120 frames | Kept, 120 frames | Count, 1 frame | First frame after a change |"); + println!("| --- | --- | --- | --- | --- |"); + for (name, mut app) in variants { + let mut runs = [vec![], vec![], vec![], vec![]]; + for _ in 0..7 { + let ctx = egui::Context::default(); + let st = app.session.active().unwrap(); + let expected = mixed_by_count(st); + assert_eq!(canvas::images_with_other_art(st, &ctx), expected, "{name}"); + runs[0].push(timed(|| { + for _ in 0..120 { + assert_eq!(std::hint::black_box(mixed_by_count(st)), expected); + } + })); + runs[1].push(timed(|| { + for _ in 0..120 { + assert_eq!(std::hint::black_box(canvas::images_with_other_art(st, &ctx)), expected); + } + })); + runs[2].push(timed(|| assert_eq!(std::hint::black_box(mixed_by_count(st)), expected))); + app.session.active_mut().unwrap().revision += 1; + let st = app.session.active().unwrap(); + runs[3].push(timed(|| assert_eq!(std::hint::black_box(canvas::images_with_other_art(st, &ctx)), expected))); + } + let [a, b, c, d] = runs.map(median); + println!("| {name} ({} selected) | {a} | {b} | {c} | {d} |", app.session.active().unwrap().selection.len()); + } +} + #[test] fn type_converts_between_point_and_area_type() { let mut app = app(); From b4fda766b69f2370e14d7a531744eb5f60d16089 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 17 Nov 2026 14:23:03 -0800 Subject: [PATCH 139/176] Document Setup: a grid color box opens the picker on a named preset's color When Document Setup's gridColors field holds a preset name (any case, as document.setup takes it), the Transparency tab now replaces it with the preset's two colors. The hex fields show them, a color box opens the Color Picker on its color instead of white, and the picker's OK sets that color instead of failing with "no such color". --- crates/ui-egui/src/dialogs/document_setup.rs | 23 ++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/crates/ui-egui/src/dialogs/document_setup.rs b/crates/ui-egui/src/dialogs/document_setup.rs index 9124fce05a..8dee8d9962 100644 --- a/crates/ui-egui/src/dialogs/document_setup.rs +++ b/crates/ui-egui/src/dialogs/document_setup.rs @@ -191,6 +191,13 @@ fn transparency(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) { widgets::subheader(ui, tl!("Transparency Grid")); let sizes: Vec<(&str, &str)> = GridSize::ALL.iter().map(|g| (g.id(), g.label())).collect(); choice(ui, d, "gridSize", tl!("Grid Size:"), &sizes); + // A preset name in the fields (any case, as `document.setup` takes it) becomes the preset's two + // colors, which the hex fields and the Color Picker edit one at a time. + if let Some((_, pair)) = + d.fields.get("gridColors").and_then(Value::as_str).and_then(|n| GRID_COLOR_PRESETS.iter().find(|(p, _)| p.eq_ignore_ascii_case(n))) + { + d.fields.insert("gridColors".into(), json!(pair.map(|c| c.to_hex()))); + } let colors = grid_colors(d); let preset = GRID_COLOR_PRESETS .iter() @@ -776,6 +783,22 @@ mod tests { } } + /// With a preset name in Document Setup's `gridColors` field, the grid color boxes show the + /// preset's colors, and the Color Picker opens on the clicked one; its OK sets that color and + /// keeps the preset's other one. + #[test] + fn a_grid_color_box_opens_the_picker_when_the_field_names_a_preset() { + let (mut app, ctx) = transparency_tab(); + app.ui.dialog.as_mut().unwrap().fields.insert("gridColors".into(), json!("blue")); + dialog_frame(&mut app, &ctx, vec![]); + click_grid_box(&mut app, &ctx, 1); + assert_picker_over_setup(&app, "#c4dcff", "blue"); + app.ui.dialog.as_mut().unwrap().fields.insert("color".into(), json!("#00ff00")); + crate::dialogs::confirm(&mut app).unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + assert_eq!((d.kind.as_str(), dialog_grid(d)), (super::KIND, ["#ffffff", "#00ff00"].map(hex).to_vec())); + } + /// Clicks the hex field that shows `digits` and types `typed` over its text, leaving the edit /// pending; returns the field's id. fn type_into_hex_field(app: &mut VectorcraftApp, ctx: &egui::Context, digits: &str, typed: &str) -> egui::Id { From dd810ea4bb25d596e63bf6e9eb719cf05d1e30bd Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 17 Nov 2026 14:30:14 -0800 Subject: [PATCH 140/176] .ai save: resolve each run's font once per font Saving a .ai file resolves the font of every run of type twice: once for its font record and once to check that the font comes back as itself. Each resolution looks the face up, reads its axes and name table, and scans the loaded faces by PostScript name, so a document with tens of thousands of runs in a few fonts repeated the same lookups for every run. The text document now keeps what each style's font fields (family, style, version and Variable Font settings, each setting by the bits of its value) resolve to for the whole save, and reuses it while the font database's generation is unchanged. A font added or loaded during the save resolves it again. The font set is still searched and filled as before, so its order, indices and rollback are unchanged. The output is unchanged. - Tests: a save resolves as many fonts for one row of type as for four; the program, header, warnings and private data are the same as with every run's font resolved again (many fonts, threaded type, envelopes of type, and type taken back when an envelope is written as its art); each resolved record and check equals the uncached one for static and variable fonts, settings outside the axis range, not a number, +0 and -0, and a missing family, and a value resolved before the font database changed is resolved again. An ignored test times the save of 10,000 point type objects in three runs over four fonts. --- crates/eps/src/ai_editing/tests.rs | 186 ++++++++++++++++++++++ crates/eps/src/ai_editing/writer.rs | 4 +- crates/eps/src/ai_editing/writer/texts.rs | 155 +++++++++++++++++- 3 files changed, 336 insertions(+), 9 deletions(-) diff --git a/crates/eps/src/ai_editing/tests.rs b/crates/eps/src/ai_editing/tests.rs index 3ddc8636c8..aa08b3e6b6 100644 --- a/crates/eps/src/ai_editing/tests.rs +++ b/crates/eps/src/ai_editing/tests.rs @@ -11170,6 +11170,192 @@ fn variable_font_instances_name_their_design_space() { ); } +/// Style 12 pt black in family `family` and style `style`, with the Variable Font settings `axes`. +fn font_style(family: &str, style: &str, axes: &[(&str, f64)]) -> vectorcraft_doc::CharStyle { + vectorcraft_doc::CharStyle { + font_family: family.into(), + font_style: style.into(), + font_axes: axes.iter().map(|(t, v)| (t.to_string(), *v)).collect(), + ..style_of(12.0) + } +} + +/// A document of `k` rows 30 pt apart, each with point type in three runs (Source Sans 3 Regular +/// and Bold, and the variable test font's Bold at a weight of 650), point type in four (Inter +/// Medium, the variable test font's Bold at 500 and at a weight that differs from 500 by less than +/// the font record's precision, and a family that isn't installed), and area type threaded through +/// two frames in Bold and the variable test font's Regular. +fn fonted_document(k: usize) -> Document { + use vectorcraft_doc::{TextKind, TextObject, TextRun}; + use vectorcraft_geom::Point; + use vectorcraft_text::test_fonts::{VARIABLE_FAMILY, variable_font}; + vectorcraft_text::FontDb::global().add_font(variable_font().unwrap()); + let (regular, bold) = (style_of(12.0), font_style("Source Sans 3", "Bold", &[])); + let mut doc = Document::new(400.0, 30.0 * k as f64 + 30.0); + let layer = doc.layers[0].id; + for i in 0..k { + let y = 20.0 + 30.0 * i as f64; + let mut three = TextObject::point(Point::new(10.0, y), "", regular.clone()); + three.runs = vec![ + TextRun::new("One ", regular.clone()), + TextRun::new("two ", bold.clone()), + TextRun::new("three", font_style(VARIABLE_FAMILY, "Bold", &[("wght", 650.0)])), + ]; + let mut four = TextObject::point(Point::new(100.0, y), "", regular.clone()); + four.runs = vec![ + TextRun::new("four ", font_style("Inter", "Medium", &[])), + TextRun::new("five ", font_style(VARIABLE_FAMILY, "Bold", &[("wght", 500.0)])), + TextRun::new("six ", font_style(VARIABLE_FAMILY, "Bold", &[("wght", 500.000_001)])), + TextRun::new("seven", font_style("No Such Family", "Bold", &[])), + ]; + let mut first = TextObject::point(Point::ZERO, "", bold.clone()); + first.runs = vec![TextRun::new("eight nine ", bold.clone()), TextRun::new("ten", font_style(VARIABLE_FAMILY, "Regular", &[]))]; + first.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(250.0, y - 10.0, 315.0, y + 10.0)) }; + first.xf = Affine::IDENTITY; + let mut second = first.clone(); + second.runs = vec![TextRun::new("", bold.clone())]; + second.kind = TextKind::Area { frame: shapes::rectangle(Rect::new(325.0, y - 10.0, 390.0, y + 10.0)) }; + let nodes = [text_node(&mut doc, three), text_node(&mut doc, four), text_node(&mut doc, first), text_node(&mut doc, second)]; + doc.text_threads.push(vec![nodes[2].id, nodes[3].id]); + for n in nodes { + doc.insert(Some(layer), usize::MAX, n).unwrap(); + } + } + doc +} + +/// A save resolves the font of each style once, however many runs are set in it: as many fonts are +/// resolved (font records and checks that a font comes back) for one row of type as for four. Two +/// weights of a variable font that the font record writes as one number are one font written. +#[test] +fn a_save_resolves_each_font_once() { + // How many fonts a save of `doc` resolves, in a save during which the font database didn't change. + let resolves = |doc: &Document| { + let db = vectorcraft_text::FontDb::global(); + for _ in 0..20 { + let before = db.generation(); + writer::FONT_RESOLVES.set(0); + export_ai_editing(doc, &opts()).unwrap(); + if db.generation() == before { + return writer::FONT_RESOLVES.get(); + } + } + panic!("the font database changed during every save"); + }; + let one = resolves(&fonted_document(1)); + let doc = fonted_document(4); + let four = resolves(&doc); + assert!(one > 0); + assert_eq!(four, one, "fonts resolved with one row of type and with four"); + let td = text_document(&program(&doc)); + // 650 × 65536 and 500 × 65536. + assert_eq!(td.matches("VaritestSans-Bold) /2 1 /4 [ 42598400 ]").count(), 1, "{td}"); + assert_eq!(td.matches("VaritestSans-Bold) /2 1 /4 [ 32768000 ]").count(), 1, "{td}"); + assert_eq!(td.matches("/CoolTypeFont").count(), 8, "seven fonts and the hidden characters' font: {td}"); +} + +/// A save that resolves each style's font once writes the same program, header, warnings and private +/// data as one that resolves the font of every run again: with type in many fonts, threaded type, +/// type in envelopes, and type taken out again when an envelope is written as its art. +#[test] +fn a_save_writes_the_same_with_each_font_resolved_once() { + use vectorcraft_doc::live::EnvelopeKind; + let save = |doc: &Document, each_run: bool| { + writer::RESOLVE_EACH_RUN.set(each_run); + let out = export_ai_editing(doc, &opts()).unwrap(); + let private = private_data(doc, &opts()).unwrap(); + writer::RESOLVE_EACH_RUN.set(false); + (out.program, out.header, out.warnings, private.0.data, private.1) + }; + let mut docs = vec![sample(), typed(), fonted_document(3)]; + for (_, kind) in live_envelope_kinds() { + for editing in [false, true] { + let mut doc = Document::new(200.0, 100.0); + let envelope = typed_envelope_node(&mut doc, kind.clone(), editing); + docs.push(alone(envelope)); + } + } + for doc in &docs { + let (once, again) = (save(doc, false), save(doc, true)); + assert!(once == again, "{}", String::from_utf8_lossy(&once.0)); + } + // An envelope of type one object short of room: it is written as its art, and its story and fonts + // are taken out again. + let kind = EnvelopeKind::Mesh { rows: 2, cols: 3, points: envelope_points(2, 3), handles: vec![] }; + let mut doc = Document::new(200.0, 100.0); + let envelope = typed_envelope_node(&mut doc, kind, false); + let doc = alone(envelope); + let read = crate::import::objects_read(&export_ai_editing(&doc, &opts()).unwrap().program).unwrap(); + let within = |each_run: bool| { + writer::RESOLVE_EACH_RUN.set(each_run); + let out = export_within(&doc, &opts(), read - 1).unwrap(); + writer::RESOLVE_EACH_RUN.set(false); + (out.program, out.warnings) + }; + let (once, again) = (within(false), within(true)); + assert!(once.1.iter().any(|w| w == writer::OBJECT_LIMIT), "{:?}", once.1); + assert!(once == again, "{}", String::from_utf8_lossy(&once.0)); +} + +/// The CPU time of saving a document of 10,000 point type objects, each in three runs drawn in turn +/// from four fonts (Source Sans 3 Regular and Bold, Inter Medium, and the variable test font's Bold +/// at a weight of 650), with each style's font resolved once and with the font of every run +/// resolved again: the median of 7 runs of each, alternating. +/// Run with `cargo test -p vectorcraft-eps --lib -- --ignored --nocapture font_resolve_time`. +#[test] +#[ignore = "timing; run by hand"] +fn font_resolve_time() { + use vectorcraft_doc::{TextObject, TextRun}; + use vectorcraft_text::test_fonts::{VARIABLE_FAMILY, variable_font}; + vectorcraft_text::FontDb::global().add_font(variable_font().unwrap()); + let fonts = [ + style_of(12.0), + font_style("Source Sans 3", "Bold", &[]), + font_style("Inter", "Medium", &[]), + font_style(VARIABLE_FAMILY, "Bold", &[("wght", 650.0)]), + ]; + let mut doc = Document::new(2000.0, 2000.0); + let layer = doc.layers[0].id; + for i in 0..10_000usize { + let (x, y) = ((i % 100) as f64 * 20.0, (i / 100) as f64 * 20.0 + 10.0); + let mut t = TextObject::point(vectorcraft_geom::Point::new(x, y), "", fonts[0].clone()); + t.runs = (0..3).map(|r| TextRun::new(["ab ", "cd ", "ef"][r], fonts[(i + r) % fonts.len()].clone())).collect(); + let n = text_node(&mut doc, t); + doc.insert(Some(layer), usize::MAX, n).unwrap(); + } + // The CPU time this thread has run, in nanoseconds: Linux's scheduler statistics, else the clock. + let start = std::time::Instant::now(); + let cpu = || { + std::fs::read_to_string("/proc/thread-self/schedstat") + .ok() + .and_then(|s| s.split_whitespace().next().and_then(|n| n.parse::<u64>().ok())) + .unwrap_or_else(|| u64::try_from(start.elapsed().as_nanos()).unwrap_or(u64::MAX)) + }; + // A first save loads the faces the document names. + export_ai_editing(&doc, &opts()).unwrap(); + let mut times: [Vec<u64>; 2] = [vec![], vec![]]; + let mut resolves = [0, 0]; + let mut outputs: [Vec<u8>; 2] = [vec![], vec![]]; + for _ in 0..7 { + for (k, each_run) in [(0, true), (1, false)] { + writer::RESOLVE_EACH_RUN.set(each_run); + writer::FONT_RESOLVES.set(0); + let t = cpu(); + let out = export_ai_editing(&doc, &opts()).unwrap(); + times[k].push(cpu() - t); + resolves[k] = writer::FONT_RESOLVES.get(); + outputs[k] = out.program; + } + } + writer::RESOLVE_EACH_RUN.set(false); + assert!(outputs[0] == outputs[1]); + for (k, label) in [(0, "resolved for every run"), (1, "resolved once")] { + times[k].sort_unstable(); + let ms: Vec<String> = times[k].iter().map(|t| format!("{:.1}", *t as f64 / 1e6)).collect(); + println!("{label}: median {:.1} ms CPU, {} fonts resolved, runs {}", times[k][3] as f64 / 1e6, resolves[k], ms.join(" ")); + } +} + fn style_of(size: f64) -> vectorcraft_doc::CharStyle { style(size, Color::BLACK) } diff --git a/crates/eps/src/ai_editing/writer.rs b/crates/eps/src/ai_editing/writer.rs index 39c3157350..a5a592118c 100644 --- a/crates/eps/src/ai_editing/writer.rs +++ b/crates/eps/src/ai_editing/writer.rs @@ -50,7 +50,7 @@ pub(super) use paints::{ #[cfg(test)] pub(super) use symbols::{MISSING_SYMBOL, SYMBOL_ART, SYMBOL_COUNT, SYMBOL_OPTIONS}; #[cfg(test)] -pub(super) use texts::TYPE_ATTRIBUTES; +pub(super) use texts::{FONT_RESOLVES, RESOLVE_EACH_RUN, TYPE_ATTRIBUTES}; #[cfg(test)] pub(super) use variables::{ACTIVE, BINDINGS, LIMITS, VALUES}; @@ -1604,7 +1604,7 @@ impl<'a> Writer<'a> { let placed = self.texts.thread(doc, thread, n.id, self.canvas, &|id| !cut_to_clipping_object(doc, id), &self.wraps_held); placed.map(|p| (p, self.texts.take_lost())) } else { - self.texts.add(t, self.canvas).map(|story| ((story, 0), texts::loses(t))) + self.texts.add(t, self.canvas).map(|story| ((story, 0), self.texts.loses(t))) }; let Some(((story, frame), lost)) = placed else { // The text document can't hold it: the outlines count their own objects. diff --git a/crates/eps/src/ai_editing/writer/texts.rs b/crates/eps/src/ai_editing/writer/texts.rs index e9d2dcf38c..226e90b4d2 100644 --- a/crates/eps/src/ai_editing/writer/texts.rs +++ b/crates/eps/src/ai_editing/writer/texts.rs @@ -445,8 +445,9 @@ fn held_aki(v: f64) -> f64 { if v.is_nan() { 0.0 } else { v.clamp(0.0, MAX_AKI) } } -/// Has type `t` attributes the text document leaves out ([`TYPE_ATTRIBUTES`])? -pub(in crate::ai_editing) fn loses(t: &TextObject) -> bool { +/// Has type `t` attributes the text document leaves out ([`TYPE_ATTRIBUTES`])? `fonts` holds the +/// fonts already resolved. +fn loses(t: &TextObject, fonts: &mut ResolvedFonts) -> bool { // Small capitals are read back at Document Setup's default size. let default_small_caps = vectorcraft_doc::DocSetup::default().small_caps_size; // A run's style as the text document holds it: every other attribute at its default. A color @@ -484,7 +485,7 @@ pub(in crate::ai_editing) fn loses(t: &TextObject) -> bool { ..CharStyle::default() } }; - let run_lost = |s: &CharStyle| { + let mut run_lost = |s: &CharStyle| { let stroked = !s.stroke.is_none(); // Without a stroke, its weight, cap, join and miter limit draw nothing: nothing is lost. let unstroked = CharStyle::default(); @@ -501,7 +502,7 @@ pub(in crate::ai_editing) fn loses(t: &TextObject) -> bool { }; // A Lab color is written as RGB. let lab = |p: &Paint| matches!(p, Paint::Solid { color: Color::Lab { .. }, .. }); - s != held_char(&s) || lab(&s.fill) || lab(&s.stroke) || !font_kept(&s) + s != held_char(&s) || lab(&s.fill) || lab(&s.stroke) || !fonts.kept(&s) }; // A paragraph's style as the text document holds it, and its text: aligned to the start of // its direction (Auto) without a direction of its own, it comes back aligned left, which @@ -669,6 +670,84 @@ fn font_kept(st: &CharStyle) -> bool { && face(&family, &style, read.as_deref()) == face(&st.font_family, &st.font_style, st.font_version.as_deref()) } +/// The font fields of a style, as [`ResolvedFonts`] keeps what they resolve to: the family, style +/// and version, and each Variable Font setting as the bits of its value, so two settings that +/// differ are two keys even where they are written as one number. +#[derive(PartialEq, Eq, Hash)] +struct FontKey { + family: String, + style: String, + version: Option<String>, + axes: Vec<(String, u64)>, +} + +impl FontKey { + fn of(st: &CharStyle) -> Self { + FontKey { + family: st.font_family.clone(), + style: st.font_style.clone(), + version: st.font_version.clone(), + axes: st.font_axes.iter().map(|(tag, v)| (tag.clone(), v.to_bits())).collect(), + } + } +} + +/// What one style's font fields resolved to, each with the font database's generation +/// ([`vectorcraft_text::FontDb::generation`]) when it was resolved. +#[derive(Default)] +struct Resolved { + /// Its font record ([`font_name`]). + record: Option<(u64, FontRecord)>, + /// Whether its font comes back as itself ([`font_kept`]). + kept: Option<(u64, bool)>, +} + +/// The fonts of the styles written so far, each resolved once for the whole save. A value is used +/// again only while the font database's generation is the one it was resolved in: fonts added or +/// loaded since then resolve it again. +#[derive(Default)] +struct ResolvedFonts(HashMap<FontKey, Resolved>); + +#[cfg(test)] +thread_local! { + /// While set on this thread, [`ResolvedFonts`] keeps nothing: every run's font is resolved again. + pub(in crate::ai_editing) static RESOLVE_EACH_RUN: std::cell::Cell<bool> = const { std::cell::Cell::new(false) }; + /// How many times [`ResolvedFonts`] has resolved a font record or checked a font on this thread. + pub(in crate::ai_editing) static FONT_RESOLVES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; +} + +impl ResolvedFonts { + /// The value `slot` holds for the font of style `st` when it was resolved in the font + /// database's current generation, else `resolve(st)`, kept for later runs. + fn get<T>(&mut self, st: &CharStyle, slot: fn(&mut Resolved) -> &mut Option<(u64, T)>, resolve: fn(&CharStyle) -> T) -> &T { + let now = vectorcraft_text::FontDb::global().generation(); + let held = slot(self.0.entry(FontKey::of(st)).or_default()); + #[cfg(test)] + if RESOLVE_EACH_RUN.get() { + *held = None; + } + if held.as_ref().is_some_and(|(generation, _)| *generation != now) { + *held = None; + } + let (_, value) = held.get_or_insert_with(|| { + #[cfg(test)] + FONT_RESOLVES.set(FONT_RESOLVES.get() + 1); + (now, resolve(st)) + }); + value + } + + /// The font record of style `st` ([`font_name`]). + fn record(&mut self, st: &CharStyle) -> &FontRecord { + self.get(st, |r| &mut r.record, font_name) + } + + /// Whether the font of style `st` comes back as itself ([`font_kept`]). + fn kept(&mut self, st: &CharStyle) -> bool { + *self.get(st, |r| &mut r.kept, font_kept) + } +} + /// Whether `c` is a strong right-to-left letter (`Some(true)`: Hebrew, Arabic, Syriac, Thaana, NKo /// and their presentation forms) or a strong left-to-right one (`Some(false)`: any other letter). fn strong_direction(c: char) -> Option<bool> { @@ -761,6 +840,8 @@ pub(in crate::ai_editing) struct TextDoc { /// reader counts in them. doc_bytes: usize, doc_values: usize, + /// The fonts of the styles written so far, as they resolve. + resolved: ResolvedFonts, } impl TextDoc { @@ -768,9 +849,14 @@ impl TextDoc { self.stories.is_empty() } + /// Has type `t` attributes the text document leaves out ([`loses`])? + pub(in crate::ai_editing) fn loses(&mut self, t: &TextObject) -> bool { + loses(t, &mut self.resolved) + } + /// The index of the font of `st` in the font set. fn font(&mut self, st: &CharStyle) -> i64 { - let font = font_name(st); + let font = self.resolved.record(st); // Two installed versions of one font are two fonts, so each keeps its own `/5`. let same = |f: &FontRecord| { f.name == font.name && f.version == font.version && f.design.iter().map(|v| fixed(*v)).eq(font.design.iter().map(|v| fixed(*v))) @@ -778,7 +864,7 @@ impl TextDoc { let i = match self.fonts.iter().position(same) { Some(i) => i, None => { - self.fonts.push(font); + self.fonts.push(font.clone()); self.fonts.len() - 1 } }; @@ -1156,7 +1242,7 @@ impl TextDoc { if !whole.runs.iter().any(|r| r.text.chars().any(|c| !c.is_whitespace())) || !self.room(&whole, texts.len()) { return None; } - let lost = split_differs || texts.iter().any(|t| loses(t)); + let lost = split_differs || texts.iter().any(|t| loses(t, &mut self.resolved)); let frames: Vec<usize> = texts.iter().map(|t| self.frame(t, canvas, scale)).collect(); let story = self.story(&whole, &frames, scale); if !self.fits(mark) { @@ -1351,3 +1437,58 @@ pub(in crate::ai_editing) fn stub(s: &mut String, story: usize, frame: usize, t: } s.push_str("2 /TextAntialiasing ,\n;\n"); } + +#[cfg(test)] +mod tests { + use super::*; + + /// A style's font resolved through [`ResolvedFonts`], the first time and again, is the font + /// record and the check [`font_name`] and [`font_kept`] give for it: static and variable fonts, + /// a version of their own, Variable Font settings within and outside the axis's range, not a + /// number, +0 and -0, an axis the font doesn't have, and a family that isn't installed. A font + /// resolved before the font database last changed is resolved again. + #[test] + fn resolved_fonts_are_the_fonts_resolved_for_each_run() { + use vectorcraft_text::test_fonts::{VARIABLE_FAMILY, variable_font}; + vectorcraft_text::FontDb::global().add_font(variable_font().unwrap()); + let font = |family: &str, style: &str, version: Option<&str>, axes: &[(&str, f64)]| CharStyle { + font_family: family.into(), + font_style: style.into(), + font_version: version.map(str::to_owned), + font_axes: axes.iter().map(|(t, v)| (t.to_string(), *v)).collect(), + ..CharStyle::default() + }; + let styles = [ + CharStyle::default(), + font("Source Sans 3", "Bold", None, &[]), + font("Inter", "Medium", None, &[]), + font(VARIABLE_FAMILY, "Regular", None, &[]), + font(VARIABLE_FAMILY, "Bold", Some("Version 1.000"), &[]), + font(VARIABLE_FAMILY, "Bold", None, &[("wght", 650.0)]), + font(VARIABLE_FAMILY, "Bold", None, &[("wght", 900.0)]), + font(VARIABLE_FAMILY, "Bold", None, &[("wght", f64::NAN)]), + font(VARIABLE_FAMILY, "Bold", None, &[("wght", 0.0)]), + font(VARIABLE_FAMILY, "Bold", None, &[("wght", -0.0)]), + font(VARIABLE_FAMILY, "Bold", None, &[("wdth", 80.0), ("wght", 500.0)]), + font("No Such Family", "Bold", None, &[]), + font("No Such Family", "", Some("2.0"), &[]), + ]; + let mut fonts = ResolvedFonts::default(); + for round in ["first", "again"] { + for st in &styles { + assert_eq!(fonts.record(st), &font_name(st), "{round}: {st:?}"); + assert_eq!(fonts.kept(st), font_kept(st), "{round}: {st:?}"); + } + } + assert_eq!(fonts.0.len(), styles.len(), "each style's font fields are a key of their own"); + // What was resolved before the font database last changed is resolved again. + let stale = vectorcraft_text::FontDb::global().generation().wrapping_sub(1); + let wrong = FontRecord { name: "Wrong".into(), truetype: false, design: vec![], version: String::new() }; + for st in &styles { + let held = fonts.0.entry(FontKey::of(st)).or_default(); + (held.record, held.kept) = (Some((stale, wrong.clone())), Some((stale, !font_kept(st)))); + assert_eq!(fonts.record(st), &font_name(st), "{st:?}"); + assert_eq!(fonts.kept(st), font_kept(st), "{st:?}"); + } + } +} From d65c87b9c965c544ee4e466d69a615ad4799dd2a Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 17 Nov 2026 14:26:45 -0800 Subject: [PATCH 141/176] Control bar: a click on the X, Y, W or H label opens the Transform panel A click on the Control bar's X:, Y:, W: or H: label, with objects selected or with the Artboard tool, opens the Transform panel in a popover under the label, as the Transform link does; a second click closes it. The help page (https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=374) describes these labels as another way to bring up the Transform panel. The click no longer gives the field the keyboard. A drag on the label still scrubs the field, and the labels are not tab stops, so Tab still moves from one field to the next. --- crates/ui-egui/src/chrome/control_bar.rs | 13 +++-- crates/ui-egui/src/chrome/tests.rs | 56 ++++++++++++++++++++ crates/ui-egui/src/panels/artboards.rs | 9 +++- crates/ui-egui/src/panels/artboards/tests.rs | 26 +++++++++ crates/ui-egui/src/panels/transform.rs | 8 ++- crates/ui-egui/src/scrub.rs | 33 +++++++++--- crates/ui-egui/src/widgets.rs | 2 +- crates/ui-egui/src/widgets/labels.rs | 8 +++ docs/target-app-parity.md | 3 +- 9 files changed, 144 insertions(+), 14 deletions(-) diff --git a/crates/ui-egui/src/chrome/control_bar.rs b/crates/ui-egui/src/chrome/control_bar.rs index ff7d58dfec..2ecc09f5a3 100644 --- a/crates/ui-egui/src/chrome/control_bar.rs +++ b/crates/ui-egui/src/chrome/control_bar.rs @@ -188,9 +188,9 @@ const INLINE_FIELD_WIDTH: f32 = 80.0; /// The keys and labels of the Control bar's inline X/Y/W/H fields, in their order. const INLINE_FIELDS: [(&str, &str); 4] = [("x", "X:"), ("y", "Y:"), ("width", "W:"), ("height", "H:")]; -/// The label of an inline X/Y/W/H field. +/// The label of an inline X/Y/W/H field, underlined: a click on it opens the Transform panel. fn inline_label(t: &Tokens, lbl: &str) -> egui::RichText { - egui::RichText::new(tl!(lbl)).size(12.0).color(t.text_dim) + egui::RichText::new(tl!(lbl)).size(12.0).color(t.text).underline() } /// The room the Control bar's inline X/Y/W/H fields take: their labels as drawn in the current @@ -217,17 +217,20 @@ fn inline_transform_fields(app: &mut VectorcraftApp, ui: &mut Ui, t: &Tokens, un // The W/H link sits between W and H, but is made after H so Tab goes from W // straight to H and finds the link after it. let mut link_room = None; + let mut labels = Vec::with_capacity(INLINE_FIELDS.len()); for ((k, lbl), (v, offset)) in INLINE_FIELDS.into_iter().zip(values) { if k == "height" { link_room = Some(crate::panels::transform::constrain_link_room(ui)); } - widgets::field_label(ui, inline_label(t, lbl)); + // A click on the label opens the Transform panel, as the Transform link does; a drag scrubs. + let label = widgets::field_panel_label(ui, inline_label(t, lbl)).on_hover_text(tl!("Transform options")); let (id, shown) = (("cb", k), Some(v - offset)); let set = if matches!(k, "width" | "height") { widgets::size_field(ui, id, shown, units, INLINE_FIELD_WIDTH) } else { widgets::num_field(ui, id, shown, units, INLINE_FIELD_WIDTH) }; + labels.push(label); if let Some(nv) = set { let params = match k { "x" => json!({"x": reference.bounds_xy(nv + offset, 0.0).0, "reference": refi, "copy": copy}), @@ -241,6 +244,10 @@ fn inline_transform_fields(app: &mut VectorcraftApp, ui: &mut Ui, t: &Tokens, un let id = ui.scope_id().with("cb-constrain-link"); crate::panels::transform::constrain_link_at(app, ui, ui.interact(room, id, Sense::click())); } + // After the fields, which each take the label before them as their own. + for label in &labels { + crate::panels::transform::popover(app, label); + } } /// The size of the Control bar's Align, Distribute and area type vertical alignment buttons, and diff --git a/crates/ui-egui/src/chrome/tests.rs b/crates/ui-egui/src/chrome/tests.rs index 61c67e6a70..501ce263bb 100644 --- a/crates/ui-egui/src/chrome/tests.rs +++ b/crates/ui-egui/src/chrome/tests.rs @@ -4651,3 +4651,59 @@ fn the_control_bar_shows_the_inline_transform_fields_only_when_they_fit() { assert!(groups_seen.iter().all(|s| *s), "{count} objects: a wide bar shows every group: {groups_seen:?}"); } } + +/// A click on the Control bar's X:, Y:, W: or H: label opens the Transform panel in a popover under +/// it, as the Transform link does, and a second click closes it. The click leaves the selection and +/// its bounds as they were, and no field takes the keyboard. A drag on W: still scrubs the width and +/// opens nothing. +#[test] +fn the_control_bars_x_y_w_and_h_labels_open_the_transform_panel() { + crate::i18n::set_current(crate::i18n::Lang::EN); + let mut app = crate::VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let id = app.run("shape.rectangle", json!({"x": 20, "y": 20, "width": 40, "height": 30})).unwrap()["id"].clone(); + app.run("select.set", json!({ "ids": [id] })).unwrap(); + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + crate::theme::install_fonts(&ctx); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(2000.0, 600.0)); + let frame = |app: &mut crate::VectorcraftApp, events| control_bar_frame_in(app, &ctx, screen, events); + let state = |app: &crate::VectorcraftApp| { + let st = app.session.active().unwrap(); + let b = st.doc.bounds_of(&st.selection.objects, false).unwrap(); + (st.selection.objects.len(), [b.x0, b.y0, b.x1, b.y1]) + }; + // The label's own node: a label whose text is `name` (the field it names is named the same). + let label = |nodes: &[egui::accesskit::Node], name: &str| { + let n = nodes.iter().find(|n| n.role() == egui::accesskit::Role::Label && n.value() == Some(name)); + let b = n.and_then(|n| n.bounds()).unwrap_or_else(|| panic!("no {name} label")); + egui::pos2(((b.x0 + b.x1) / 2.0) as f32, ((b.y0 + b.y1) / 2.0) as f32) + }; + // The Transform panel's Rotate field is not on the bar itself. + let open = |nodes: &[egui::accesskit::Node]| nodes.iter().any(|n| n.label() == Some("Rotate")); + let before = state(&app); + frame(&mut app, vec![]); + for name in ["X:", "Y:", "W:", "H:"] { + let nodes = frame(&mut app, vec![]); + assert!(!open(&nodes), "{name}: the Transform panel is closed at first"); + let at = label(&nodes, name); + frame(&mut app, vec![egui::Event::PointerMoved(at), press_at(at, true)]); + frame(&mut app, vec![press_at(at, false)]); + assert!(open(&frame(&mut app, vec![])), "{name}: a click on the label opens the Transform panel"); + assert_eq!(ctx.memory(|m| m.focused()), None, "{name}: no field took the keyboard"); + assert_eq!(state(&app), before, "{name}: the selection and its bounds stay"); + frame(&mut app, vec![egui::Event::PointerMoved(at), press_at(at, true)]); + frame(&mut app, vec![press_at(at, false)]); + assert!(!open(&frame(&mut app, vec![])), "{name}: a second click closes it"); + } + let at = label(&frame(&mut app, vec![]), "W:"); + frame(&mut app, vec![egui::Event::PointerMoved(at), press_at(at, true)]); + for i in 1..=4 { + frame(&mut app, vec![egui::Event::PointerMoved(at + egui::vec2(5.0 * i as f32, 0.0))]); + } + frame(&mut app, vec![press_at(at + egui::vec2(20.0, 0.0), false)]); + let nodes = frame(&mut app, vec![]); + assert!(!open(&nodes), "a drag on W: opens nothing"); + let (_, [x0, _, x1, _]) = state(&app); + assert!(x1 - x0 > before.1[2] - before.1[0], "a drag on W: scrubs the width: {:?} to {:?}", before.1, [x0, x1]); +} diff --git a/crates/ui-egui/src/panels/artboards.rs b/crates/ui-egui/src/panels/artboards.rs index b7f9e25df5..94560b9f76 100644 --- a/crates/ui-egui/src/panels/artboards.rs +++ b/crates/ui-egui/src/panels/artboards.rs @@ -149,11 +149,14 @@ pub(crate) fn control_bar(app: &mut VectorcraftApp, ui: &mut Ui, options: bool, // The W/H link sits between W and H, but is made after H so Tab goes from W straight to H and // finds the link after it, as in the object Control bar. let mut link_room = None; + let mut labels = Vec::with_capacity(4); for (k, lbl, v) in [("x", "X:", rp.x - origin.x), ("y", "Y:", rp.y - origin.y), ("width", "W:", r.width()), ("height", "H:", r.height())] { if k == "height" { link_room = Some(super::transform::constrain_link_room(ui)); } - widgets::field_label(ui, egui::RichText::new(tl!(lbl)).size(12.0).color(t.text_dim)); + // A click on the label opens the Transform panel, as the Transform link does; a drag scrubs. + let text = egui::RichText::new(tl!(lbl)).size(12.0).color(t.text).underline(); + labels.push(widgets::field_panel_label(ui, text).on_hover_text(tl!("Transform options"))); let set = if matches!(k, "width" | "height") { widgets::size_field(ui, ("cb-ab", k), Some(v), units, 80.0) } else { @@ -173,6 +176,10 @@ pub(crate) fn control_bar(app: &mut VectorcraftApp, ui: &mut Ui, options: bool, let id = ui.scope_id().with("cb-ab-constrain-link"); super::transform::constrain_link_at(app, ui, ui.interact(room, id, egui::Sense::click())); } + // After the fields, which each take the label before them as their own. + for label in &labels { + super::transform::popover(app, label); + } true } diff --git a/crates/ui-egui/src/panels/artboards/tests.rs b/crates/ui-egui/src/panels/artboards/tests.rs index b53faf87c0..b52d1da682 100644 --- a/crates/ui-egui/src/panels/artboards/tests.rs +++ b/crates/ui-egui/src/panels/artboards/tests.rs @@ -957,6 +957,32 @@ fn the_control_bar_resizes_the_active_artboard_about_the_reference_point() { assert_eq!(boards(&app).0, want, "Artboard 2 widens from its left edge"); } +/// With the Artboard tool, a click on the Control bar's X:, Y:, W: or H: label opens the Transform +/// panel's artboard fields in a popover under it, as the Transform link does, and a second click +/// closes it; the artboards stay as they were and no field takes the keyboard. +#[test] +fn the_artboard_control_bars_x_y_w_and_h_labels_open_the_transform_panel() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 100, "units": "Points"})).unwrap(); + app.select_tool("artboard"); + let ctx = bar_context(); + let before = boards(&app); + // The bar draws one W:, and the popover's artboard fields another. + let ws = |texts: &[(String, egui::Rect)]| texts.iter().filter(|(t, _)| t == "W:").count(); + for label in ["X:", "Y:", "W:", "H:"] { + let texts = bar_texts(&mut app, &ctx); + assert_eq!(ws(&texts), 1, "{label}: the bar alone: {texts:?}"); + let at = text_rect(&texts, label).center(); + bar_click(&mut app, &ctx, at); + let texts = bar_texts(&mut app, &ctx); + assert_eq!(ws(&texts), 2, "{label}: the Transform panel opens: {texts:?}"); + assert_eq!(ctx.memory(|m| m.focused()), None, "{label}: no field took the keyboard"); + bar_click(&mut app, &ctx, at); + assert_eq!(ws(&bar_texts(&mut app, &ctx)), 1, "{label}: a second click closes it"); + } + assert_eq!(boards(&app), before, "the artboards stay"); +} + /// The Control bar's Portrait and Landscape buttons swap the active artboard's width and height, /// its top-left corner staying put, in one undo step each. #[test] diff --git a/crates/ui-egui/src/panels/transform.rs b/crates/ui-egui/src/panels/transform.rs index 1bce03c53d..2309351c87 100644 --- a/crates/ui-egui/src/panels/transform.rs +++ b/crates/ui-egui/src/panels/transform.rs @@ -515,7 +515,13 @@ pub(crate) fn polygon_rows(app: &mut VectorcraftApp, ui: &mut Ui, n: &Node, live /// popover under it, as the Stroke link does with the Stroke panel. pub fn link(app: &mut VectorcraftApp, ui: &mut Ui) { let resp = ui.link(link_text(ui)).on_hover_text(tl!("Transform options")); - widgets::popover(&resp, resp.clicked(), |ui| { + popover(app, &resp); +} + +/// The Transform panel in a popover under `resp`, which a click on it toggles: the Control bar's +/// Transform [`link`], and its X:, Y:, W: and H: labels. +pub fn popover(app: &mut VectorcraftApp, resp: &egui::Response) { + widgets::popover(resp, resp.clicked(), |ui| { ui.set_width(300.0); show(app, ui); }); diff --git a/crates/ui-egui/src/scrub.rs b/crates/ui-egui/src/scrub.rs index 5a0a2ff4f9..e5350b0541 100644 --- a/crates/ui-egui/src/scrub.rs +++ b/crates/ui-egui/src/scrub.rs @@ -3,7 +3,8 @@ //! field's value by one unit every [`PX_PER_STEP`] points, ten with Shift and a tenth with //! Ctrl/Cmd, as the arrow keys step a focused field; a click on the label focuses the field. A //! label that is a link (the Control bar's `Stroke:` and `Opacity:`, which open their panels; -//! #4088) scrubs its field the same way, and a click on it still follows the link. The text box +//! #4088) or opens a panel (its `X:`, `Y:`, `W:` and `H:`, which open the Transform panel) scrubs +//! its field the same way, and a click on it still opens the panel. The text box //! itself never scrubs, and a field without a label doesn't. //! //! The panels apply each value the drag passes as they apply a typed one, so the art follows the @@ -117,12 +118,14 @@ struct Label { pass: u64, /// The label is a link, this widget: a click follows it instead of focusing the field. link: Option<Id>, + /// The label is a tab stop of its own (a link; not a [`panel_label`]). + tab_stop: bool, } /// Note the label (text or icon) drawn at `rect`: a numeric field drawn right after it on the /// same line takes it as its label, which scrubs the field. pub(crate) fn note_label(ui: &Ui, rect: Rect) { - note(ui, rect, None); + note(ui, Label { rect, pass: 0, link: None, tab_stop: false }); } /// A link that labels the numeric field drawn after it (it opens a panel when clicked): a drag on @@ -135,13 +138,27 @@ pub(crate) fn link_label(ui: &mut Ui, text: egui::RichText) -> Response { ui.link(text) }) .inner; - note(ui, link.rect, Some(link.id)); + note(ui, Label { rect: link.rect, pass: 0, link: Some(link.id), tab_stop: true }); link } -fn note(ui: &Ui, rect: Rect, link: Option<Id>) { +/// A field's label that opens a panel when clicked (the Control bar's X:, Y:, W: and H:, which open +/// the Transform panel): a drag on it scrubs the field after it, and a click stays the label's, as +/// with [`link_label`]. Unlike a link it is not a tab stop of its own, so Tab still moves from one +/// field to the next. The pointing hand shows over it. +pub(crate) fn panel_label(ui: &mut Ui, text: egui::RichText) -> Response { + let label = ui.add(egui::Label::new(text).selectable(false).sense(Sense::CLICK)); + if label.hovered() { + ui.ctx().set_cursor_icon(CursorIcon::PointingHand); + } + note(ui, Label { rect: label.rect, pass: 0, link: Some(label.id), tab_stop: false }); + label +} + +/// Keep `label` for the field after it, as drawn this pass. +fn note(ui: &Ui, label: Label) { let pass = ui.ctx().cumulative_pass_nr(); - ui.data_mut(|d| d.insert_temp(label_id(), Label { rect, pass, link })); + ui.data_mut(|d| d.insert_temp(label_id(), Label { pass, ..label })); } /// The label noted just before the field at `field`, on its line. @@ -169,9 +186,11 @@ pub(crate) fn field(ui: &Ui, field: Id, rect: Rect, text: &str, value: Option<f6 // On top of the label, which may sense clicks itself (selectable text). A link senses drags // too and keeps its clicks (and its pointing hand while hovered): a widget laid over it would // take them. The zone is not a tab stop of its own (`Sense::click_and_drag` would be): Tab - // moves from a field to the next field, not onto the label before it. + // moves from a field to the next field, not onto the label before it. A link stays the tab stop + // it is, and a [`panel_label`] stays none. let resp = match label.link { - Some(link) => ui.interact(label.rect, link, Sense::drag()), + Some(link) if label.tab_stop => ui.interact(label.rect, link, Sense::drag()), + Some(link) => ui.interact(label.rect, link, Sense::DRAG), None => ui.interact(label.rect, field.with("scrub-label"), Sense::CLICK | Sense::DRAG), }; drag(ui, &resp, field, text, value, decimals, label.link.is_some()).map(|v| v.max(*bounds.start()).min(*bounds.end())) diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index fb291b8525..6d22f0e6a2 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -55,7 +55,7 @@ pub use dropdowns::{ #[cfg(test)] pub(crate) use dropdowns::{menu_floor, menu_room_either}; pub use labels::{dim_label, dim_name, divider, field_label, label_row, link_label, section_header, section_toggle, section_toggle_name, subheader}; -pub(crate) use labels::{dim_label_width, label_field, take_previous_label, text_width}; +pub(crate) use labels::{dim_label_width, field_panel_label, label_field, take_previous_label, text_width}; pub(crate) use numeric::{ANY, round_to, set_bare_numbers_are_points, typed_unit}; pub use numeric::{ SpinPick, mixed_field, mixed_field_named, num_field, num_field_live, num_field_named, num_field_refusing, num_field_within, diff --git a/crates/ui-egui/src/widgets/labels.rs b/crates/ui-egui/src/widgets/labels.rs index 221d418a46..419cd46cf4 100644 --- a/crates/ui-egui/src/widgets/labels.rs +++ b/crates/ui-egui/src/widgets/labels.rs @@ -144,6 +144,14 @@ pub fn field_label(ui: &mut Ui, text: impl Into<egui::WidgetText>) -> Response { resp } +/// A field's label (`text` as given) that a click follows to a panel ([`scrub::panel_label`]): +/// before a numeric field it scrubs the field and names it. +pub fn field_panel_label(ui: &mut Ui, text: egui::RichText) -> Response { + let resp = scrub::panel_label(ui, text); + remember_next_label(ui, resp.id); + resp +} + /// [`dim_label`] for a name that is user or file data (a swatch, style, artboard or font name): /// shown as it is, never translated. pub fn dim_name(ui: &mut Ui, text: &str) -> Response { diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 04b25c70eb..4e7a6bd212 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1141,9 +1141,10 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - A plain step of a number field (Up/Down or a wheel notch) goes to the next whole unit in its direction and a Ctrl/Cmd step goes to the next tenth, so 5.1 mm steps up to 6 mm and down to 5 mm (#2881). A Shift step adds or takes ten and keeps the fraction. - In the number, text and color fields of the panels and the Control bar, Shift+Enter (Shift+Return) applies the value and keeps the field active with its value selected; a text box of several lines takes it as a line break. In a dialog, Shift+Enter applies the value and confirms the dialog, as Enter does. - The Pattern Options panel's Name field and the name fields that a double-click opens in the Layers, Artboards and Asset Export panels take Shift+Enter (Shift+Return) the same way: it applies the name and keeps the field active with the name selected. - - Scrubby labels (#400, beyond Illustrator, as in Photoshop): dragging a numeric field's label left or right (the ↔ cursor shows over it) steps the value one unit every 2 points (Shift: ten, Ctrl/Cmd: a tenth; counts stay whole), in the field's unit and within its limits, applied live as the art follows; the whole drag is one undo step and Escape puts the value back. A click on the label focuses the field; the text box itself never scrubs, and a field with no label doesn't. Text labels before a field (Transform, Properties, Control bar, Stroke, Transparency, form rows in dialogs) and the Character and Paragraph panels' icons act as labels, and so do the links that label a field (the Control bar's Stroke: and Opacity:, the Properties panel's Stroke), which a click still follows to their panel (#4088). Preferences › General › Scrub Numeric Fields by Dragging (on by default) turns it off. + - Scrubby labels (#400, beyond Illustrator, as in Photoshop): dragging a numeric field's label left or right (the ↔ cursor shows over it) steps the value one unit every 2 points (Shift: ten, Ctrl/Cmd: a tenth; counts stay whole), in the field's unit and within its limits, applied live as the art follows; the whole drag is one undo step and Escape puts the value back. A click on the label focuses the field; the text box itself never scrubs, and a field with no label doesn't. Text labels before a field (Transform, Properties, Control bar, Stroke, Transparency, form rows in dialogs) and the Character and Paragraph panels' icons act as labels, and so do the links that label a field (the Control bar's Stroke: and Opacity:, the Properties panel's Stroke), which a click still follows to their panel (#4088), and the Control bar's X:, Y:, W: and H:, which a click follows to the Transform panel. Preferences › General › Scrub Numeric Fields by Dragging (on by default) turns it off. - In the Transform panel, the Properties panel's Transform section and the Control bar, Alt+Enter (Option+Return) applies a value to a copy of the selection and selects the copy, in one undo step. With anchor points selected with Direct Selection it applies the value to them, as Enter does. Ctrl/Cmd+Enter in W or H applies the value and scales the selection proportionally with the link off. With the Artboard tool, it scales the active artboard proportionally. A percentage typed alone in W or H (`50%`) is that share of the size the field shows, and the link and Ctrl/Cmd+Enter keep the proportions as with a length (#2401). - The Control bar's underlined Transform link opens the Transform panel in a popover under it (reference point, X/Y/W/H, Rotate and Shear with their icons and angle presets, flips, shape properties, Scale Corners and Scale Strokes & Effects), as its Stroke link does the Stroke panel; X/Y/W/H also show inline while the bar has room. The reference point locator is nine squares, the outer eight joined around the box. As VectorCraft's own keyboard rule, the locator is one tab stop in the Control bar popover, the Transform panel, the Properties panel and the dialogs, the Arrange Tools dialogs included. While it has the focus it shows an outline, and ←, →, ↑ and ↓ move the reference point one square, stopping at the edges (`the_reference_point_grid_is_one_tab_stop`, `arrow_keys_move_the_reference_point`, `the_reference_point_locator_is_one_tab_stop_and_arrows_move_it`). + - A click on the Control bar's underlined X:, Y:, W: or H: label opens the Transform panel in a popover under that label, as the Transform link does, and a second click, Escape or a click elsewhere closes it; with the Artboard tool the popover shows the artboard's fields. The help page (<https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=374>) describes these four labels as another way to bring up the Transform panel. VectorCraft's own rules: the click does not give the field the keyboard, a drag on the label still scrubs the field, and the labels are not tab stops, so Tab still moves from one field to the next and the Transform link stays the keyboard's way to the panel (`the_control_bars_x_y_w_and_h_labels_open_the_transform_panel`, `the_artboard_control_bars_x_y_w_and_h_labels_open_the_transform_panel`). - The Control bar's inline X and Y show the point of the selection's box that the Transform panel's locator chose, counted from the ruler origin, and a new X or Y moves that point there; a new W or H resizes the selection about it. The help page (<https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=333>) describes typing X and Y in the Transform panel or the Control panel after choosing the point on the locator. Use Registration Point for Symbol applies to the inline fields as it does to the panel's. Choosing another point changes only what the fields show; each field edit is one undo step (`panels::transform::tests::the_control_bar_fields_use_the_shared_reference_point`). - In isolation mode the Control bar has an Exit Isolation Mode button (`object.exitIsolation`), except while a pattern is edited. Outside isolation mode, with one group, compound path, path, image, mesh or placed file selected, it has an Isolate Selected Object button (`object.isolate`), which also isolates a path inside a group that Direct Selection selected. - The canvas context menu has Isolate Selected Path (`object.isolate`) when the selection is one path, a path selected inside a group or a compound path included, as the [help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=324) lists it beside Isolate Selected Group. As VectorCraft's own rule, neither item shows for two or more objects, or for an object `object.isolate` refuses: a hidden or locked object, one in a hidden or locked group or layer, a guide while Lock Guides is on, and, while a symbol is edited, an object outside the symbol's art (`single_path_context_item_enters_isolation`, `isolation_context_item_follows_selected_kind`, `isolation_context_item_skips_objects_that_cannot_be_isolated`). From 30ec1179606e54a679485d043e1e958f1bc5d7db Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 17 Nov 2026 14:40:08 -0800 Subject: [PATCH 142/176] Color Picker: the screen sampler works in a picker opened over a dialog A Color Picker opened from a dialog's color (an effect's color, a command form's color or a Document Setup grid color) now carries the number that ui.sampleScreenColor uses to find the open picker. Its eyedropper sends the sampled color to that picker instead of failing with "the Color Picker is not open". --- crates/ui-egui/src/dialogs/color_picker.rs | 1 + crates/ui-egui/src/dialogs/document_setup.rs | 21 ++++++++++++++++++++ 2 files changed, 22 insertions(+) diff --git a/crates/ui-egui/src/dialogs/color_picker.rs b/crates/ui-egui/src/dialogs/color_picker.rs index ca0e6051f8..2c7159c2d6 100644 --- a/crates/ui-egui/src/dialogs/color_picker.rs +++ b/crates/ui-egui/src/dialogs/color_picker.rs @@ -282,6 +282,7 @@ pub(super) fn over_effect(parent: &Dialog, field: &str, colour: Color) -> Dialog ); d.fields.insert(super::PARENT.into(), serde_json::to_value(parent).unwrap_or_default()); store(&mut d, &Picked::of(colour)); + d.fields.insert(crate::screen_color::PICKER_ID.into(), json!(crate::screen_color::picker_id())); d } diff --git a/crates/ui-egui/src/dialogs/document_setup.rs b/crates/ui-egui/src/dialogs/document_setup.rs index 8dee8d9962..187e36e6b0 100644 --- a/crates/ui-egui/src/dialogs/document_setup.rs +++ b/crates/ui-egui/src/dialogs/document_setup.rs @@ -799,6 +799,27 @@ mod tests { assert_eq!((d.kind.as_str(), dialog_grid(d)), (super::KIND, ["#ffffff", "#00ff00"].map(hex).to_vec())); } + /// The screen color sampler works in the Color Picker of a grid color: the color sampled goes + /// to that picker, and its OK sets the grid color. + #[test] + fn the_grid_color_picker_takes_a_screen_sampled_color() { + let (mut app, ctx) = transparency_tab(); + let (tx, rx) = std::sync::mpsc::channel::<crate::screen_color::Answer>(); + let mut rx = Some(rx); + app.services.screen_color = Some(Box::new(move || rx.take().ok_or_else(|| "shown twice".to_string()))); + click_grid_box(&mut app, &ctx, 0); + assert_picker_over_setup(&app, LIGHT[0], "before sampling"); + app.run("ui.sampleScreenColor", json!({"picker": true})).unwrap(); + tx.send(Ok(Some([0.0, 0.5, 1.0]))).unwrap(); + crate::screen_color::poll(&mut app, &ctx); + let sampled = app.ui.dialog.as_ref().unwrap().fields.get("color").and_then(vectorcraft_engine::cmd::color_value).unwrap(); + assert_ne!(sampled.to_hex(), LIGHT[0]); + crate::dialogs::confirm(&mut app).unwrap(); + let d = app.ui.dialog.as_ref().unwrap(); + let grid: Vec<String> = dialog_grid(d).iter().map(Color::to_hex).collect(); + assert_eq!((d.kind.as_str(), grid), (super::KIND, vec![sampled.to_hex(), LIGHT[1].to_string()])); + } + /// Clicks the hex field that shows `digits` and types `typed` over its text, leaving the edit /// pending; returns the field's id. fn type_into_hex_field(app: &mut VectorcraftApp, ctx: &egui::Context, digits: &str, typed: &str) -> egui::Id { From ef366997ec50c2780256e234ade9a5bc15386768 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 17 Nov 2026 14:51:14 -0800 Subject: [PATCH 143/176] .ai save: keep at most 4,096 parsed style texts per save The writer kept every style text it checked, with its parse, until the save ended, including texts the reader does not accept. A gradient style placed on each object's outline is often a different text per object, so memory grew with the number of objects checked. The first 4,096 texts, up to 8 MiB of text, are kept parsed. Past that, only the last text checked is kept, so the brush check that follows an object's check reuses its parse, and other texts are parsed again when checked. The written file is unchanged. --- crates/eps/src/ai_editing/writer/styles.rs | 91 +++++++++++++++++++--- 1 file changed, 80 insertions(+), 11 deletions(-) diff --git a/crates/eps/src/ai_editing/writer/styles.rs b/crates/eps/src/ai_editing/writer/styles.rs index 0af8e313fa..df153c236e 100644 --- a/crates/eps/src/ai_editing/writer/styles.rs +++ b/crates/eps/src/ai_editing/writer/styles.rs @@ -4,7 +4,8 @@ //! [`crate::ai_editing`] for the form). Each style is read back before it is written //! ([`crate::import::read_parsed_style`]: the `.ai` reader's style parser and its reading of a graphic //! style, with the object's own gradient): one that reads back differently is not written, and the -//! object is written as its drawn look alone. Each style text is parsed once per save ([`Parsed`]). +//! object is written as its drawn look alone. Style texts are kept parsed for the save, up to a +//! limit ([`Parsed`]). use std::collections::{HashMap, HashSet}; use std::fmt::Write; @@ -172,15 +173,27 @@ pub(in crate::ai_editing) struct Styles { next_anon: u64, /// How many objects were written with the graphic style they are linked to. pub(super) links_written: usize, - /// Every style text checked so far, as the reader parses it. + /// The style texts checked so far, as the reader parses them. pub(super) parsed: Parsed, } -/// Style texts as the reader parses them ([`crate::import::parse_art_style`]), each parsed once -/// however many styles and objects are checked with it; a text the reader doesn't parse is kept -/// as `None`. +/// The most style texts [`Parsed`] keeps parsed in one save. +const MAX_PARSED: usize = 4096; +/// The most bytes of style text [`Parsed`] keeps parsed in one save. +const MAX_PARSED_BYTES: usize = 8 << 20; + +/// Style texts as the reader parses them ([`crate::import::parse_art_style`]). The first +/// [`MAX_PARSED`] texts, up to [`MAX_PARSED_BYTES`] bytes in all, are each parsed once however many +/// styles and objects are checked with them; a text the reader doesn't parse is kept as `None`. +/// Past that, only the last text checked is kept, and each other text is parsed again when checked. #[derive(Default)] -pub(super) struct Parsed(HashMap<String, Option<crate::import::ParsedStyle>>); +pub(super) struct Parsed { + kept: HashMap<String, Option<crate::import::ParsedStyle>>, + /// The bytes of the texts in `kept`. + bytes: usize, + /// The last text checked that `kept` doesn't hold, with its parse. + last: Option<(String, Option<crate::import::ParsedStyle>)>, +} #[cfg(test)] thread_local! { @@ -192,14 +205,21 @@ impl Parsed { /// Style text `text` as the reader parses it (`None` when it doesn't). pub(super) fn get(&mut self, text: &str) -> Option<&crate::import::ParsedStyle> { #[cfg(test)] - if REPARSE.get() { - self.0.remove(text); + let reparse = REPARSE.get(); + #[cfg(not(test))] + let reparse = false; + if !reparse && self.kept.contains_key(text) { + return self.kept.get(text).and_then(Option::as_ref); } - if !self.0.contains_key(text) { + if reparse || self.last.as_ref().is_none_or(|(last, _)| last != text) { let parsed = crate::import::parse_art_style(known_style("x", text).as_bytes(), "x"); - self.0.insert(text.to_owned(), parsed); + if !reparse && self.kept.len() < MAX_PARSED && self.bytes.saturating_add(text.len()) <= MAX_PARSED_BYTES { + self.bytes += text.len(); + return self.kept.entry(text.to_owned()).or_insert(parsed).as_ref(); + } + self.last = Some((text.to_owned(), parsed)); } - self.0.get(text).and_then(Option::as_ref) + self.last.as_ref().and_then(|(_, parsed)| parsed.as_ref()) } } @@ -1071,3 +1091,52 @@ pub(super) fn near(a: &Value, b: &Value) -> bool { _ => a == b, } } + +#[cfg(test)] +mod tests { + use super::*; + + /// A style text after its name: a stroke `width` pt wide. + fn stroke_style(width: usize) -> String { + format!( + "/ActiveStyle :\n/CompoundFilter :\n(Chain Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ + /CompoundFilter :\n(Stack Style Filter) 0 0 /Filter ,\n1 /Visible ,\n/BasicFilter :\n(Stroke Style Filter) 0 0 /Filter ,\n1 /Visible ,\n\ + 2 /FillOrStroke ,\n/Dictionary : /NotRecorded ,\n/StrokeStyle : 0 R\n0 0 0 0 0 0 1 XA\n0 J 0 j {width} w 10 M []0 d\n0 XR\n1 0 Xd\n/Def ;\n (StrokeStyle) ,\n\ + ; /Dict ;\n /Part ,\n/BasicFilter :\n(Conduit Filter) 0 0 /Filter ,\n1 /Visible ,\n;\n /Part ,\n;\n" + ) + } + + /// `text` parsed on its own, as the reader parses it. + fn fresh(text: &str) -> String { + format!("{:?}", crate::import::parse_art_style(known_style("x", text).as_bytes(), "x")) + } + + /// A save that checks more distinct style texts than [`Parsed`] keeps, stroke styles and texts + /// that aren't styles, keeps at most [`MAX_PARSED`] texts and [`MAX_PARSED_BYTES`] bytes, and each + /// check still gives the text's own parse, kept or not, the first time and again. + #[test] + fn parsed_styles_kept_in_a_save_stay_within_the_limits() { + let mut parsed = Parsed::default(); + for i in 0..MAX_PARSED + 100 { + let text = if i % 2 == 0 { stroke_style(i + 1) } else { format!("not a style {i}") }; + let got = format!("{:?}", parsed.get(&text).cloned()); + assert_eq!(got, fresh(&text), "{i}"); + assert_eq!(format!("{:?}", parsed.get(&text).cloned()), got, "{i}"); + assert!(parsed.kept.len() <= MAX_PARSED && parsed.bytes <= MAX_PARSED_BYTES, "{i}: {} texts", parsed.kept.len()); + } + assert_eq!(parsed.kept.len(), MAX_PARSED); + for i in [0, 1, MAX_PARSED - 1, MAX_PARSED, MAX_PARSED + 98, MAX_PARSED + 99] { + let text = if i % 2 == 0 { stroke_style(i + 1) } else { format!("not a style {i}") }; + assert_eq!(format!("{:?}", parsed.get(&text).cloned()), fresh(&text), "{i}"); + } + + let mut parsed = Parsed::default(); + let long = |i: usize| format!("{i} {}", "x".repeat(1 << 20)); + for i in 0..MAX_PARSED_BYTES / (1 << 20) + 4 { + assert_eq!(format!("{:?}", parsed.get(&long(i)).cloned()), fresh(&long(i)), "{i}"); + assert!(parsed.bytes <= MAX_PARSED_BYTES, "{i}: {} bytes", parsed.bytes); + assert_eq!(parsed.bytes, parsed.kept.keys().map(String::len).sum::<usize>()); + } + assert!(parsed.kept.len() < MAX_PARSED_BYTES / (1 << 20)); + } +} From a5b3a216df3d9d269739f47937083232f2784ed4 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 17 Nov 2026 14:52:13 -0800 Subject: [PATCH 144/176] Pen: the Info panel shows W, H, D and the angle while a drag pulls out a handle While a Pen drag past the drag threshold shapes a handle, the Info panel shows the change in x and y, the distance and the angle from the anchor to the handle's end: the outgoing handle of a new, added or last anchor, and the incoming handle of the first anchor when the drag closes the path. Shift gives the constrained handle and Space moves the anchor with it. The readout clears on release, a dropped press and a tool change. --- crates/tools/src/lib.rs | 4 +- crates/tools/src/pen.rs | 18 +++++ crates/tools/src/pen/tests.rs | 125 ++++++++++++++++++++++++++++++++++ docs/target-app-parity.md | 1 + docs/ui-parity.md | 2 +- 5 files changed, 147 insertions(+), 3 deletions(-) diff --git a/crates/tools/src/lib.rs b/crates/tools/src/lib.rs index 7526717665..0a0ab46f94 100644 --- a/crates/tools/src/lib.rs +++ b/crates/tools/src/lib.rs @@ -272,8 +272,8 @@ pub trait Tool: Send { false } /// What the Info panel shows for the tool as it is now: the drag in progress (a move of the - /// selection, a gradient vector, a Scale, Rotate, Reflect or Shear tool drag), or the - /// Paintbrush's brush. None for a tool with nothing of its own to show. + /// selection, a gradient vector, a handle the Pen pulls out, a Scale, Rotate, Reflect or Shear + /// tool drag), or the Paintbrush's brush. None for a tool with nothing of its own to show. fn readout(&self, _cx: &ToolContext) -> Option<Readout> { None } diff --git a/crates/tools/src/pen.rs b/crates/tools/src/pen.rs index 24a21d08ca..d2f02c20f1 100644 --- a/crates/tools/src/pen.rs +++ b/crates/tools/src/pen.rs @@ -29,6 +29,7 @@ //! the other art and of the path being drawn, into line with them, onto the construction guides //! through the last anchor; with Shift held it slides along its 45° step into line. Hovering shows //! where the next one would go. +//! While a drag pulls a handle out, the Info panel shows it from the anchor to the handle's end. use serde_json::json; use vectorcraft_doc::{NodeId, NodeKind}; @@ -62,6 +63,10 @@ pub struct PenTool { /// The pointer has moved past the drag threshold since the press: a press released inside it /// is a click, so the anchor stays a corner without handles. dragged: bool, + /// The handle a drag past the threshold is pulling out, from the anchor it shapes to the + /// handle's end as last previewed (the outgoing handle, or the incoming one of the first + /// anchor closing the path): what the Info panel shows ([`Tool::readout`]). + vector: Option<Vec2>, /// The last anchor of the path being drawn, while a click retracts its outgoing handle or a /// drag pulls a new one out: (path, subpath, anchor, its position). handle: Option<(NodeId, usize, usize, Point)>, @@ -256,6 +261,12 @@ impl Tool for PenTool { fn ends_on_escape(&self, cx: &ToolContext) -> bool { self.active(cx).is_some() } + /// The handle a drag is pulling out of the anchor it shapes: the outgoing handle of a new or + /// added anchor or of the last anchor, or the incoming handle of the first anchor closing the + /// path. None for a click, a hover or an Alt gesture. + fn readout(&self, _cx: &ToolContext) -> Option<crate::Readout> { + self.vector.filter(|_| self.dragged && (self.drag.is_some() || self.handle.is_some())).map(crate::Readout::drag) + } fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec<Action> { let tol = cx.tol(5.0).max(cx.point_tol()); // The path a press began is the selected one by the next event. @@ -292,6 +303,7 @@ impl Tool for PenTool { self.last = ev.pos; self.pressed = ev.pos; self.dragged = false; + self.vector = None; if let Some((id, si, first, last, _)) = active { let end = last_anchor(cx, id, Some(si)); let closing_end = end.filter(|(_, ai)| *ai > 0).map(|_| first); @@ -391,6 +403,7 @@ impl Tool for PenTool { if ev.mods.shift { h = a + vectorcraft_geom::constrain_angle_from(ev.pos - a, 45.0, cx.constrain_angle); } + self.vector = Some(h - a); return vec![set_out_handle(id, si, ai, h)]; } let Some(Place { at: mut a, path, subpath, closing, mut moved }) = self.drag else { return vec![] }; @@ -412,6 +425,8 @@ impl Tool for PenTool { if ev.mods.shift { out_h = a + vectorcraft_geom::constrain_angle_from(ev.pos - a, 45.0, cx.constrain_angle); } + // A closing drag shapes the first anchor's incoming handle, which mirrors the pointer. + self.vector = Some(if closing { a - out_h } else { out_h - a }); let alt = ev.mods.alt; let Some(id) = path else { // First anchor of a new path: re-issue create with handles. @@ -436,6 +451,7 @@ impl Tool for PenTool { } PointerKind::Up => { self.snap.clear(); + self.vector = None; if let Some(mut t) = self.convert.take() { return t.pointer(cx, ev); } @@ -465,6 +481,7 @@ impl Tool for PenTool { self.first = None; self.handle = None; self.convert = None; + self.vector = None; self.snap.clear(); vec![] } @@ -476,6 +493,7 @@ impl Tool for PenTool { let placing = self.drag.take().is_some(); self.first = None; let handling = self.handle.take().is_some(); + self.vector = None; // Finish the preview as it stands; clearing state alone leaves its transaction open. let mut acts = self.convert.take().map(|mut t| t.deactivate(cx)).unwrap_or_default(); if placing || handling { diff --git a/crates/tools/src/pen/tests.rs b/crates/tools/src/pen/tests.rs index badb8193a7..580decf3e7 100644 --- a/crates/tools/src/pen/tests.rs +++ b/crates/tools/src/pen/tests.rs @@ -970,3 +970,128 @@ fn continuing_a_compound_member_at_its_first_anchor_reverses_that_path_by_id() { ); assert_eq!((pen.path, pen.subpath), (Some(a), Some(0))); } + +/// A context with snapping off, so each point goes where the pointer is. +fn plain<'a>(d: &'a vectorcraft_doc::Document, s: &'a Selection, p: &'a crate::PaintDefaults) -> ToolContext<'a> { + ToolContext { zoom: 1.0, smart_guides: false, snap_to_point: false, snap_to_pixel: false, snap_to_grid: false, ..cx(d, s, p) } +} + +fn drag_readout(dx: f64, dy: f64) -> Option<crate::Readout> { + Some(crate::Readout::Drag { dx, dy }) +} + +/// The Info panel shows the handle a drag pulls out of a new anchor, from the anchor to the +/// handle's end, once the drag passes the threshold and until the button comes up. +#[test] +fn info_readout_tracks_the_handle_of_a_new_anchor() { + let (d, s, p) = (vectorcraft_doc::Document::new(500.0, 500.0), Selection::default(), paint()); + let cx = plain(&d, &s, &p); + let mut t = PenTool::default(); + assert_eq!(t.readout(&cx), None, "hovering"); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 100.0, 100.0)); + assert_eq!(t.readout(&cx), None, "pressed"); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 101.0, 101.0)); + assert_eq!(t.readout(&cx), None, "inside the drag threshold"); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 130.0, 60.0)); + let r = t.readout(&cx); + assert_eq!(r, drag_readout(30.0, -40.0)); + let (dist, angle) = r.and_then(|r| r.distance_angle()).unwrap_or_default(); + assert!((dist - 50.0).abs() < 1e-9 && (angle - 53.130_102_354_155_98).abs() < 1e-9, "{dist} {angle}"); + t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 130.0, 60.0)); + assert_eq!(t.readout(&cx), None, "released"); + // A click shows nothing. + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 200.0, 200.0)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 201.0, 200.0)); + assert_eq!(t.readout(&cx), None); + t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 201.0, 200.0)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Move, 250.0, 250.0)); + assert_eq!(t.readout(&cx), None, "hovering after a click"); +} + +/// An anchor added to the path being drawn and the first anchor closing it: the handle the drag +/// shapes is measured from the anchor it belongs to. +#[test] +fn info_readout_tracks_added_and_closing_anchors() { + let pts = [Point::new(100.0, 300.0), Point::new(200.0, 300.0), Point::new(200.0, 400.0)]; + let (d, _, s) = drawing(vectorcraft_geom::SubPath::polyline(&pts, false)); + let p = paint(); + let cx = plain(&d, &s, &p); + let mut t = PenTool { drawing: true, ..PenTool::default() }; + let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 300.0, 400.0)); + assert!(matches!(&a[..], [Action::Begin(_), Action::Preview(c, _)] if c == "path.appendAnchor"), "{a:?}"); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 330.0, 440.0)); + assert_eq!(t.readout(&cx), drag_readout(30.0, 40.0)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 330.0, 440.0)); + assert_eq!(t.readout(&cx), None); + // A press on the first anchor, a pixel off it, closes: the readout is that anchor's incoming + // handle, which mirrors the pointer. + let a = t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 101.0, 301.0)); + assert!(matches!(&a[..], [Action::Begin(c), _] if c == "Close Path"), "{a:?}"); + let acts = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 130.0, 260.0)); + let [Action::Preview(c, v)] = acts.as_slice() else { panic!("not a close preview: {acts:?}") }; + assert_eq!((c.as_str(), &v["in"]), ("path.close", &json!([70.0, 340.0]))); + assert_eq!(t.readout(&cx), drag_readout(-30.0, 40.0)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 130.0, 260.0)); + assert_eq!(t.readout(&cx), None); +} + +/// A drag from the last anchor pulls its outgoing handle out on its own; with Shift the readout +/// gives the constrained handle the preview shows. +#[test] +fn info_readout_tracks_the_last_anchor_handle() { + let (d, id, s) = drawing(vectorcraft_geom::SubPath::polyline(&[Point::new(10.0, 300.0), Point::new(60.0, 300.0)], false)); + let p = paint(); + let cx = plain(&d, &s, &p); + let mut t = PenTool { drawing: true, ..PenTool::default() }; + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 60.0, 300.0)); + assert_eq!(t.readout(&cx), None, "a click retracts the handle"); + assert_eq!(t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 70.0, 280.0)), vec![set_out(id, 1, 70.0, 280.0)]); + assert_eq!(t.readout(&cx), drag_readout(10.0, -20.0)); + let shift = Mods { shift: true, ..Mods::default() }; + // 26.6° from the anchor: Shift turns it to the 45° step nearest. + let acts = t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 80.0, 290.0).with_mods(shift)); + let [Action::Preview(_, v)] = acts.as_slice() else { panic!("not a handle preview: {acts:?}") }; + let (hx, hy) = (v["x"].as_f64().unwrap_or(f64::NAN), v["y"].as_f64().unwrap_or(f64::NAN)); + assert!(((hx - 60.0) + (hy - 300.0)).abs() < 1e-9, "constrained to 45°: {v}"); + assert_eq!(t.readout(&cx), drag_readout(hx - 60.0, hy - 300.0)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Up, 80.0, 290.0)); + assert_eq!(t.readout(&cx), None); +} + +/// Space moves the anchor and its handles together, so the handle keeps its length; Alt leaves +/// the incoming handle behind and the readout follows the outgoing one. +#[test] +fn info_readout_follows_space_and_alt() { + let (d, s, p) = (vectorcraft_doc::Document::new(500.0, 500.0), Selection::default(), paint()); + let cx = plain(&d, &s, &p); + let mut t = PenTool::default(); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 400.0, 420.0)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 450.0, 420.0)); + assert_eq!(t.readout(&cx), drag_readout(50.0, 0.0)); + let space = Mods { space: true, ..Mods::default() }; + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 450.0, 380.0).with_mods(space)); + assert_eq!(t.readout(&cx), drag_readout(50.0, 0.0), "the anchor moved with the handle"); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 460.0, 400.0)); + assert_eq!(t.readout(&cx), drag_readout(60.0, 20.0), "measured from the moved anchor"); + let alt = Mods { alt: true, ..Mods::default() }; + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 400.0, 450.0).with_mods(alt)); + assert_eq!(t.readout(&cx), drag_readout(0.0, 70.0)); +} + +/// A dropped press and switching tools clear the readout. +#[test] +fn info_readout_clears_on_a_dropped_press_and_deactivate() { + let (d, s, p) = (vectorcraft_doc::Document::new(500.0, 500.0), Selection::default(), paint()); + let cx = plain(&d, &s, &p); + let mut t = PenTool::default(); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 100.0, 100.0)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 120.0, 100.0)); + assert_eq!(t.readout(&cx), drag_readout(20.0, 0.0)); + t.drop_press(&cx); + assert_eq!(t.readout(&cx), None, "dropped"); + t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 100.0, 100.0)); + t.pointer(&cx, &PointerEvent::new(PointerKind::Drag, 100.0, 130.0)); + assert_eq!(t.readout(&cx), drag_readout(0.0, 30.0)); + t.deactivate(&cx); + assert_eq!(t.readout(&cx), None, "deactivated"); +} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index ef83de54ad..ddee8084c8 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1120,6 +1120,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Pixel Snapping Options:** Control bar › Snapping › Pixel Snapping Options… sets whether View › Snap to Pixel snaps drawing, moving and scaling, each on by default (`view.snapToPixel.options`, the `pixelSnap` preference group; [the help page](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/draw-pixel-perfect-art.html)). Tests: `pixel_snapping_options_read_set_and_reset`, `pixel_snapping_options_choose_the_edits_snap_to_pixel_rounds`, `handle_drag_follows_the_while_scaling_option`, `move_follows_the_while_moving_option`, `an_anchor_drag_follows_the_while_moving_option`, `new_ruler_guide_follows_the_while_moving_option` and `the_control_bar_snapping_menu_opens_pixel_snapping_options`. Scores and estimates unchanged. - **Measure tools and Snap to Glyph:** with Snap to Glyph, Smart Guides and Alignment Guides on, and Snap to Grid and Snap to Pixel off, both ends of a Measure or Measure & Inspect drag land within the snapping tolerance on the guides of live type that the Character panel's options allow, except Anchor Point, and a Shift-drag's end slides along its 45° step to them. The guide shows during the drag. This is VectorCraft's own rule (`Targets::for_measure`, `xform::measure::tests::its_ends_land_on_glyph_guides_with_snap_to_glyph`); scores and estimates unchanged. - **Drawing readout without the rubber band:** with Enable Rubber Band for the Pen or Curvature tool off and Measurement Labels on, the Pen, the Smart Pen and the Curvature tool hide the preview segment but still show the D / Angle / dX / dY readout at the snapped pointer before the next click, and the Curvature tool also shows it when going on from the current end of a selected path. Measurement Labels show distance and placement while drawing ([the help page](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/smart-guides-options.html)), and the rubber band preference turns off the path preview ([the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/preview-paths-drawn.html)). Showing the readout with the rubber band off is VectorCraft's own rule (`pen::tests::measurement_label_shows_with_the_rubber_band_off`, and `the_measurement_label_shows_with_the_rubber_band_off` in `draw2::curvature::tests` and `addons::smart_pen::tests`); scores and estimates unchanged. + - **Pen handle drags in the Info panel:** while a Pen drag pulls a handle out of an anchor, the Info panel shows the change in x and y (W, H), the distance (D) and the angle, as the Info panel overview in the [archived user guide](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=76) describes for the Pen. The values run from the anchor being shaped to the end of the handle the drag shapes: the outgoing handle of a new or added anchor or of the last anchor, and the incoming handle of the first anchor when the drag closes the path. Shift gives the constrained handle, Space moves the anchor with its handle, and the readout starts past the 3-pixel drag threshold and ends when the button comes up, the press is dropped or the tool changes. These details are VectorCraft's own rules. Tests: the `info_readout_*` tests in `pen::tests`; scores and estimates unchanged. - The desktop app keeps the Color panel's Show Options or Hide Options between sessions, and `ui.colorPanel` sets its mode and options as its panel menu does. - Preferences that act (#394, in part): Show Tool Tips, Double Click To Isolate, Zoom with Mouse Wheel (the wheel zooms about the pointer, Shift-wheel scrolls up and down, Cmd/Ctrl-wheel sideways; Alt/Option-wheel and a trackpad pinch zoom about the pointer either way), Use Precise Cursors; Selection & Anchor Display › Tolerance (objects, anchors and handles), Object Selection by Path Only, Command Click to Select Objects Behind (cycling down the stack), Zoom to Selection, anchor Size, Highlight anchors on mouse over; Type › Number of Recent Fonts (up to 15); Guides & Grid › guide and grid Color and Style (lines or dots) and Grids In Back. Then Snap to Point (its distance, for moves, drawn points and reference points), Move Locked and Hidden Artwork with Artboard, Enable Rubber Band for the Pen and Curvature tools, Handles style, Show handles when multiple anchors are selected, Hide Corner Widget for angles greater than; General › Transform Pattern Tiles (the transforms' and dialogs' Transform Patterns, Align and Distribute, art moved or duplicated with an artboard, and objects moved whole with direct-selected anchors) and Select Same Tint %; Type › Size/Leading, Tracking and Baseline Shift increments (`type.step`, Cmd+Shift+. and Cmd+Shift+, for the size, the Type tool's Alt+arrows), Enable Missing Glyph Protection and Fill New Type Objects With Placeholder Text. Then Smart Guides › Color, Alignment Guides, Anchor/Path Labels, Measurement Labels, Transform Tools, Object Highlighting (with Smart Guides on) and Snapping Tolerance (4 px by default, for every smart guide snap), then Construction Guides and their Angles (#506: a drawn point near a line at one of those angles through the point it leaves from lands on it). Then Type › Type Object Selection by Path Only (type is picked on the baseline of any of its lines, area type's frame or the path of type on a path, no longer anywhere in its bounds; the Type tools and the Eyedropper still take a click among the characters). Then General › Anti-aliased Artwork (off, the canvas draws the art with hard edges). Then Guides & Grid › Show Pixel Grid (Above 600% Zoom), a line at every document pixel over the art in Pixel Preview, turning with a rotated view as the document grid now does too. Then General › Show The Home Screen When No Documents Are Open (off, closing the last document leaves an empty window; the Home button still opens the screen). Then Units › Numbers Without Units Are Points (on by default: a number typed with no unit into a field in picas is read in points, a typed unit still wins; dimmed unless a unit is Picas). Then User Interface › Auto-Collapse Iconic Panels (off by default: on, a click away from a panel popped out of the icon column puts it away). Then Performance › Animated Zoom (on, with GPU Performance, which it needs and which dims it when off: the Zoom tool dragged sideways zooms about the press, right in and left out, and held still zooms on, Alt out; off, a drag zooms to the area dragged across, now drawn as a marquee), User Interface › Large Tabs (taller document tabs) and Scale Cursor Proportional to UI (off, the tool cursors keep their size whatever the UI Scaling), and File Handling › Display Bitmaps as Anti-aliased Images in Pixel Preview (off by default: Pixel Preview draws images with each pixel taking its nearest image pixel). Type › Auto Size New Area Type works too (new area type gets Auto Size). They reach agents too (`prefs.set`, then `pointer_gesture` or `press_key`; `ui.wheel` on the control channel). Then Smart Guides › Spacing Guides (moves space the selection evenly with its row or column, see Drawing aids). Then Hyphenation › Exceptions (comma-separated words that never break, or break only at their hyphens; `prefs.set` and restore push them into the hyphenator, #394). Then Type › Show Font Names in English (off, font menus label a family by its native-language name when the font has one; documents still use the English family, #394). Then General › Display Print Size at 100% Zoom (off by default: View › Actual Size is one document point per screen point; on, one document inch fills 96 screen points, an inch at the reference density display scaling is set against; `view.actualSize` / `prefs.set`, #394). Then Guides & Grid › Gridline every and Subdivisions (changing either sets the grid of every open document; new and opened documents take that grid too, except a native file and the native document an SVG, PDF, `.ai` or EPS file carries, which open with the grid they were saved with; `file.new`, `document.open`, `file.newFromTemplate`, `file.revert`, #394). Then Appearance of Black › On Screen (Display All Blacks Accurately by default: pure CMYK black shows through the CMYK profile, a dark grey; Display All Blacks as Rich Black shows it on the canvas as RGB black, also in CMYK documents drawn by ink planes, while rich blacks, black tints and images show as before; `RenderOptions::rich_black`, #394). Then Appearance of Black › Printing / Exporting (Output All Blacks Accurately by default; Output All Blacks as Rich Black draws pure CMYK black as RGB black in RGB raster exports and Print as Bitmap; CMYK ink exports and the document stay unchanged; `prefs.blackOutput` / `richBlack`, #394). Then Units › Identify Objects By (Object Name by default: Layers, Variables and Layer Options show and edit free names; XML ID shows and edits AI-style XML ids, `_` for a space and `_xHH_` escapes, and `layer.setProps` / rename refuse invalid ids; the document still stores the object name, #394). Then Type › Highlight Alternate Glyphs (off by default; on, pink shows behind OpenType substitutions on screen, such as ligatures and contextual forms; Document Setup's Highlight Substituted Glyphs stays separate; `prefs.set` key `highlightAlternateGlyphs`, #394). Then Units › East Asian Type (the bullet below). Then User Interface › Open Documents As Tabs (see Window › Arrange). Two stored options still do nothing yet: Plug-ins & Scratch Disks › Primary and Secondary, and Clipboard Handling › Legacy vector clipboard (the audit below). - Preferences › General › Scroll Sideways with Cmd/Ctrl + Wheel (on by default; dimmed while Zoom with Mouse Wheel is on): while Zoom with Mouse Wheel is off, Cmd/Ctrl with a mouse wheel's whole notches scrolls the canvas sideways instead of zooming. Alt + Cmd/Ctrl-wheel and a pinch on a Mac trackpad, on a touch screen or in the web build still zoom about the pointer, and once a trackpad gesture holds Alt, it zooms until it ends, also after Alt is let go. Under either wheel preference, Cmd/Ctrl with a touchpad zooms about the pointer. diff --git a/docs/ui-parity.md b/docs/ui-parity.md index 4182189c4a..0f7fab3aa4 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -446,7 +446,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po | Control bar: Paragraph: link and Align left/center/right while type is selected (#5372) | done | After the Character controls, as the public documentation has the Control panel format paragraphs ([Paragraph panel overview](https://helpx.adobe.com/illustrator/using/formatting-paragraphs.html), [Align text](https://helpx.adobe.com/illustrator/using/align-text.html)); the link opens the Paragraph panel in a popover, as Character: does with the Character panel. The bar trims from its right end: X/Y/W/H, Distribute, Align, area type vertical alignment, then these buttons, then the link. The three-button set is our choice for room; all seven alignments are in the popover. `panels/paragraph/tests.rs` headless tests (`the_control_bar_shows_the_paragraph_alignment_of_the_selected_type`, `the_control_bar_trims_its_paragraph_section_after_the_controls_to_its_right`) | | Pathfinder shape results keep their source names and SVG IDs | done | #1293; Minus Front keeps the back name, Minus Back the front name; Unite/Intersect/Exclude use the backmost named input; compound output carries it once; geometry and paint unchanged | | Attributes fill-rule controls with a compound member selected | done | Edits the compound's rule; direction still edits only the member; rendered-hole and Undo/Redo regression tests (#1197) | -| Info panel follows the tool in use: W and H show the change in x and y, with the distance and the angle, while the selection moves or the Gradient tool draws a vector; the Scale tool's percentages; the center and angles of a Rotate, Reflect or Shear tool drag; the Zoom tool's magnification; the Paintbrush's brush. W and H follow Use Preview Bounds, several selected objects show only the paint and type they share, and Show Options names a tint or a gradient swatch | done | `info.readout`; `Tool::readout`; behavior from the Info panel overview in the [archived user guide](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=76); number formats, the rows shown between drags and the Direct Selection and Group Selection readouts are VectorCraft's own | +| Info panel follows the tool in use: W and H show the change in x and y, with the distance and the angle, while the selection moves, the Gradient tool draws a vector or a Pen drag pulls out an anchor's handle; the Scale tool's percentages; the center and angles of a Rotate, Reflect or Shear tool drag; the Zoom tool's magnification; the Paintbrush's brush. W and H follow Use Preview Bounds, several selected objects show only the paint and type they share, and Show Options names a tint or a gradient swatch | done | `info.readout`; `Tool::readout`; behavior from the Info panel overview in the [archived user guide](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=76); number formats, the rows shown between drags and the Direct Selection and Group Selection readouts are VectorCraft's own | | Make Compound Path on a group (such as outlined type) keeps its backmost path's paint; compound paths joined into one keep their holes | done | #1537 | | Symbol libraries: Window › Symbol Libraries (Basic Shapes, UI Frames, Map Markers, Inventory Icons, Skill Icons, User Defined, Other Library…, Save Symbols…) and the Symbols panel's Symbol Libraries Menu button and its menu's Open Symbol Library / Save Symbol Library…; a click on a library symbol adds it to the document's Symbols (one undo step, it becomes the current symbol), Shift/Cmd-clicks select for Add to Symbols, and a symbol dragged onto the canvas is added and placed where it is dropped | done | [public source](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-or-import-symbol-libraries.html), [Symbols panel options](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/symbols-panel-options.html), [placing from a library](https://helpx.adobe.com/illustrator/desktop/manage-objects/traces-mockups-symbols/create-and-place-symbols.html); `window.symbolLibrary`, `window.symbolLibrary.other`, `ui.saveSymbolLibrary` (dialog `saveSymbolLibrary`), `window.userSymbolLibrary1`…`10`; `panels::tests_symbol_libraries`; five built-in libraries (Basic Shapes, UI Frames with default 9-slice, Map Markers, Inventory Icons, Skill Icons; original, generated in code) | | Brush libraries: Window › Brush Libraries (Art Ribbons, Ink and Wash, Calligraphic Nibs, Bristle Brushes, Pattern Borders, Scatter Shapes, Game Trails, Energy Beams, Dry Media, Tech Circuit, User Defined, Other Library…, Save Brushes…) and the Brushes panel's Brush Libraries Menu button and its menu's Open Brush Library / Save Brush Library…; a click on a library brush adds it to the document's Brushes (one undo step, it becomes the current brush, and selected paths take it in the same step), Shift/Cmd-clicks select 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; thumbnails render with the library's patterns and symbols | done | [public source](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/create-new-brush-libraries.html), [import brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/import-brushes-from-brush-libraries-or-other-files.html), [Brushes panel overview](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/brushes-panel-overview.html); `window.brushLibrary`, `window.brushLibrary.other`, `ui.saveBrushLibrary` (dialog `saveBrushLibrary`), `window.userBrushLibrary1`…`10`; `panels::tests_brush_libraries`; ten built-in libraries (original, generated in code) | From 1f41683f58f4baa4e4675503d9cbc731a78249d0 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 17 Nov 2026 15:07:06 -0800 Subject: [PATCH 145/176] Color Themes: Set Active Color paints the current fill or stroke with the selected color A button on the Create tab, beside the pipette that copies the current color into the theme, does the reverse: it sends the selected theme color to the proxy in front, through paint.setFill or paint.setStroke with keepModel, so the selection and the default for new art take it in its own color model. A click is one undo step; a click that changes no art adds none. The button is off without a document. The help page describes this action for creating a color theme: https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=222 --- crates/ui-egui/src/i18n/bg.tsv | 1 + crates/ui-egui/src/i18n/bs.tsv | 1 + crates/ui-egui/src/i18n/ca.tsv | 1 + crates/ui-egui/src/i18n/cs.tsv | 1 + crates/ui-egui/src/i18n/da.tsv | 1 + crates/ui-egui/src/i18n/de.tsv | 1 + crates/ui-egui/src/i18n/el.tsv | 1 + crates/ui-egui/src/i18n/es.tsv | 1 + crates/ui-egui/src/i18n/fi.tsv | 1 + crates/ui-egui/src/i18n/fr.tsv | 1 + crates/ui-egui/src/i18n/gu.tsv | 1 + crates/ui-egui/src/i18n/hi.tsv | 1 + crates/ui-egui/src/i18n/hu.tsv | 1 + crates/ui-egui/src/i18n/id.tsv | 1 + crates/ui-egui/src/i18n/it.tsv | 1 + crates/ui-egui/src/i18n/ja.tsv | 1 + crates/ui-egui/src/i18n/ka.tsv | 1 + crates/ui-egui/src/i18n/ko.tsv | 1 + crates/ui-egui/src/i18n/nl.tsv | 1 + crates/ui-egui/src/i18n/pl.tsv | 1 + crates/ui-egui/src/i18n/pt-br.tsv | 1 + crates/ui-egui/src/i18n/ru.tsv | 1 + crates/ui-egui/src/i18n/sv.tsv | 1 + crates/ui-egui/src/i18n/tr.tsv | 1 + crates/ui-egui/src/i18n/uk.tsv | 1 + crates/ui-egui/src/i18n/vi.tsv | 1 + crates/ui-egui/src/i18n/zh-hans.tsv | 1 + crates/ui-egui/src/i18n/zh-hant.tsv | 1 + crates/ui-egui/src/panels/color_themes.rs | 145 +++++++++++++++++++++- docs/mcp.md | 4 +- docs/target-app-parity.md | 1 + 31 files changed, 176 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index bb039bb08e..39a6763bce 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -3368,6 +3368,7 @@ digits Malayalam Малаялам Set Slice Rectangle Задаване на правоъгълник за резен Set Tab Stops Задаване на табулатори Set Text Задаване на текст + Set the current fill or stroke to the selected color Задаване на избрания цвят като текущо запълване или щрих Set the selected color to the current color Задаване на текущия цвят като избран Set Zoom Задаване на мащаб Settings… Настройки… diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 99f23d313c..0040ce03ba 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -1735,6 +1735,7 @@ digits Malayalam Malajalam Rule: Pravilo: Save changes to {name} Sačuvaj promjene u {name} Save theme to My Themes Sačuvaj temu u Moje teme + Set the current fill or stroke to the selected color Postavi odabranu boju kao trenutnu ispunu ili potez Set the selected color to the current color Postavi odabranu boju na trenutnu boju Copy All Styles Kopiraj sve stilove Exported {path} Izvezeno: {path} diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index c54311799d..b3268d2d6d 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -4384,6 +4384,7 @@ digits Malayalam Malaiàlam Set Slice Rectangle Defineix el rectangle del tall Set Tab Stops Defineix les tabulacions Set Text Defineix el text + Set the current fill or stroke to the selected color Defineix el color seleccionat com a farciment o traç actual Set the selected color to the current color Defineix el color seleccionat com a color actual Set Zoom Defineix el zoom Set: Defineix: diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index a5d7bb948a..1afc32ca06 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -1806,6 +1806,7 @@ digits Malayalam Malajálamské Rule: Pravidlo: Save changes to {name} Uložit změny do {name} Save theme to My Themes Uložit motiv do Mých motivů + Set the current fill or stroke to the selected color Nastavit vybranou barvu jako aktuální výplň nebo tah Set the selected color to the current color Nastavit vybranou barvu jako aktuální barvu Copy All Styles Kopírovat všechny styly Exported {path} Exportováno: {path} diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 08100f593f..1d94859379 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -4403,6 +4403,7 @@ digits Malayalam Malayalam Rule: Regel: Save changes to {name} Gem ændringer i {name} Save theme to My Themes Gem tema i Mine temaer + Set the current fill or stroke to the selected color Sæt den aktuelle udfyldning eller streg til den markerede farve Set the selected color to the current color Sæt den markerede farve til den aktuelle farve Copy All Styles Kopiér alle typografier Exported {path} Eksporterede {path} diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 10147b2d45..d5390308a5 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -3434,6 +3434,7 @@ digits Malayalam Malayalam Set Slice Rectangle Slice-Rechteck festlegen Set Tab Stops Tabstopps festlegen Set Text Text festlegen + Set the current fill or stroke to the selected color Aktuelle Fläche oder Kontur auf die ausgewählte Farbe setzen Set the selected color to the current color Ausgewählte Farbe auf die aktuelle Farbe setzen Set Zoom Zoom festlegen Settings… Einstellungen… diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 1ebf6e5684..99f4bc2345 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -4127,6 +4127,7 @@ digits Malayalam Μαλαγιάλαμ Set Slice Rectangle Ορισμός ορθογωνίου τομής Set Tab Stops Ορισμός στηλοθετών Set Text Ορισμός κειμένου + Set the current fill or stroke to the selected color Ορισμός επιλεγμένου χρώματος ως τρέχοντος γεμίσματος ή περιγράμματος Set the selected color to the current color Ορισμός επιλεγμένου χρώματος ως τρέχοντος Set Zoom Ορισμός ζουμ Setup… Ρύθμιση… diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index a456910a16..86a7cf29d1 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -3470,6 +3470,7 @@ digits Malayalam Malayálam Set Slice Rectangle Definir rectángulo de sector Set Tab Stops Definir tabulaciones Set Text Definir texto + Set the current fill or stroke to the selected color Asignar el color seleccionado al relleno o trazo actual Set the selected color to the current color Asignar el color actual al color seleccionado Set Zoom Definir zoom Settings… Ajustes… diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index bff46fc0d7..02d6b41b54 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -1779,6 +1779,7 @@ digits Malayalam Malajalam Rule: Sääntö: Save changes to {name} Tallenna muutokset kohteeseen {name} Save theme to My Themes Tallenna teema Omiin teemoihin + Set the current fill or stroke to the selected color Aseta nykyiseksi täytöksi tai viivaksi valittu väri Set the selected color to the current color Aseta valituksi väriksi nykyinen väri Copy All Styles Kopioi kaikki tyylit Exported {path} Viety: {path} diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 3be3497f97..ab3b778a44 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -3458,6 +3458,7 @@ digits Malayalam Malayalam Set Slice Rectangle Définir le rectangle de tranche Set Tab Stops Définir les taquets de tabulation Set Text Définir le texte + Set the current fill or stroke to the selected color Appliquer la couleur sélectionnée au fond ou au contour actuel Set the selected color to the current color Remplacer la couleur sélectionnée par la couleur actuelle Set Zoom Définir le zoom Settings… Réglages… diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index c427fc527c..d888d68c64 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -3614,6 +3614,7 @@ Set Zoom ઝૂમ સેટ કરો Set as Default ડિફૉલ્ટ તરીકે સેટ કરો Set base color to the current color બેઝ રંગ વર્તમાન રંગ પર સેટ કરો + Set the current fill or stroke to the selected color વર્તમાન ભરો અથવા સ્ટ્રોક પસંદ કરેલ રંગ પર સેટ કરો Set the selected color to the current color પસંદ કરેલ રંગ વર્તમાન રંગ પર સેટ કરો Set {n} {n} સેટ કરો Settings સેટિંગ્સ diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index cbfb4f51d1..dac53b50d4 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -4699,6 +4699,7 @@ antiAlias Sharp शार्प Set Slice Rectangle सेट स्लाइस आयत Set Tab Stops टैब स्टॉप्स सेट करें Set Text टेक्स्ट सेट करें + Set the current fill or stroke to the selected color वर्तमान फ़िल या स्ट्रोक को सिलेक्टेड रंग में सेट करें Set the selected color to the current color सिलेक्टेड रंग को वर्तमान रंग में सेट करें Set Zoom ज़ूम सेट करें Set: सेट: diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 0f81a72036..fe31367b01 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -4104,6 +4104,7 @@ mark-style Japanese Japán Set Slice Rectangle Szelet téglalapjának beállítása Set Tab Stops Tabulátorpontok beállítása Set Text Szöveg beállítása + Set the current fill or stroke to the selected color Az aktuális kitöltés vagy körvonal legyen a kijelölt szín Set the selected color to the current color A kijelölt szín legyen az aktuális szín Set Zoom Nagyítás beállítása Set: Készlet: diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 28ea2b5ab3..0470b4143b 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -1662,6 +1662,7 @@ digits Malayalam Malayalam Rule: Aturan: Save changes to {name} Simpan perubahan ke {name} Save theme to My Themes Simpan tema ke Tema saya + Set the current fill or stroke to the selected color Atur isian atau stroke saat ini ke warna terpilih Set the selected color to the current color Atur warna terpilih ke warna saat ini Copy All Styles Salin semua gaya Exported {path} Diekspor ke {path} diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 8f2ed3216c..9e9cdd4ecc 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -3515,6 +3515,7 @@ digits Malayalam Malayalam Set Slice Rectangle Imposta rettangolo sezione Set Tab Stops Imposta tabulazioni Set Text Imposta testo + Set the current fill or stroke to the selected color Imposta il riempimento o la traccia corrente sul colore selezionato Set the selected color to the current color Imposta il colore selezionato sul colore corrente Set Zoom Imposta zoom Settings… Impostazioni… diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index c429f204a1..85c7863402 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -3370,6 +3370,7 @@ mark-style Japanese 日本式 Set Text テキストを設定 Set Zoom ズーム率を設定 Set base color to the current color 基本カラーを現在のカラーに設定 + Set the current fill or stroke to the selected color 現在の塗りまたは線を選択したカラーに設定 Set the selected color to the current color 選択したカラーを現在のカラーに設定 Setup… 設定… Shape Builder シェイプ形成ツール diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 414f45171c..a5b39faff5 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -3840,6 +3840,7 @@ digits Malayalam მალაიალამური Rule: წესი: Save changes to {name} ცვლილებების შენახვა: {name} Save theme to My Themes თემის შენახვა „ჩემ თემებში“ + Set the current fill or stroke to the selected color მიმდინარე შევსების ან კონტურის მონიშნულ ფერად დაყენება Set the selected color to the current color მონიშნული ფერის მიმდინარე ფერად დაყენება Copy All Styles ყველა სტილის კოპირება Exported {path} ექსპორტირებულია: {path} diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index dbda53243f..cb844c6967 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -3359,6 +3359,7 @@ mark-style Japanese 일본식 Set Text 문자 설정 Set Zoom 확대/축소 설정 Set base color to the current color 기준 색상을 현재 색상으로 설정 + Set the current fill or stroke to the selected color 현재 칠 또는 선을 선택한 색상으로 설정 Set the selected color to the current color 선택한 색상을 현재 색상으로 설정 Setup… 설정… Shape Builder 모양 빌더 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 69aef91cfc..67ca26851d 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -2277,6 +2277,7 @@ digits Malayalam Malayalam Rule: Regel: Save changes to {name} Wijzigingen opslaan in {name} Save theme to My Themes Thema opslaan in Mijn thema's + Set the current fill or stroke to the selected color De huidige vulling of contour op de geselecteerde kleur instellen Set the selected color to the current color De geselecteerde kleur op de huidige kleur instellen Copy All Styles Alle stijlen kopiëren Exported {path} {path} geëxporteerd diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 0147515ffe..27bb8a9a6e 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -1718,6 +1718,7 @@ digits Malayalam Malajalam Rule: Reguła: Save changes to {name} Zapisz zmiany w {name} Save theme to My Themes Zapisz motyw w Moich motywach + Set the current fill or stroke to the selected color Ustaw bieżące wypełnienie lub obrys na zaznaczony kolor Set the selected color to the current color Ustaw zaznaczony kolor na bieżący Copy All Styles Kopiuj wszystkie style Exported {path} Wyeksportowano {path} diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 8201db7ab6..7dd1122049 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -2920,6 +2920,7 @@ digits Malayalam Malaiala Set Text Definir Texto Set Zoom Definir Zoom Set base color to the current color Definir cor base para a cor atual + Set the current fill or stroke to the selected color Definir o preenchimento ou traçado atual para a cor selecionada 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 diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index d1593508d3..158f57fd15 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -3502,6 +3502,7 @@ digits Malayalam Малаялам Set Slice Rectangle Задать прямоугольник фрагмента Set Tab Stops Задать табуляции Set Text Задать текст + Set the current fill or stroke to the selected color Назначить выбранный цвет текущей заливке или обводке Set the selected color to the current color Назначить текущий цвет выбранному цвету Set Zoom Задать масштаб Settings… Параметры… diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 5c0420fcd3..5da7dc1765 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -3388,6 +3388,7 @@ digits Malayalam Malayalam Set Slice Rectangle Ange skivrektangel Set Tab Stops Ange tabbstopp Set Text Ange text + Set the current fill or stroke to the selected color Ersätt den aktuella fyllningen eller konturen med den markerade färgen Set the selected color to the current color Ersätt den markerade färgen med den aktuella färgen Set Zoom Ange zoom Settings… Inställningar… diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 910a7fc5b1..0fb6299690 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -3260,6 +3260,7 @@ digits Malayalam Malayalam Set Slice Rectangle Dilim Dikdörtgenini Ayarla Set Tab Stops Sekme Duraklarını Ayarla Set Text Metni Ayarla + Set the current fill or stroke to the selected color Geçerli dolguyu veya konturu seçilen renge ayarla Set the selected color to the current color Seçilen rengi geçerli renge ayarla Set Zoom Yakınlaştırmayı Ayarla Settings… Ayarlar… diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index dbd6d2609e..45e2e2af2f 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -3507,6 +3507,7 @@ digits Malayalam Малаялам Set Slice Rectangle Вказати прямокутник фрагмента Set Tab Stops Задати табуляції Set Text Задати текст + Set the current fill or stroke to the selected color Призначити вибраний колір поточній заливці або обведенню Set the selected color to the current color Призначити поточний колір вибраному кольору Set Zoom Задати масштаб Settings… Параметри… diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 519c5d8f0d..8b2b0ab086 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -3861,6 +3861,7 @@ mark-style Japanese Kiểu Nhật Set Slice Rectangle Đặt hình chữ nhật lát cắt Set Tab Stops Đặt vị trí tab Set Text Đặt văn bản + Set the current fill or stroke to the selected color Đặt tô hoặc nét hiện tại thành màu đã chọn Set the selected color to the current color Đặt màu đã chọn thành màu hiện tại Set Zoom Đặt thu phóng Settings Cài đặt diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index c6696a9ec6..eb840880dc 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -3331,6 +3331,7 @@ digits Malayalam 马拉雅拉姆数字 Set Slice Rectangle 设置切片矩形 Set Tab Stops 设置制表位 Set Text 设置文本 + Set the current fill or stroke to the selected color 将当前填色或描边设为选择的颜色 Set the selected color to the current color 将选择的颜色设为当前颜色 Set Zoom 设置缩放 Settings… 设置… diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 1480422931..a1874653ec 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -4648,6 +4648,7 @@ digits Malayalam 馬來亞拉姆數字 Set Slice Rectangle 設定切片矩形 Set Tab Stops 設定定位點 Set Text 設定文字 + Set the current fill or stroke to the selected color 將目前填色或筆畫設為選取的顏色 Set the selected color to the current color 將選取的顏色設為目前顏色 Set Zoom 設定縮放 Settings… 設定… diff --git a/crates/ui-egui/src/panels/color_themes.rs b/crates/ui-egui/src/panels/color_themes.rs index d736fa415b..efa55f284e 100644 --- a/crates/ui-egui/src/panels/color_themes.rs +++ b/crates/ui-egui/src/panels/color_themes.rs @@ -10,7 +10,7 @@ use vectorcraft_color::Color; use vectorcraft_color::harmony::{Harmony, THEME_SIZE, move_on_wheel}; use vectorcraft_engine::cmd::colortheme::ColorTheme; -use super::{active_paint, c32, color_json, empty_state, pstate, set_pstate}; +use super::{active_paint, c32, color_json, empty_state, proxy_cmd, pstate, set_pstate}; use crate::VectorcraftApp; use crate::theme::{self, Tokens}; use crate::widgets::{self, menu_item}; @@ -126,6 +126,15 @@ fn add_draft_to_swatches(app: &mut VectorcraftApp, ctx: &egui::Context) { app.run("swatch.newGroup", json!({ "name": name, "colors": colors_json(&d.colors), "keepModel": true })).ok(); } +/// Paint the active proxy (Fill or Stroke) with the selected colour of the theme being made, in its +/// own model: the selection and the new-art default take it in one paint command, so one undo +/// step, and no step when the art already has it. The theme stays as it is. +fn set_active_color(app: &mut VectorcraftApp, d: &Draft) { + if let Some(c) = d.colors.get(d.sel) { + app.run(proxy_cmd(app, false), json!({ "color": color_json(c), "keepModel": true })).ok(); + } +} + pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) { let ctx = ui.ctx().clone(); ui.horizontal(|ui| { @@ -192,6 +201,11 @@ fn create(app: &mut VectorcraftApp, ui: &mut Ui) { if let Some(c) = widgets::hex_field_named(ui, "ct-hex", Some(tl!("Color")), &hex).and_then(|h| Color::from_hex(&h)) { d.set_selected(c); } + let can_set = app.session.active().is_some() && d.colors.get(d.sel).is_some(); + let tip = tl!("Set the current fill or stroke to the selected color"); + if widgets::icon_button_enabled(ui, "paint-bucket", tip, false, can_set, 24.0).clicked() { + set_active_color(app, &d); + } let current = active_paint(app).color(); if widgets::icon_button_enabled(ui, "pipette", tl!("Set the selected color to the current color"), false, current.is_some(), 24.0).clicked() && let Some(c) = current @@ -454,6 +468,135 @@ mod tests { frame(&mut app, &ctx); } + const SET_ACTIVE: &str = "Set the current fill or stroke to the selected color"; + + /// A click on the panel button that screen readers name `label`. egui finds what the pointer is + /// over from the frame before, so the move gets a frame of its own. + fn click(app: &mut VectorcraftApp, ctx: &egui::Context, label: &str) { + crate::i18n::set_current(crate::i18n::Lang::EN); + ctx.enable_accesskit(); + let mut time = ctx.input(|i| i.time); + let mut run = |app: &mut VectorcraftApp, events: Vec<egui::Event>| { + time += 0.1; + let screen = Rect::from_min_size(egui::Pos2::ZERO, vec2(320.0, 520.0)); + let input = egui::RawInput { events, time: Some(time), screen_rect: Some(screen), ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| show(app, ui)); + out.textures_delta.clear(); + out + }; + run(app, vec![]); + let out = run(app, vec![]); + let nodes = &out.platform_output.accesskit_update.as_ref().expect("an accessibility tree").nodes; + let node = nodes.iter().find(|(_, n)| n.label() == Some(label)); + let b = node.unwrap_or_else(|| panic!("nothing named {label:?}")).1.bounds().expect("bounds"); + let at = egui::pos2((b.x0 + b.x1) as f32 * 0.5, (b.y0 + b.y1) as f32 * 0.5); + let button = + |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + run(app, vec![egui::Event::PointerMoved(at)]); + run(app, vec![button(true)]); + run(app, vec![button(false)]); + } + + /// A Custom theme of five different colours with the third selected. + fn five_colors(ctx: &egui::Context) -> Draft { + let colors = ["#cc2200", "#22aa44", "#3355dd", "#ddbb11", "#884499"].map(|h| Color::from_hex(h).unwrap()).to_vec(); + let d = Draft { colors, rule: None, sel: 2, name: "Mine".into(), editing: None }; + set_draft(ctx, d.clone()); + d + } + + /// The fill and stroke paints of object `id`. + fn paints(app: &VectorcraftApp, id: vectorcraft_doc::NodeId) -> (vectorcraft_color::Paint, vectorcraft_color::Paint) { + let n = app.session.doc().unwrap().doc.node(id).unwrap(); + (n.appearance.fill().unwrap().paint.clone(), n.appearance.stroke().unwrap().paint.clone()) + } + + fn undo_len(app: &VectorcraftApp) -> usize { + app.session.doc().unwrap().history.undo.len() + } + + /// Screen readers name the Set Active Color button by its tool tip; it is off without a document. + #[test] + fn set_active_color_is_named_and_needs_a_document() { + use crate::widgets::accessibility_tests::{named, tree}; + let mut app = app(); + let shown = tree(|ui| show(&mut app, ui)); + assert_eq!(named(&shown, SET_ACTIVE).role(), egui::accesskit::Role::Button); + assert!(!named(&shown, SET_ACTIVE).is_disabled()); + let mut none = VectorcraftApp::new(Session::new(), Default::default()); + let shown = tree(|ui| show(&mut none, ui)); + assert!(named(&shown, SET_ACTIVE).is_disabled(), "no document: nothing to paint"); + } + + /// Set Active Color paints the active proxy of the selection with the selected theme colour, + /// one undo step a click, none when the art already has it, and leaves the theme as it is. + #[test] + fn set_active_color_paints_the_active_proxy_with_the_selected_color() { + let mut app = app(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 30, "height": 20})).unwrap(); + let id = app.session.doc().unwrap().selection.objects[0]; + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let d = five_colors(&ctx); + let (_, stroke) = paints(&app, id); + let undo = undo_len(&app); + click(&mut app, &ctx, SET_ACTIVE); + assert_eq!(paints(&app, id), (vectorcraft_color::Paint::solid(d.colors[2]), stroke.clone()), "the selected colour, not the first"); + assert_eq!(undo_len(&app), undo + 1, "one undo step"); + click(&mut app, &ctx, SET_ACTIVE); + assert_eq!(undo_len(&app), undo + 1, "no step when the fill already has the colour"); + // With the Stroke proxy in front, the stroke takes the colour and the fill stays. + app.run("paint.toggleActive", json!({"fill": false})).unwrap(); + set_draft(&ctx, Draft { sel: 3, ..d.clone() }); + click(&mut app, &ctx, SET_ACTIVE); + let solid = |i: usize| vectorcraft_color::Paint::solid(d.colors[i]); + assert_eq!(paints(&app, id), (solid(2), solid(3))); + assert_eq!(undo_len(&app), undo + 2); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(paints(&app, id), (solid(2), stroke.clone()), "one undo takes the stroke back"); + app.run("edit.redo", json!({})).unwrap(); + assert_eq!(paints(&app, id), (solid(2), solid(3))); + // The theme being made and the saved themes stay as they were. + assert_eq!(draft(&app, &ctx), Draft { sel: 3, ..d.clone() }); + assert!(themes(&app).is_empty()); + // The reverse pipette paints nothing. + let undo = undo_len(&app); + click(&mut app, &ctx, "Set the selected color to the current color"); + assert_eq!((paints(&app, id), undo_len(&app)), ((solid(2), solid(3)), undo)); + } + + /// With nothing selected, Set Active Color sets the new-art default alone, without an undo step, + /// and new art takes it. + #[test] + fn set_active_color_with_nothing_selected_sets_the_default_for_new_art() { + let mut app = app(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let d = five_colors(&ctx); + let undo = undo_len(&app); + click(&mut app, &ctx, SET_ACTIVE); + assert_eq!(app.session.paint.fill, vectorcraft_color::Paint::solid(d.colors[2])); + assert_eq!(undo_len(&app), undo, "no art changed"); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 30, "height": 20})).unwrap(); + let id = app.session.doc().unwrap().selection.objects[0]; + assert_eq!(paints(&app, id).0, vectorcraft_color::Paint::solid(d.colors[2])); + } + + /// In a CMYK document Set Active Color keeps an RGB theme colour in RGB. + #[test] + fn set_active_color_keeps_the_model_in_a_cmyk_document() { + let mut app = app(); + app.run("file.documentColorMode", json!({"mode": "cmyk"})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 30, "height": 20})).unwrap(); + let id = app.session.doc().unwrap().selection.objects[0]; + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let d = five_colors(&ctx); + click(&mut app, &ctx, SET_ACTIVE); + assert_eq!(paints(&app, id).0.color(), Some(d.colors[2])); + assert!(matches!(d.colors[2], Color::Rgb { .. })); + } + /// In a CMYK document the theme being made goes to Swatches with its colors in their own model. #[test] fn the_theme_being_made_keeps_its_model_in_a_cmyk_document() { diff --git a/docs/mcp.md b/docs/mcp.md index 4c1b661f42..6dd13e3422 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1099,7 +1099,9 @@ Color Themes (local only: no online service) keeps five-colour themes in the pre harmony rule makes from a base colour (base first; `name?` defaults to "Theme N", `replace: "<name>"` overwrites that theme in place). `colorTheme.list` answers `{themes: [{name, colors: [hex], keys: [colour keys], rule?}]}`, `colorTheme.delete {name}` removes one and `colorTheme.addToSwatches {name}` adds one to the Swatches panel as a -colour group (one undo step). +colour group (one undo step). The Create tab's Set the current fill or stroke to the selected color button runs +`paint.setFill` (or `paint.setStroke` with the Stroke proxy in front) with the selected colour and `keepModel: true`; +a script does the same with those commands. ```json {"name":"run_command","arguments":{"command":"colorTheme.save","params":{"color":"#2266aa","rule":"splitComplementary","name":"Harbor"}}} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index ef83de54ad..bc3ae3941c 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1776,6 +1776,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **RGB input to other commands in a CMYK document:** type colors (`text.create`, `text.setStyle`, `text.setRangeStyle`), a Shape Builder hex fill, `paint.editGradient` stops, freeform gradient points, gradient mesh points (the Mesh tool gives a new point the fill's color in its own model), the Symbol Stainer's color and the swatch commands (`swatch.new {colors}`, `swatch.newGroup`, `swatch.editGroup`, `swatch.edit`) separate RGB through the color settings as `paint.setFill` does: with Generic CMYK, `text.setStyle {fill: "#53aadf"}` gives C62 M19 Y0 K0. A color a swatch already has keeps its model, and a swatch color given with `mode` is converted into that mode only. - **Generic CMYK (SWOP-like):** each ink's 40% and 50% tints gain as [CGATS TR 001](https://registry.color.org/cmyk-registry/cgats_tr_001) gives for SWOP printing, and separations stay within SWOP's [300% total ink limit](https://en.wikipedia.org/wiki/Specifications_for_Web_Offset_Publications). The paper, solid and overprint colors, the black-generation curve and the black point are VectorCraft's own values: RGB black separates to 90% black under neutral cyan, magenta and yellow that fill the ink limit (C75 M68 Y67 K90). - **Swatches made from a shown color in a CMYK document:** the Color panel menu's Create New Swatch, an Alt-click on the Swatches panel's New Swatch button, the New Swatch dialog for a gradient, a Fill or Stroke proxy or the Gradient panel's thumbnail dropped on the Swatches panel (or Alt-dropped on a swatch of its kind), and the Gradient panel's Add to Swatches and Save to Swatches keep each color's model, as the Color Guide's and Color Themes' saved colors do: an RGB object's color gives an RGB swatch, and a gradient's RGB stops stay RGB. + - **Color Themes Set Active Color:** a button on the Color Themes panel's Create tab makes the selected theme color the current color, the action the [help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=222) describes for creating a color theme. VectorCraft's own rules: the color goes to the proxy in front (Fill or Stroke), on the selection and the default for new art, in its own color model, through `paint.setFill` or `paint.setStroke`; a click is one undo step, a click that changes no art adds none, and the button is off without a document. Tests: `set_active_color_*` in `crates/ui-egui/src/panels/color_themes.rs`. - **Sample Color from Screen:** an eyedropper button in the Color Picker and `ui.sampleScreenColor` (which can be given a key in Keyboard Shortcuts) pick a color anywhere on the screen with the system's sampler: `NSColorSampler` on macOS, the XDG desktop portal's [PickColor](https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.Screenshot.html) on Linux, a still copy of every monitor under a crosshair on Windows, and the EyeDropper API in browsers that have it. The color becomes the fill or the stroke as one undo step, or the Color Picker's color, converted from display sRGB into the working RGB space. On Linux, a session without a portal that has PickColor, a portal that does not return from the call within 25 seconds (VectorCraft's own limit) or leaves the bus before it answers, and a portal that ends the request another way each show a status message and end the wait. On Windows, the copy is read as sRGB, so the colors of HDR and wide-gamut displays are not converted; Escape, a click of another mouse button or switching to another window cancels (VectorCraft's own rules). The BSDs and other browsers have no sampler yet; the button is gray there. - **Color Guide color groups:** with variation cells selected, the Color Guide's Save Color Group to Swatches button saves those cells as one swatch group, and with none selected it saves the harmony colors, as the [help page](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf) describes saving several selected variations together (printed page 135). The group takes the cells in grid order (row by row, left to right, each cell once), is named after the harmony rule and is one undo step; these are VectorCraft's own rules. A selection lasts until the base, the Color Guide Options, the variation mode, the harmony rule, the library limit or the colors the grid shows (for example after a new swatch while the guide is limited to the document's swatches) change. - **Color Guide colors dragged to Swatches:** a variation cell dragged from the Color Guide onto the Swatches panel's list becomes a swatch of that color, as the [help page](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf) describes for saving variations as individual swatches (printed page 135). In VectorCraft a harmony strip color drags the same way, a drag carries only the grabbed color (the selected cells stay selected and the selection is not saved), it carries the color the cell shows (snapped to the Limit to Library colors), keeps the color's model and does not paint the selected art; the swatch follows the panel's rules for a dropped color (`swatch.new`, one undo step, a color that is already a swatch is added again under another name, a drop on a color group joins it). These are VectorCraft's own rules. Tests: `a_dragged_guide_color_carries_its_color_and_applies_nothing` and `a_guide_color_dragged_onto_the_swatches_panel_becomes_a_swatch` in `crates/ui-egui/src/panels/color_guide.rs`. From 1c89800023ed3d02c8b23dee529f8762978eea1c Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 17 Nov 2026 12:35:57 -0800 Subject: [PATCH 146/176] Twist: keep fractional boundary tangents accurate --- crates/doc/src/live/warp.rs | 14 ++++++++- crates/effects/src/distort.rs | 22 ++++++++++++-- crates/effects/src/tests.rs | 55 +++++++++++++++++++++++++++++++++++ 3 files changed, 87 insertions(+), 4 deletions(-) diff --git a/crates/doc/src/live/warp.rs b/crates/doc/src/live/warp.rs index 64687e49fc..a921c7d2ff 100644 --- a/crates/doc/src/live/warp.rs +++ b/crates/doc/src/live/warp.rs @@ -564,7 +564,8 @@ fn map_pieces_within(path: &PathData, max_piece: f64, max: usize, f: &impl Fn(Po let c = seg_cubic(sp, i); let k = pieces(poly_len(&c), max_piece, MAX_PIECES); for j in 0..k { - let sub = c.subsegment((j as f64 / k as f64)..((j + 1) as f64 / k as f64)); + // Evaluating an unchanged curve can overflow even when its control points are finite. + let sub = if k == 1 { c } else { c.subsegment((j as f64 / k as f64)..((j + 1) as f64 / k as f64)) }; if let Some(last) = res.last_mut() { last.h_out = handle(sub.p0, sub.p1); } @@ -629,6 +630,17 @@ pub(super) fn resample(poly: &[Point], m: usize) -> Vec<Point> { mod handle_tests { use super::*; + #[test] + fn an_unsplit_curve_keeps_its_finite_control_points() { + let start = Point::new(1e308, 0.0); + let end = Point::new(1.03e308, 0.0); + let path = PathData::new(vec![SubPath::new( + vec![Anchor::with_handles(start, start, Point::new(1.01e308, 1.0)), Anchor::with_handles(end, Point::new(1.02e308, 1.0), end)], + false, + )]); + assert_eq!(map_handles_within(&path, 1.0, 2, |p| p, |_, h| h), path); + } + #[test] fn rounded_samples_preserve_a_smooth_interior_join() { let center = Point::new(1e16, 0.0); diff --git a/crates/effects/src/distort.rs b/crates/effects/src/distort.rs index 543b1a13cd..3fa1f3d152 100644 --- a/crates/effects/src/distort.rs +++ b/crates/effects/src/distort.rs @@ -336,11 +336,26 @@ pub fn twist(path: &PathData, b: Rect, angle: f64, max: usize) -> PathData { } let c = b.center(); let r = diag(b) / 2.0; + let half = Vec2::new(b.width() * 0.5, b.height() * 0.5); + let boundary = move |p: Point, length: f64| { + if length == r { + return true; + } + if !r.is_finite() || (length - r).abs() > 8.0 * f64::EPSILON * r { + return false; + } + // A bounds-relative distance identifies boundary points affected by center rounding. + (Vec2::new(p.x - b.x0, p.y - b.y0) - half).hypot() == r + }; let f = move |q: Point| { let d = q - c; - let t = (1.0 - d.hypot() / r).max(0.0); + let length = d.hypot(); + let t = (1.0 - length / r).max(0.0); // y runs down, so a positive turn is clockwise on the page. let a = ang * t; + if a == 0.0 { + return q; + } let (s, co) = a.sin_cos(); c + Vec2::new(d.x * co - d.y * s, d.x * s + d.y * co) }; @@ -354,8 +369,9 @@ pub fn twist(path: &PathData, b: Rect, angle: f64, max: usize) -> PathData { let length = d.hypot(); let radial = if length > 0.0 { (d / length).dot(v) } else { 0.0 }; // The clamped rotation has different inward and outward derivatives at the circle. - let gradient = if length < r || (length == r && radial < 0.0) { -ang / r * radial } else { 0.0 }; - let tangent = v + Vec2::new(-d.y, d.x) * gradient; + let inside = if boundary(p, length) { radial < 0.0 } else { length < r }; + let gradient = if inside { -ang / r * radial } else { 0.0 }; + let tangent = if gradient == 0.0 { v } else { v + Vec2::new(-d.y, d.x) * gradient }; let a = ang * (1.0 - length / r).max(0.0); let (s, co) = a.sin_cos(); f(p) + Vec2::new(tangent.x * co - tangent.y * s, tangent.x * s + tangent.y * co) diff --git a/crates/effects/src/tests.rs b/crates/effects/src/tests.rs index 2d0f70b0be..2a34fb1d07 100644 --- a/crates/effects/src/tests.rs +++ b/crates/effects/src/tests.rs @@ -1762,6 +1762,61 @@ fn twist_large_coordinate_joins_preserve_boundary_sides() { } } +#[test] +fn twist_fractional_boundary_handles_use_each_sides_derivative() { + use vectorcraft_geom::Anchor; + + for (bounds, step) in [(Rect::new(40.1, 30.0, 60.3, 30.0), 1.0), (Rect::new(-60.3, 30.0, -40.1, 30.0), 1.0)] { + for x in [bounds.x0, bounds.x1] { + for angle in [90.0_f64, 400.0, -720.0] { + let p = Point::new(x, 30.0); + let line = PathData::single(SubPath::new( + vec![ + Anchor::corner(Point::new(x - 3.0 * step, 30.0)), + Anchor::with_handles(p, Point::new(x - step, 30.0), Point::new(x + step, 30.0)), + Anchor::corner(Point::new(x + 3.0 * step, 30.0)), + ], + false, + )); + let out = crate::distort::twist(&line, bounds, angle, 3); + assert!( + out.subpaths[0].anchors.iter().all(|a| a.p.is_finite() && a.h_in.is_finite() && a.h_out.is_finite()), + "x={x} angle={angle}: {:?}", + out.subpaths[0].anchors + ); + let join = &out.subpaths[0].anchors[1]; + assert!(join.p.distance(p) < 1e-10, "{:?}", join.p); + let a = angle.to_radians(); + let expected = if x == bounds.x0 { [(-1.0, 0.0), (1.0, -a)] } else { [(-1.0, a), (1.0, 0.0)] }; + for (actual, (dx, dy)) in [join.h_in - join.p, join.h_out - join.p].into_iter().zip(expected) { + let expected = vectorcraft_geom::Vec2::new(dx, dy); + let error = actual.cross(expected).atan2(actual.dot(expected)).abs(); + assert!(error < 1e-9, "x={x} angle={angle}: {actual:?}, join={join:?}, source={:?}", line.subpaths[0].anchors[1]); + } + } + } + } + let bounds = Rect::new(1e16, 30.0, 1e16 + 18.0, 30.0); + let center = bounds.center(); + let line = PathData::single(SubPath::polyline(&[Point::new(center.x - 4.0, center.y), center, Point::new(center.x + 4.0, center.y)], false)); + let out = crate::distort::twist(&line, bounds, 90.0, 3); + assert_eq!(out.subpaths[0].anchors[1].p, center); + let bounds = Rect::new(0.0, 30.0, 2e16, 30.0); + let p = Point::new(bounds.x1 - 8.0, 30.0); + let line = PathData::single(SubPath::new( + vec![ + Anchor::corner(Point::new(p.x - 12.0, p.y)), + Anchor::with_handles(p, Point::new(p.x - 4.0, p.y), Point::new(p.x + 4.0, p.y)), + Anchor::corner(Point::new(p.x + 12.0, p.y)), + ], + false, + )); + let out = crate::distort::twist(&line, bounds, 90.0, 3); + let join = &out.subpaths[0].anchors[1]; + assert!(join.p.y - p.y > 10.0, "{:?}", join.p); + assert!(join.h_out.y - join.p.y < -4.0, "{join:?}"); +} + #[test] fn twist_fixes_the_outer_circle_and_rotates_inside() { let out = run("distort.twist", json!({"angle": 0}), &square()); From da010c6598e9f198c267abd97bf9d1784959a676 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 17 Nov 2026 15:30:22 -0800 Subject: [PATCH 147/176] Isolation: Exit Isolation Mode on a sublayer goes back one layer at a time With a sublayer isolated, Exit Isolation Mode now isolates its parent layer and selects the sublayer, so repeated use goes up one layer at a time and leaves isolation mode from the top-level layer, as the help page describes: https://helpx.adobe.com/illustrator/desktop/manage-objects/select-objects/isolate-objects.html This applies to the Layers panel menu item, the isolation bar's back arrow, the Control bar button, the canvas context menu, a double-click outside the art and object.exitIsolation {}. Before, each of them left isolation mode in one step. - object.exitIsolation takes all (default false); all: true leaves isolation mode from a sublayer at any depth. Any other value is an error. - Esc and the top-level layer's crumb on the isolation bar pass all: true, so they still leave in one step. A sublayer's crumb isolates that sublayer. - A hidden or locked parent layer is not isolated; the call leaves isolation mode. A step up records no undo step. Groups keep their rule. --- crates/engine/src/cmd/object/arrange.rs | 17 ++++++-- crates/engine/src/cmd/object/commands.rs | 2 +- crates/engine/src/tests/menucmds.rs | 52 ++++++++++++++++++++++++ crates/tools/src/direct.rs | 2 +- crates/ui-egui/src/canvas/tests.rs | 30 ++++++++++++++ crates/ui-egui/src/chrome/tabs.rs | 9 ++-- crates/ui-egui/src/chrome/tests.rs | 39 ++++++++++++++++++ crates/ui-egui/src/shortcuts.rs | 3 +- docs/mcp.md | 11 ++++- docs/target-app-parity.md | 1 + 10 files changed, 156 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/cmd/object/arrange.rs b/crates/engine/src/cmd/object/arrange.rs index 17568d50b9..ff0b22b31b 100644 --- a/crates/engine/src/cmd/object/arrange.rs +++ b/crates/engine/src/cmd/object/arrange.rs @@ -384,6 +384,11 @@ fn add_drawn_live_paint(s: &mut Session, isolated: NodeId, next: Option<NodeId>) } pub(super) fn exit_isolation(s: &mut Session, p: &Value) -> Result<Value> { + let key = "all"; + let all = match p.get(key) { + None => false, + Some(v) => v.as_bool().ok_or_else(|| bad("object.exitIsolation", format!("`{key}` must be true or false")))?, + }; // Opacity mask editing, pattern editing and symbol editing isolate their editing layer. Leaving // isolation mode then leaves that mode, as Stop Editing Opacity Mask and the isolation bar's // Done do. A group isolated inside the symbol's art goes back to the symbol's layer. @@ -419,12 +424,18 @@ pub(super) fn exit_isolation(s: &mut Session, p: &Value) -> Result<Value> { return ok(); } let menu = s.menu.clone(); - let prev = s.active().and_then(|d| d.isolation); + let prev = st.isolation; + // An isolated sublayer goes up to its parent layer, which stays isolated, unless `all` is true or + // that layer is hidden or locked; anything else leaves isolation mode. + let up = prev + .filter(|i| !all && st.doc.node(*i).is_some_and(Node::is_layer)) + .and_then(|i| st.doc.parent_of(i)) + .filter(|parent| st.doc.is_editable(*parent)); if let Some(i) = prev { crate::cmd::settle_interaction(s)?; - let left = add_drawn_live_paint(s, i, None)?.unwrap_or(i); + let left = add_drawn_live_paint(s, i, up)?.unwrap_or(i); let st = s.doc_mut()?; - st.isolation = None; + st.isolation = up; crate::cmd::distortcmds::finish_edit_text(st, i); let target = st.doc.parent_of(left).filter(|p| st.doc.node(*p).is_some_and(|n| n.extras().shaper.is_some())).unwrap_or(left); st.selection.set([target]); diff --git a/crates/engine/src/cmd/object/commands.rs b/crates/engine/src/cmd/object/commands.rs index 0c638ceb5e..d6840bd752 100644 --- a/crates/engine/src/cmd/object/commands.rs +++ b/crates/engine/src/cmd/object/commands.rs @@ -250,7 +250,7 @@ pub fn specs() -> Vec<CommandSpec> { "Exit Isolation Mode", [], None, - "{} leave isolation mode; leaving an isolated Live Paint group adds the paths, compound paths and groups of them drawn in it (shown and unlocked with everything in them) to the group as livePaint.merge does, in one undo step, and leaves type, images and other objects in it as they are; object.isolate on a level outside the group does the same", + "{all?: bool (default false)} leave isolation mode; from an isolated sublayer, go up one level to its parent layer instead (the next call goes up again), unless all is true or the parent layer is hidden or locked; no undo step for the move up; while a symbol is edited, a group isolated in its art goes back to the symbol's layer first, with or without all; leaving an isolated Live Paint group adds the paths, compound paths and groups of them drawn in it (shown and unlocked with everything in them) to the group as livePaint.merge does, in one undo step, and leaves type, images and other objects in it as they are; object.isolate on a level outside the group does the same", has_doc, exit_isolation ), diff --git a/crates/engine/src/tests/menucmds.rs b/crates/engine/src/tests/menucmds.rs index 1faeaa76ad..d7548e7986 100644 --- a/crates/engine/src/tests/menucmds.rs +++ b/crates/engine/src/tests/menucmds.rs @@ -4473,6 +4473,58 @@ fn exit_isolation_leaves_a_locked_guide_path_deselected() { assert_eq!(selected(&s), vec![g]); } +/// Exit Isolation Mode on an isolated sublayer isolates its parent layer and selects the sublayer, one +/// layer per call, without an undo step; from the top-level layer it leaves isolation mode. `all: true` +/// leaves from any depth, a hidden parent layer is not isolated (the call leaves), and a group in a +/// sublayer still leaves in one call. +#[test] +fn exit_isolation_goes_up_one_layer_from_a_sublayer() { + let mut s = session(); + let top = s.doc().unwrap().doc.layers[0].id; + let mid = id_of(&s.execute("layer.newSublayer", &json!({"parent": top.0})).unwrap()); + let deep = id_of(&s.execute("layer.newSublayer", &json!({"parent": mid.0})).unwrap()); + s.execute("layer.setCurrent", &json!({"id": deep.0})).unwrap(); + let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0); + let b = rect(&mut s, 20.0, 0.0, 10.0, 10.0); + let isolation = |s: &Session| s.doc().unwrap().isolation; + let exit = |s: &mut Session, p: Value| s.execute("object.exitIsolation", &p).unwrap(); + + s.execute("object.isolate", &json!({"id": deep.0})).unwrap(); + let before = history(&s); + exit(&mut s, json!({})); + assert_eq!((isolation(&s), selected(&s)), (Some(mid), vec![deep]), "up from the deepest sublayer"); + exit(&mut s, json!({})); + assert_eq!((isolation(&s), selected(&s)), (Some(top), vec![mid]), "up from the middle sublayer"); + exit(&mut s, json!({})); + assert_eq!((isolation(&s), selected(&s)), (None, vec![top]), "out from the top-level layer"); + assert_eq!(history(&s), before, "no undo step"); + + s.execute("object.isolate", &json!({"id": deep.0})).unwrap(); + exit(&mut s, json!({"all": true})); + assert_eq!((isolation(&s), selected(&s)), (None, vec![deep]), "all: true"); + s.execute("object.isolate", &json!({"id": deep.0})).unwrap(); + exit(&mut s, json!({"all": false})); + assert_eq!(isolation(&s), Some(mid), "all: false"); + for bad in [json!({"all": 1}), json!({"all": "yes"}), json!({"all": null})] { + let e = s.execute("object.exitIsolation", &bad).unwrap_err().to_string(); + assert!(e.contains("`all` must be true or false"), "{bad}: {e}"); + assert_eq!(isolation(&s), Some(mid), "{bad}: still isolated"); + } + + // A parent layer hidden while its sublayer is isolated isn't isolated: the call leaves. + s.execute("object.isolate", &json!({"id": deep.0})).unwrap(); + s.execute("layer.setProps", &json!({"id": mid.0, "visible": false})).unwrap(); + exit(&mut s, json!({})); + assert_eq!(isolation(&s), None, "hidden parent layer"); + s.execute("layer.setProps", &json!({"id": mid.0, "visible": true})).unwrap(); + + sel(&mut s, &[a, b]); + let g = id_of(&s.execute("object.group", &json!({})).unwrap()); + s.execute("object.isolate", &json!({"id": g.0})).unwrap(); + exit(&mut s, json!({})); + assert_eq!((isolation(&s), selected(&s)), (None, vec![g]), "a group in a sublayer"); +} + /// Undo and Redo bring back a selection without the guides, ruler guides or guide paths, that /// Lock Guides has locked since, so a move after them leaves the guides where they are. #[test] diff --git a/crates/tools/src/direct.rs b/crates/tools/src/direct.rs index 6586cb8586..f9f28eeec0 100644 --- a/crates/tools/src/direct.rs +++ b/crates/tools/src/direct.rs @@ -1348,7 +1348,7 @@ impl DirectSelectionTool { if hit.as_ref().and_then(|h| cx.doc.node(h.leaf)).is_some_and(|n| matches!(n.kind, NodeKind::Text(_))) { return vec![Action::SwitchTool("type".into())]; } - // Outside the isolated art it leaves isolation mode, as with the Selection tool (#4466). + // Outside the isolated art it runs Exit Isolation Mode, as with the Selection tool (#4466). if hit.is_none() && cx.isolation.is_some() { return vec![Action::Exec("object.exitIsolation".into(), json!({}))]; } diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 34d0777c51..fa06ed929c 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -8871,6 +8871,36 @@ fn escape_while_editing_in_isolation_returns_to_selection_tool_and_keeps_isolati assert!(app.session.active().unwrap().isolation.is_none(), "2nd Escape must exit isolation mode"); } +/// One Escape leaves isolation mode from a sublayer two levels down, where Exit Isolation Mode goes +/// up one layer at a time. +#[test] +fn escape_leaves_an_isolated_sublayer_in_one_step() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let top = app.session.active().unwrap().doc.layers[0].id; + let mid = app.session.execute("layer.newSublayer", &json!({"parent": top.0})).unwrap()["id"].as_u64().unwrap(); + let deep = app.session.execute("layer.newSublayer", &json!({"parent": mid})).unwrap()["id"].as_u64().unwrap(); + app.session.execute("layer.setCurrent", &json!({"id": deep})).unwrap(); + app.session.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 40, "height": 20})).unwrap(); + app.session.execute("object.isolate", &json!({"id": deep})).unwrap(); + app.select_tool("selection"); + let ctx = egui::Context::default(); + let timed = |app: &mut VectorcraftApp, time: f64, events: Vec<egui::Event>| { + let screen = egui::Rect::from_min_size(Pos2::ZERO, vec2(800.0, 600.0)); + let mut out = ctx.run_ui(egui::RawInput { screen_rect: Some(screen), time: Some(time), events, ..Default::default() }, |ui| { + crate::shortcuts::handle(app, ui.ctx()); + show(app, ui) + }); + out.textures_delta.clear(); + }; + let esc = |pressed| egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed, repeat: false, modifiers: Default::default() }; + timed(&mut app, 0.0, vec![]); + assert_eq!(app.session.active().unwrap().isolation, Some(vectorcraft_doc::NodeId(deep))); + timed(&mut app, 1.0, vec![esc(true), esc(false)]); + timed(&mut app, 1.1, vec![]); + assert_eq!(app.session.active().unwrap().isolation, None, "one Escape leaves every level"); +} + #[test] fn a_symbol_dropped_on_the_canvas_is_placed_there() { let mut app = VectorcraftApp::new(Session::new(), Default::default()); diff --git a/crates/ui-egui/src/chrome/tabs.rs b/crates/ui-egui/src/chrome/tabs.rs index 9278b8baf3..f88372e75b 100644 --- a/crates/ui-egui/src/chrome/tabs.rs +++ b/crates/ui-egui/src/chrome/tabs.rs @@ -364,8 +364,10 @@ pub fn isolation_bar(app: &mut VectorcraftApp, ui: &mut Ui, area: egui::Rect) { ui.painter().rect_filled(crumb_rect, 3.0, t.hover); } if resp.clicked() { - if crumb.is_layer { - nav_cmd = Some(("object.exitIsolation", json!({}))); + // The top-level layer's crumb leaves isolation mode; a sublayer's or a group's + // crumb isolates that level. + if crumb.is_layer && i == 0 { + nav_cmd = Some(("object.exitIsolation", json!({ "all": true }))); } else if let Some(target) = crumb.id { nav_cmd = Some(("object.isolate", json!({ "id": target.0 }))); } @@ -401,7 +403,8 @@ pub fn isolation_bar(app: &mut VectorcraftApp, ui: &mut Ui, area: egui::Rect) { if bresp.clicked() { pattern_cmd = pattern_cmd.or(pattern_edit.as_ref().map(|_| "object.pattern.done")); if pattern_cmd.is_none() { - // Up one level: the isolated object's parent, or out of isolation mode from a layer. + // Up one level: the isolated object's parent group, or `object.exitIsolation`, which + // goes from an isolated sublayer to its parent layer and otherwise leaves isolation mode. nav_cmd = Some(match ancestry.iter().rev().nth(1).filter(|p| st.doc.node(**p).is_some_and(|n| !n.is_layer())) { Some(parent) => ("object.isolate", json!({ "id": parent.0 })), None => ("object.exitIsolation", json!({})), diff --git a/crates/ui-egui/src/chrome/tests.rs b/crates/ui-egui/src/chrome/tests.rs index 61c67e6a70..ee2225ef10 100644 --- a/crates/ui-egui/src/chrome/tests.rs +++ b/crates/ui-egui/src/chrome/tests.rs @@ -1914,6 +1914,45 @@ fn isolation_bar_navigation_and_back_button_steps_up() { assert_eq!(app.session.active().unwrap().isolation, Some(NodeId(g2))); } +/// With a sublayer isolated, the back arrow goes up one layer at a time and then leaves isolation +/// mode. The top-level layer's crumb leaves isolation mode from any depth, and a parent sublayer's +/// crumb isolates that sublayer. +#[test] +fn isolation_bar_back_button_steps_up_through_sublayers() { + use vectorcraft_doc::NodeId; + let mut app = crate::VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 200})).unwrap(); + let top = app.session.active().unwrap().doc.layers[0].id; + let mid = NodeId(app.run("layer.newSublayer", json!({"parent": top.0, "name": "Sublayer B"})).unwrap()["id"].as_u64().unwrap()); + let deep = NodeId(app.run("layer.newSublayer", json!({"parent": mid.0, "name": "Sublayer C"})).unwrap()["id"].as_u64().unwrap()); + app.run("layer.setCurrent", json!({"id": deep.0})).unwrap(); + app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 30, "height": 20})).unwrap(); + let ctx = isolation_bar_context(); + let click = |app: &mut crate::VectorcraftApp, pos: egui::Pos2| isolation_bar_gesture(app, &ctx, pos, pos); + let back = egui::pos2(15.0, 12.0); + let isolation = |app: &crate::VectorcraftApp| app.session.active().unwrap().isolation; + + app.run("object.isolate", json!({"id": deep.0})).unwrap(); + let steps = app.session.doc().unwrap().history.undo.len(); + click(&mut app, back); + assert_eq!(isolation(&app), Some(mid), "back from the deepest sublayer"); + click(&mut app, back); + assert_eq!(isolation(&app), Some(top), "back from the middle sublayer"); + click(&mut app, back); + assert_eq!(isolation(&app), None, "back from the top-level layer"); + assert_eq!(app.session.doc().unwrap().history.undo.len(), steps, "no undo step"); + + // "Layer 1" is the first crumb, at x 30 to about 75. + app.run("object.isolate", json!({"id": deep.0})).unwrap(); + click(&mut app, egui::pos2(40.0, 12.0)); + assert_eq!(isolation(&app), None, "the top-level layer's crumb"); + + // "Sublayer B" is the second crumb, from about x 95. + app.run("object.isolate", json!({"id": deep.0})).unwrap(); + click(&mut app, egui::pos2(115.0, 12.0)); + assert_eq!(isolation(&app), Some(mid), "the parent sublayer's crumb"); +} + /// Headless frames of the isolation bar over a 1200 × 700 canvas for one pointer gesture: a press /// at `from`, a move to `to` and a release there. `from == to` is a click. fn isolation_bar_gesture(app: &mut crate::VectorcraftApp, ctx: &egui::Context, from: egui::Pos2, to: egui::Pos2) { diff --git a/crates/ui-egui/src/shortcuts.rs b/crates/ui-egui/src/shortcuts.rs index 781bec4e74..56bc5ada08 100644 --- a/crates/ui-egui/src/shortcuts.rs +++ b/crates/ui-egui/src/shortcuts.rs @@ -539,7 +539,8 @@ 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!({})); + // From an isolated sublayer, Escape leaves isolation mode rather than going up one layer. + let _ = app.run("object.exitIsolation", json!({ "all": true })); } 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() { diff --git a/docs/mcp.md b/docs/mcp.md index 4c1b661f42..f6e8b34d4b 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5441,7 +5441,16 @@ and `layerRows`, the rows highlighted in the panel. runs Hide or Lock Others for the row's layer, or Show or Unlock All when the others already are), `layer.pasteRemembersLayers`, `object.isolate {id?}` (a group, a layer or a single object, by default the first selected object; not type, not a hidden or locked object or one in a hidden or locked group or layer, not a guide path while Lock Guides is on, and - while a symbol is edited only the editing layer or art on it) / `object.exitIsolation`. Leaving an isolated Live + while a symbol is edited only the editing layer or art on it) / `object.exitIsolation {all?}`. With a sublayer + isolated, `object.exitIsolation` isolates its parent layer and selects the sublayer, so repeated calls go up one + layer at a time until the top-level layer is left, as the + [help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/select-objects/isolate-objects.html) + describes for Exit Isolation Mode; the Layers panel menu item, the isolation bar's back arrow, the Control bar + button, the canvas context menu and a double-click outside the art run it this way. As VectorCraft's own rules, a + step up records no undo step, a hidden or locked parent layer is not isolated (the call leaves isolation mode), and + `all: true` (Esc, the top-level layer's crumb on the isolation bar) leaves isolation mode from a sublayer at any + depth; `all` must be true or false. While a symbol is edited, a group isolated in its art still goes back to the + symbol's layer first, with or without `all`. A sublayer's crumb on the isolation bar isolates that sublayer. Leaving an isolated Live Paint group (`object.exitIsolation`, or `object.isolate` on a level outside it) adds the paths, compound paths and groups of them drawn in it, shown and unlocked with everything in them, to the group as `livePaint.merge` does, in one undo step; type, images and other objects stay in it as they are, and with nothing drawn no undo step is diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index ef83de54ad..9d65ea3bfa 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1148,6 +1148,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - The canvas context menu has Isolate Selected Path (`object.isolate`) when the selection is one path, a path selected inside a group or a compound path included, as the [help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=324) lists it beside Isolate Selected Group. As VectorCraft's own rule, neither item shows for two or more objects, or for an object `object.isolate` refuses: a hidden or locked object, one in a hidden or locked group or layer, a guide while Lock Guides is on, and, while a symbol is edited, an object outside the symbol's art (`single_path_context_item_enters_isolation`, `isolation_context_item_follows_selected_kind`, `isolation_context_item_skips_objects_that_cannot_be_isolated`). - While an opacity mask is edited, Exit Isolation Mode (Esc, the isolation bar's back arrow, the Control bar's button, and the Layers panel menu's and canvas context menu's Exit Isolation Mode) leaves mask editing as Stop Editing Opacity Mask does, in one undo step: the mask keeps the edits, and the masked object is selected. While a pattern is edited, the Exit Isolation Mode item of the Layers panel menu and of the canvas context menu saves the pattern and leaves pattern editing, as Done does. - A click anywhere on the isolation bar, the isolated object's name included, outside its back arrow, the breadcrumbs of the levels above and its buttons leaves isolation mode altogether, nested isolation included, as Exit Isolation Mode does ([the help page](https://help.adobe.com/archive/en_US/illustrator/cs4/illustrator_cs4_help.pdf#page=207)). As VectorCraft's own rules, the click stops editing an opacity mask, leaves symbol editing mode even while a group inside the symbol's art is isolated, together with the isolation the mode was entered from, and does nothing while a pattern is edited; a drag across the bar does not leave (`isolation_bar_background_click_exits_nested_isolation`). + - With a sublayer isolated, Exit Isolation Mode (the Layers panel menu item, the isolation bar's back arrow, the Control bar button and `object.exitIsolation`) goes back one layer at a time, isolating the parent layer, and leaves isolation mode from the top-level layer, as the [help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/select-objects/isolate-objects.html) and an archived [help page](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=213) describe. As VectorCraft's own rules, Esc and the top-level layer's crumb leave isolation mode from a sublayer at any depth (`object.exitIsolation {all: true}`), a sublayer's crumb isolates that sublayer, a hidden or locked parent layer is not isolated, and a step up records no undo step (`exit_isolation_goes_up_one_layer_from_a_sublayer`, `isolation_bar_back_button_steps_up_through_sublayers`, `escape_leaves_an_isolated_sublayer_in_one_step`). - Numeric spinner arrows keep stepping while held with the mouse past the click timeout and stop on release (#6307; `a_held_spinner_arrow_repeats`). - Object › Vector Halftone keeps the selection box and hides selection marks on the temporary dots during Preview; turning Preview off or cancelling restores the original selection marks (#6369). - Tab shows and hides the panels (in the Type tool it types a tab) without moving the keyboard focus onto a field, so the next shortcut or letter still works; in dialogs and panel fields it moves between fields, one press each — a numeric field's scrub label is not a tab stop of its own, and the Transform panel's, Properties panel's and Control bar's W/H link comes after the fields it sits between (`one_tab_moves_from_a_field_to_the_next`). A field's up/down spinner, the chevron that opens its presets (Stroke Weight, font size, Rotate, Export for Screens' scale) and the Transparency row's opacity slider chevron are not tab stops either. Alt+↓ with no other modifier in a field with presets opens them with the keyboard focus on the chosen one, instead of stepping the field down; Enter picks the focused preset without pressing a dialog's OK, and after a pick or Escape the field has the keyboard focus again (`tab_goes_from_field_to_field_past_the_spinner_and_the_preset_chevron`, `tab_goes_from_the_opacity_field_past_its_slider_chevron`, `alt_down_opens_a_fields_presets_for_the_keyboard`, `escape_closes_a_fields_presets_and_returns_to_the_field`). From 1aef05110bc05f16fd3526eb0aab8550556145bc Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 17 Nov 2026 15:37:54 -0800 Subject: [PATCH 148/176] SVG export: type is laid out once for its live, on-path, outline and character-stroke writers SVG export lays out each type object once and hands that layout to the writer for live text, type on a path, outlines and inside or outside character strokes, where each of them laid the same type out again. Type on a path, bidirectional type and type that falls back to outlines go from two layouts to one; inside or outside character strokes and the object's own fills go from up to four to one. The outline and character-stroke writers also group glyphs by run in one pass instead of filtering every glyph for each run. The written SVG, warnings and notes are unchanged. A test compares the export with each writer laying the type out on its own over 17 kinds of type and checks the layout counts; an ignored test times a large document. --- crates/svg/src/export/text.rs | 137 ++++++++++++------- crates/svg/src/export/text/tests.rs | 201 ++++++++++++++++++++++++++++ docs/target-app-parity.md | 1 + 3 files changed, 292 insertions(+), 47 deletions(-) diff --git a/crates/svg/src/export/text.rs b/crates/svg/src/export/text.rs index 8a808b5f72..f8bc712117 100644 --- a/crates/svg/src/export/text.rs +++ b/crates/svg/src/export/text.rs @@ -103,20 +103,23 @@ impl Writer<'_> { || t.stacks_warichu() || (inline && matches!(t.kind, TextKind::OnPath { .. })) || unwritable; - let chars = |w: &mut Self, n: &Node| if outlined { w.text_outlines(n, t) } else { w.text(n, t) }; + // Every writer below draws this one layout of the type. + let db = vectorcraft_text::FontDb::global(); + let lay = vectorcraft_text::layout(db, t); + let chars = |w: &mut Self, n: &Node| if outlined { w.text_outlines(n, t, &lay) } else { w.text(n, t, &lay) }; let painted = n.appearance.items.iter().any(|i| i.visible() && !i.paint().is_none()); // Live type with an inside or outside character stroke writes that stroke apart from the // text, in the group. let apart = !outlined && t.runs.iter().any(|r| aligned(&r.style)); if !painted && !inline && !apart { + #[cfg(test)] + DRAW_HANDED.with(|d| d.set(true)); return chars(self, n); } let id = self.id_attr(n); let a = self.attrs(&css::transparency(n)); self.line(&format!("<g{id}{a}>")); self.depth += 1; - let db = vectorcraft_text::FontDb::global(); - let lay = vectorcraft_text::layout(db, t); let mut all = lay.to_bezpath(); for (_, bar) in vectorcraft_text::decorations(&lay, db, t) { all.extend(bar.iter()); @@ -154,14 +157,22 @@ impl Writer<'_> { } /// Text as glyph outlines: one compound path per run, painted like the run (gradients span - /// the whole text), over its colour glyphs, as on the canvas. - fn text_outlines(&mut self, n: &Node, t: &TextObject) { + /// the whole text), over its colour glyphs, as on the canvas. `lay` is the layout of `t`. + fn text_outlines(&mut self, n: &Node, t: &TextObject, lay: &vectorcraft_text::TextLayout) { + let mut again = None; + let lay = handed(t, lay, &mut again); let db = vectorcraft_text::FontDb::global(); - let lay = vectorcraft_text::layout(db, t); let mut runs = vec![kurbo::BezPath::new(); t.runs.len()]; + // Each run's glyphs, in layout order. + let mut run_glyphs = vec![Vec::new(); t.runs.len()]; + for g in &lay.glyphs { + if let Some(gs) = run_glyphs.get_mut(g.run) { + gs.push(g); + } + } // Underline and strikethrough bars join their run's outlines; ruby glyphs are painted // with the run of the text they annotate. - let bars = vectorcraft_text::decorations(&lay, db, t); + let bars = vectorcraft_text::decorations(lay, db, t); for (run, outline) in lay .glyphs .iter() @@ -197,10 +208,10 @@ impl Writer<'_> { // The glyphs stay in text space; the text's transform joins the document's meanwhile. let saved = self.xf; self.xf = saved * t.xf; - for (i, (bp, run)) in runs.iter().zip(&t.runs).enumerate() { + for ((bp, run), glyphs) in runs.iter().zip(&t.runs).zip(&run_glyphs) { // Colour glyphs paint themselves, under their run's paint: bitmap glyphs (emoji) as // their images, COLR and SVG glyphs as their art. - for g in lay.glyphs.iter().filter(|g| g.run == i) { + for g in glyphs { if let Some((image, to_text)) = g.placed_image() { let m = self.matrix(self.xf * to_text); let href = self.blob_href(&image.blob); @@ -233,40 +244,42 @@ impl Writer<'_> { /// spacing come out as on the canvas. Centred and right-aligned lines are anchored /// (`text-anchor`) at their centre or right end, so they stay aligned in a viewer whose font /// differs; other lines are placed where each style run (and, justified, each word) starts. - fn text(&mut self, n: &Node, t: &TextObject) { + /// `lay` is the layout of `t`. + fn text(&mut self, n: &Node, t: &TextObject, lay: &vectorcraft_text::TextLayout) { // Live SVG text is written in logical order from left-aligned pieces: bidirectional text // (and right-to-left paragraphs) keep their look as outlines until it is written with // `direction`/`unicode-bidi`. So do runs set Right to Left (Character Direction), whose // `direction="rtl"` would anchor their pieces at the right end. - let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t); + let mut again = None; + let lay = handed(t, lay, &mut again); let rtl_runs = t.runs.iter().any(|r| r.style.char_direction == Some(vectorcraft_doc::ParaDirection::RightToLeft)); if lay.glyphs.iter().any(|g| g.rtl) || lay.lines.iter().any(|l| l.rtl) || rtl_runs { self.warn("bidirectional text is outlined to preserve shaping and visual order"); - return self.text_outlines(n, t); + return self.text_outlines(n, t, lay); } if let TextKind::OnPath { path, start, end } = &t.kind { // A reader lays a `<textPath>`'s glyphs straight: joined glyphs bent along the path // keep their look as outlines. if lay.glyphs.iter().any(|g| g.bend.is_some()) { self.warn("joined type bent along a path is outlined to keep its look"); - return self.text_outlines(n, t); + return self.text_outlines(n, t, lay); } // `<textPath>` has a start offset only: an end bracket, Align to Path and Spacing // keep their look as outlines. if end.is_some() || t.path_align != vectorcraft_doc::PathAlign::Baseline || t.path_spacing != 0.0 { self.warn("type on a path with an end bracket, Align to Path or Spacing is outlined to keep its look"); - return self.text_outlines(n, t); + return self.text_outlines(n, t, lay); } // A reader turns each `<textPath>` glyph with the path, as Rainbow does: Skew, 3D // Ribbon, Stair Step and Gravity keep their look as outlines. if t.path_effect != vectorcraft_doc::PathEffect::Rainbow { self.warn("type on a path with an effect other than Rainbow is outlined to keep its look"); - return self.text_outlines(n, t); + return self.text_outlines(n, t, lay); } // It cannot hang glyphs outside the start bracket either. - if hangs_on_path(t, &lay) { + if hangs_on_path(t, lay) { self.warn("type on a path with glyphs hanging outside its brackets is outlined to keep its look"); - return self.text_outlines(n, t); + return self.text_outlines(n, t, lay); } // The space before the first character is written as its `dx`; one before a character // after a line break, which the `<textPath>` writes as a space, keeps its look as outlines. @@ -279,39 +292,39 @@ impl Writer<'_> { }); if spaced_break { self.warn("type on a path with space before a character after a line break is outlined to keep its look"); - return self.text_outlines(n, t); + return self.text_outlines(n, t, lay); } // A `<textPath>` places its characters one after the other: Insert Aki keeps its look as // outlines. if t.runs.iter().any(|r| r.style.aki_left != 0.0 || r.style.aki_right != 0.0) { self.warn("type on a path with Insert Aki is outlined to keep its look"); - return self.text_outlines(n, t); + return self.text_outlines(n, t, lay); } // Tsume does as well. if t.runs.iter().any(|r| r.style.tsume != 0.0) { self.warn("type on a path with Tsume is outlined to keep its look"); - return self.text_outlines(n, t); + return self.text_outlines(n, t, lay); } // Justification…'s Desired word and letter spacing and glyph scaling do too. if (0..t.paragraph_count()).any(|i| !t.layout_justification(t.para_at(i)).desired_is_default()) { self.warn("type on a path with Justification spacing or glyph scaling is outlined to keep its look"); - return self.text_outlines(n, t); + return self.text_outlines(n, t, lay); } // A `<textPath>` holds the characters of the text, not the bullets or numbers drawn // before them. if !lay.markers.is_empty() { self.warn("type on a path with bullets or numbers is outlined to keep its look"); - return self.text_outlines(n, t); + return self.text_outlines(n, t, lay); } // Nor the character a repeat mark is drawn as in the mark's width (Kurikaeshi Moji Shori). if !lay.repeat_marks.is_empty() { self.warn("type on a path that starts with a repeat mark drawn as the character it repeats is outlined to keep its look"); - return self.text_outlines(n, t); + return self.text_outlines(n, t, lay); } - return self.text_on_path(n, t, path, *start); + return self.text_on_path(n, t, lay, path, *start); } - self.note_fonts(t, &lay); - let lines = text_lines(t, &lay, self.opts.fewer_tspans); + self.note_fonts(t, lay); + let lines = text_lines(t, lay, self.opts.fewer_tspans); // `drawn` holds the styles the layout draws the text in: Shrink Text to Fit scales its sizes, explicit leading and baseline shifts. let fitted = (lay.fit_scale != 1.0).then(|| vectorcraft_text::scaled(t, lay.fit_scale)); let drawn = fitted.as_ref().unwrap_or(t); @@ -374,35 +387,36 @@ impl Writer<'_> { } s.push_str("</text>"); self.line(&s); - self.aligned_char_strokes(t); + self.aligned_char_strokes(t, lay); } - /// The inside and outside character strokes of live type `t`, over its text (which goes - /// without them, see [`Self::char_props`]): each such run's stroke on its glyph outlines, drawn - /// twice as wide and clipped or masked to its side as aligned path strokes are + /// The inside and outside character strokes of live type `t`, laid out as `lay`, over its text + /// (which goes without them, see [`Self::char_props`]): each such run's stroke on its glyph + /// outlines, drawn twice as wide and clipped or masked to its side as aligned path strokes are /// ([`Self::side_attr`]). The text stays live; only the stroke follows the outlines. - fn aligned_char_strokes(&mut self, t: &TextObject) { + fn aligned_char_strokes(&mut self, t: &TextObject, lay: &vectorcraft_text::TextLayout) { if !t.runs.iter().any(|r| aligned(&r.style)) { return; } + let mut again = None; + let lay = handed(t, lay, &mut again); let db = vectorcraft_text::FontDb::global(); - let lay = vectorcraft_text::layout(db, t); - let bars = vectorcraft_text::decorations(&lay, db, t); + let bars = vectorcraft_text::decorations(lay, db, t); + // Each such run's glyph outlines and then its bars, in layout order. + let mut outlines = vec![BezPath::new(); t.runs.len()]; + for (run, outline) in lay.glyphs.iter().map(|g| (g.run, &g.outline)).chain(bars.iter().map(|(r, b)| (*r, b))) { + if let Some(bp) = outlines.get_mut(run).filter(|_| t.runs.get(run).is_some_and(|r| aligned(&r.style))) { + bp.extend(outline.iter()); + } + } // The glyphs stay in text space; the text's transform joins the document's meanwhile. let saved = self.xf; self.xf = saved * t.xf; - for (i, run) in t.runs.iter().enumerate().filter(|(_, r)| aligned(&r.style)) { - let mut bp = BezPath::new(); - for g in lay.glyphs.iter().filter(|g| g.run == i) { - bp.extend(g.outline.iter()); - } - for (_, bar) in bars.iter().filter(|(r, _)| *r == i) { - bp.extend(bar.iter()); - } + for (run, bp) in t.runs.iter().zip(&outlines).filter(|(r, _)| aligned(&r.style)) { if bp.elements().is_empty() { continue; } - let pd = PathData::from_bezpath(&bp); + let pd = PathData::from_bezpath(bp); let ap = vectorcraft_doc::Appearance { items: vec![AppearanceItem::Stroke(run.style.stroke_layer())], ..Default::default() }; let d = self.path_d(&pd, self.xf); self.shape(&Node::path(NodeId(u64::MAX), pd.clone(), ap), &d, None, &[&pd], FillRule::NonZero, Some(lay.bounds)); @@ -574,15 +588,16 @@ impl Writer<'_> { rules } - /// Type on a path: a `<textPath>` along the path (a def). - fn text_on_path(&mut self, n: &Node, t: &TextObject, path: &PathData, start: f64) { + /// Type on a path, laid out as `lay`: a `<textPath>` along the path (a def). + fn text_on_path(&mut self, n: &Node, t: &TextObject, lay: &vectorcraft_text::TextLayout, path: &PathData, start: f64) { let id = self.id_attr(n); let pid = self.fresh_id("text-path"); let d = self.path_d(path, self.xf * t.xf); self.def(1, &format!("<path id=\"{pid}\" d=\"{d}\"/>")); // The <text> element's user space is the document's; gradients span the laid-out text. - let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t); - self.note_fonts(t, &lay); + let mut again = None; + let lay = handed(t, lay, &mut again); + self.note_fonts(t, lay); // The styles the layout draws the text in: Dynamic Text scales its sizes, leading and baseline shifts. let fitted = (lay.fit_scale != 1.0).then(|| vectorcraft_text::scaled(t, lay.fit_scale)); let drawn = fitted.as_ref().unwrap_or(t); @@ -626,7 +641,7 @@ impl Writer<'_> { } s.push_str("</textPath></text>"); self.line(&s); - self.aligned_char_strokes(t); + self.aligned_char_strokes(t, lay); } } @@ -635,6 +650,34 @@ fn aligned(st: &CharStyle) -> bool { st.has_stroke() && st.stroke_align != StrokeAlign::Center } +#[cfg(test)] +thread_local! { + /// Tests: each type writer lays `t` out again ([`handed`]) instead of drawing the layout it is + /// handed, so a test can compare the two. The first writer of type written without a group + /// still draws the layout it is handed ([`DRAW_HANDED`]), so each object is laid out where it + /// is drawn. + static LAY_OUT_AGAIN: std::cell::Cell<bool> = const { std::cell::Cell::new(false) }; + /// Tests: the next type writer draws the layout it is handed, with [`LAY_OUT_AGAIN`] too. + static DRAW_HANDED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) }; +} + +/// The layout a type writer draws: `lay`, the layout of `t` it is handed. In tests that ask for it, +/// `t` laid out again, kept in `again`. +fn handed<'a>( + t: &TextObject, + lay: &'a vectorcraft_text::TextLayout, + again: &'a mut Option<vectorcraft_text::TextLayout>, +) -> &'a vectorcraft_text::TextLayout { + #[cfg(test)] + let lay = { + let draw_handed = DRAW_HANDED.with(|d| d.replace(false)); + if LAY_OUT_AGAIN.with(std::cell::Cell::get) && !draw_handed { &*again.insert(vectorcraft_text::layout(FontDb::global(), t)) } else { lay } + }; + #[cfg(not(test))] + let _ = (t, again); + lay +} + /// Does type on a path `t`, laid out as `lay`, hang glyphs outside its brackets? It does when /// Optical Margin Alignment or its first paragraph's Roman Hanging Punctuation is on and its /// glyphs sit elsewhere with both off. diff --git a/crates/svg/src/export/text/tests.rs b/crates/svg/src/export/text/tests.rs index 951817c2c5..6b2fcbfb1f 100644 --- a/crates/svg/src/export/text/tests.rs +++ b/crates/svg/src/export/text/tests.rs @@ -1,5 +1,7 @@ //! The advances a reader gives live type ([`reader_advances`]): the same as when the type is laid //! out again each time, which happens only when a reader sets the type differently from its layout. +//! The type writers draw one layout of the type ([`handed`]) and write what laying it out in each +//! writer writes. use super::*; use vectorcraft_doc::text::{Bullet, ParaList}; @@ -145,3 +147,202 @@ fn a_mixed_document_lays_out_again_only_the_japanese_type() { let (svg, again) = export_layouts_again(vec![point("Latin"), point("「かな」。"), point(""), point("Ab2")]); assert_eq!(again, 1, "{svg}"); } + +/// Type `t`, with the object's own fills and strokes `items`, alone in a document. +fn doc_of(t: TextObject, items: Vec<AppearanceItem>) -> Document { + let mut d = Document::new(300.0, 200.0); + let mut n = Node::new(d.alloc_id(), NodeKind::Text(Box::new(t))); + n.appearance.items = items; + let l = d.layers[0].id; + d.insert(Some(l), 0, n).unwrap(); + d +} + +/// Type on a straight path across the page. +fn on_path(text: &str, st: CharStyle) -> TextObject { + let mut t = TextObject::point(Point::ZERO, text, st); + let mut line = BezPath::new(); + line.move_to((20.0, 100.0)); + line.line_to((280.0, 100.0)); + t.kind = TextKind::OnPath { path: PathData::from_bezpath(&line), start: 0.0, end: None }; + t +} + +/// A character style with a stroke on side `align`. +fn stroked(align: StrokeAlign) -> CharStyle { + CharStyle { stroke: Paint::solid(vectorcraft_color::Color::rgb8(200, 0, 0)), stroke_width: 2.0, stroke_align: align, ..style() } +} + +fn red_fill() -> Vec<AppearanceItem> { + vec![AppearanceItem::Fill(vectorcraft_doc::FillLayer::new(Paint::solid(vectorcraft_color::Color::rgb8(255, 0, 0))))] +} + +/// The type the writers handle differently, each with how many times its export lays the type +/// out: once, plus the layout of the copy that checks for hanging glyphs on a path; and how many +/// times with each writer laying the type out on its own ([`LAY_OUT_AGAIN`]). +fn writer_cases() -> Vec<(&'static str, Document, crate::ExportOptions, u64, u64)> { + let opts = crate::ExportOptions::default; + let outlined = || crate::ExportOptions { outline_text: true, ..crate::ExportOptions::default() }; + let mut runs = point("Red "); + runs.runs.push(TextRun::new("green ", CharStyle { underline: true, ..stroked(StrokeAlign::Outside) })); + runs.runs.push(TextRun::new("blue", CharStyle { strikethrough: true, ..style() })); + let mut many = point(""); + many.runs = (0..200).map(|i| TextRun::new(if i % 7 == 6 { " " } else { "x" }, CharStyle { size: 8.0 + f64::from(i % 5), ..style() })).collect(); + let mut rtl_run = point("abc"); + rtl_run.runs[0].style.char_direction = Some(vectorcraft_doc::ParaDirection::RightToLeft); + let mut skewed = on_path("Skewed", style()); + skewed.path_effect = vectorcraft_doc::PathEffect::Skew; + let mut hanging = on_path("\u{201C}Quoted.\u{201D}", style()); + hanging.optical_margin = true; + let mut inside = point("Inside out"); + inside.runs.push(TextRun::new(" plain", style())); + inside.runs[0].style = CharStyle { underline: true, ..stroked(StrokeAlign::Inside) }; + let outside = TextObject::point(Point::new(20.0, 20.0), "Outside", stroked(StrokeAlign::Outside)); + vec![ + ("point type", doc_of(point("Plain type"), vec![]), opts(), 1, 1), + ("point type with a fill", doc_of(point("Filled type"), red_fill()), opts(), 1, 2), + ("type on a path", doc_of(on_path("Type on a path", style()), vec![]), opts(), 1, 2), + ("type on a path with a fill", doc_of(on_path("Filled path type", style()), red_fill()), opts(), 1, 3), + ("bidirectional type", doc_of(point("abc \u{5D0}\u{5D1}\u{5D2} def"), vec![]), opts(), 1, 2), + ("a run set right to left", doc_of(rtl_run, vec![]), opts(), 1, 2), + ("bidirectional type on a path", doc_of(on_path("abc \u{5D0}\u{5D1}\u{5D2}", style()), vec![]), opts(), 1, 2), + ("type on a path with Skew", doc_of(skewed, vec![]), opts(), 1, 2), + ("type on a path that may hang", doc_of(hanging, vec![]), opts(), 2, 3), + ("outside character stroke", doc_of(outside, vec![]), opts(), 1, 3), + ("inside character stroke", doc_of(inside, vec![]), opts(), 1, 3), + ("runs with a stroke and decorations", doc_of(runs.clone(), vec![]), opts(), 1, 3), + ("runs as outlines", doc_of(runs.clone(), vec![]), outlined(), 1, 1), + ("outside stroke on a path with a fill", doc_of(on_path("Stroked", stroked(StrokeAlign::Outside)), red_fill()), opts(), 1, 4), + ("inside stroke on a path", doc_of(on_path("Stroked", stroked(StrokeAlign::Inside)), vec![]), opts(), 1, 4), + ("many runs as outlines", doc_of(many.clone(), vec![]), outlined(), 1, 1), + ("many runs", doc_of(many, vec![]), opts(), 1, 1), + ] +} + +/// SVG export of `d` with each type writer laying the type out again (`again`) or drawing the +/// layout it is handed, and how many times the export laid type out. +fn export_counting(d: &Document, opts: &crate::ExportOptions, again: bool) -> (crate::Output, u64) { + LAY_OUT_AGAIN.with(|a| a.set(again)); + let before = vectorcraft_text::test_fonts::layouts_on_this_thread(); + let out = crate::export_full(d, opts, None); + let laid = vectorcraft_text::test_fonts::layouts_on_this_thread() - before; + LAY_OUT_AGAIN.with(|a| a.set(false)); + (out, laid) +} + +#[test] +fn every_type_writer_draws_one_layout() { + for (name, d, opts, layouts, own_layouts) in writer_cases() { + let (out, laid) = export_counting(&d, &opts, false); + assert_eq!(laid, layouts, "{name}: {}", out.svg); + // The same file and warnings as each writer laying the type out on its own. + let (again, laid_again) = export_counting(&d, &opts, true); + assert_eq!(laid_again, own_layouts, "{name}"); + assert_eq!(out.svg, again.svg, "{name}"); + assert_eq!(out.warnings, again.warnings, "{name}"); + assert_eq!(out.setting_notes, again.setting_notes, "{name}"); + } +} + +/// The CPU time this thread has run, from Linux's scheduler statistics; wall time elsewhere. +fn thread_time(start: std::time::Instant) -> std::time::Duration { + std::fs::read_to_string("/proc/thread-self/schedstat") + .ok() + .and_then(|s| s.split_whitespace().next()?.parse().ok()) + .map_or_else(|| start.elapsed(), std::time::Duration::from_nanos) +} + +fn median(mut v: Vec<std::time::Duration>) -> std::time::Duration { + v.sort(); + v[v.len() / 2] +} + +/// Timing, not a check: SVG export of a large document with each writer laying the type out again +/// and with one layout handed to them, alternating, seven runs each; and grouping the glyphs of +/// type with 1,000 runs by run, one filter per run against one pass. Run with +/// `cargo test --release -p vectorcraft-svg --lib svg_type_layout_timing -- --ignored --nocapture`. +#[test] +#[ignore = "timing"] +fn svg_type_layout_timing() { + let mut d = Document::new(2000.0, 2000.0); + let l = d.layers[0].id; + let add = |d: &mut Document, t: TextObject, items: Vec<AppearanceItem>| { + let mut n = Node::new(d.alloc_id(), NodeKind::Text(Box::new(t))); + n.appearance.items = items; + d.insert(Some(l), usize::MAX, n).unwrap(); + }; + let words: String = "Type set along a path for timing. ".chars().cycle().take(60).collect(); + for _ in 0..1000 { + add(&mut d, on_path(&words, style()), vec![]); + } + let hebrew = "abc \u{5D0}\u{5D1}\u{5D2}\u{5D3} def ".repeat(6); + for _ in 0..1000 { + add(&mut d, point(&hebrew.chars().take(80).collect::<String>()), vec![]); + } + for _ in 0..300 { + add(&mut d, TextObject::point(Point::new(20.0, 20.0), "Stroked outside", stroked(StrokeAlign::Outside)), vec![]); + } + let mut runs = point(""); + runs.runs = (0..1000).map(|i| TextRun::new(if i % 9 == 8 { " " } else { "x" }, CharStyle { size: 8.0 + f64::from(i % 3), ..style() })).collect(); + let mut outlined = Document::new(2000.0, 2000.0); + let ol = outlined.layers[0].id; + for _ in 0..300 { + let n = Node::new(outlined.alloc_id(), NodeKind::Text(Box::new(runs.clone()))); + outlined.insert(Some(ol), usize::MAX, n).unwrap(); + } + let docs = [ + ("1,000 on a path, 1,000 bidirectional, 300 outside strokes", &d, crate::ExportOptions::default()), + ("300 texts of 1,000 runs as outlines", &outlined, crate::ExportOptions { outline_text: true, ..crate::ExportOptions::default() }), + ]; + for (name, doc, opts) in docs { + let (one, again) = (export_counting(doc, &opts, false), export_counting(doc, &opts, true)); + assert_eq!(one.0.svg, again.0.svg, "{name}"); + let (mut base, mut handed) = (vec![], vec![]); + for _ in 0..7 { + for (again, times) in [(true, &mut base), (false, &mut handed)] { + let start = std::time::Instant::now(); + let t0 = thread_time(start); + let _ = export_counting(doc, &opts, again); + times.push(thread_time(start) - t0); + } + } + let (from, to, base_median, handed_median) = (again.1, one.1, median(base.clone()), median(handed.clone())); + println!( + "{name}: layouts {from} -> {to}; laid out again {base:?} (median {base_median:?}); one layout {handed:?} (median {handed_median:?})" + ); + } + // The glyphs of one 1,000-run text, grouped by run 300 times. + let lay = vectorcraft_text::layout(FontDb::global(), &runs); + let (mut filtered, mut bucketed) = (vec![], vec![]); + for _ in 0..7 { + let start = std::time::Instant::now(); + let t0 = thread_time(start); + for _ in 0..300 { + for i in 0..runs.runs.len() { + for g in lay.glyphs.iter().filter(|g| g.run == i) { + std::hint::black_box(g); + } + } + } + filtered.push(thread_time(start) - t0); + let start = std::time::Instant::now(); + let t0 = thread_time(start); + for _ in 0..300 { + let mut run_glyphs = vec![Vec::new(); runs.runs.len()]; + for g in &lay.glyphs { + if let Some(gs) = run_glyphs.get_mut(g.run) { + gs.push(g); + } + } + for g in run_glyphs.iter().flatten() { + std::hint::black_box(g); + } + } + bucketed.push(thread_time(start) - t0); + } + println!( + "grouping 300 texts of 1,000 runs: filter per run {filtered:?} (median {:?}); one pass {bucketed:?} (median {:?})", + median(filtered.clone()), + median(bucketed.clone()) + ); +} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index ef83de54ad..45bbff0c80 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1973,6 +1973,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur `.ai` and EPS editing-data import reads a text document whose keys are written by name, as files saved for version 11 write them, and the keys that later files write by name among the numbered ones (a font record's version, a paragraph's direction). The type of such a file comes from its text document, so type outside the artboards opens and each text object keeps its own story A run that names its paragraph or character style by the style's number takes that style (`a_text_document_with_named_keys_gives_type_off_the_page_too`, `a_text_document_with_named_keys_takes_a_runs_style_by_its_number`, `crates/eps/src/import/ate/names.rs`). In SVG export without Fewer `<tspan>` Elements, each character of live type that justification or Mojikumi moves (the letter gaps of a Justify All line without word spaces, the gaps between the characters of a justified Japanese line, closed-up punctuation, the space between Japanese and Latin letters) starts its own positioned `<tspan>`, and type scaled horizontally on a justified line is stretched to its own width (`crates/svg/tests/it/text_layout.rs`). To find those characters, SVG export lays a type object out a second time only when the second layout can differ from the first: point type with Line-end Punctuation Half Width and no Japanese punctuation or letters, the setting new type gets, is laid out once. Exporting 5,000 such objects takes a median of 109.4 ms instead of 171.5 ms on Windows 11, with the same SVG (`crates/svg/src/export/text/tests.rs`). + SVG export lays each type object out once and draws that layout in all of its writers (live text, type on a path, outlines, and inside or outside character strokes), and groups the glyphs of type written as outlines or with such strokes by run in one pass, with the same SVG. Exporting 1,000 objects of type on a path, 1,000 of bidirectional type and 300 with an outside character stroke lays type out 2,300 times instead of 4,900 and takes a median of 665 ms of CPU time instead of 893 ms over seven runs each, alternating, on Linux; grouping the glyphs of 300 texts of 1,000 runs by run takes 10 ms instead of 190 ms (`crates/svg/src/export/text/tests.rs`). SVG export (live text), legacy `.ai` saves (text objects), DXF export (`TEXT` entities) and the CSS Properties panel write area type that Shrink Text to Fit scales down at the size it draws at, and scale its tracking, kerning, leading and baseline shifts the same way where the format holds them. Legacy `.ai` saves (version 7) write type with rotated characters (Character Rotation, Touch Type turns) as its outlines, with a warning that it is no longer editable text (unless `outlineText` already asks for every type object as outlines): a version 7 text object has no character rotation ([Adobe Illustrator File Format Specification 7.0](https://www.nationalarchives.gov.uk/PRONOM/fmt/423), §15), and the outlines keep each character's rotation, baseline shift and scale (`legacy_ai::tests::type_with_rotated_characters_is_outlines_that_keep_the_rotation`). Legacy `.ai` type keeps its manual kerning pairs (`Tk`, `TK`), its discretionary hyphens (`T+`, `T-`) as soft hyphens and its hyphenation language (`XL`) when it opens, and legacy `.ai` saves write manual kerning as `Tk` and soft hyphens as `T+` ([file format specification, version 7](https://web.archive.org/web/20050126105313/https://partners.adobe.com/public/developer/en/illustrator/sdk/AI7FileFormat.pdf), §15.4.6.1, §15.4.10.1 and §22.6). A file whose type sets a line breaking value (`TG`) or Japanese layout rules (`Xu`, `Tu`), which VectorCraft doesn't keep, opens with a warning for each (`import::ai::tests::legacy_manual_pair_kerning_is_kept`, `legacy_line_breaking_and_japanese_layout_rules_are_warned_once`, `legacy_ai::tests::manual_kerning_and_soft_hyphens_are_written_and_read_back`). From 70e10dd553d040c9a258b6c61008574b1dff6560 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 17 Nov 2026 15:39:56 -0800 Subject: [PATCH 149/176] Width Point Edit: a discontinuous point shows and edits both sets of side widths Opening Width Point Edit on either half of a discontinuous width point now shows the Incoming and Outgoing side widths, each with Side 1, Side 2, Total Width and its own link. OK sets both halves in one stroke.widthPoint.set and one undo step, and Delete removes both. Single Width Only keeps the incoming or the outgoing widths as one continuous point. A continuous point keeps the one-set layout. stroke.widthPoint.set takes outIndex, outLeft, outRight and single for this. With adjustAdjoining, the nearest point before follows the incoming change and the nearest point after follows the outgoing change, once each. Indices that are not the two halves of one discontinuous point, another t, or another single value are refused without changing the document or its history. Help page: https://helpx.adobe.com/illustrator/using/stroke-object.html describes editing the widths on each side of a discontinuous point in this dialog. The group labels, the adjoining rule and Delete removing both halves are VectorCraft's own. --- crates/engine/src/cmd/distortcmds.rs | 87 +++++++++-- crates/engine/src/tests/widthpoints.rs | 104 +++++++++++++ crates/ui-egui/src/dialogs/width_point.rs | 124 ++++++++++++--- .../ui-egui/src/dialogs/width_point/tests.rs | 143 ++++++++++++++++++ crates/ui-egui/src/i18n/bg.tsv | 6 + crates/ui-egui/src/i18n/bs.tsv | 6 + crates/ui-egui/src/i18n/ca.tsv | 6 + crates/ui-egui/src/i18n/cs.tsv | 6 + crates/ui-egui/src/i18n/da.tsv | 6 + crates/ui-egui/src/i18n/de.tsv | 6 + crates/ui-egui/src/i18n/el.tsv | 6 + crates/ui-egui/src/i18n/es.tsv | 6 + crates/ui-egui/src/i18n/fi.tsv | 6 + crates/ui-egui/src/i18n/fr.tsv | 6 + crates/ui-egui/src/i18n/gu.tsv | 3 + crates/ui-egui/src/i18n/hi.tsv | 6 + crates/ui-egui/src/i18n/hu.tsv | 6 + crates/ui-egui/src/i18n/id.tsv | 6 + crates/ui-egui/src/i18n/it.tsv | 6 + crates/ui-egui/src/i18n/ja.tsv | 6 + crates/ui-egui/src/i18n/ka.tsv | 6 + crates/ui-egui/src/i18n/ko.tsv | 6 + crates/ui-egui/src/i18n/nl.tsv | 6 + crates/ui-egui/src/i18n/pl.tsv | 6 + crates/ui-egui/src/i18n/pt-br.tsv | 6 + crates/ui-egui/src/i18n/ru.tsv | 6 + crates/ui-egui/src/i18n/sv.tsv | 6 + crates/ui-egui/src/i18n/tr.tsv | 6 + crates/ui-egui/src/i18n/uk.tsv | 6 + crates/ui-egui/src/i18n/vi.tsv | 6 + crates/ui-egui/src/i18n/zh-hans.tsv | 6 + crates/ui-egui/src/i18n/zh-hant.tsv | 6 + docs/control-protocol.md | 3 + docs/mcp.md | 8 + docs/target-app-parity.md | 1 + 35 files changed, 603 insertions(+), 32 deletions(-) diff --git a/crates/engine/src/cmd/distortcmds.rs b/crates/engine/src/cmd/distortcmds.rs index 1e78f210e6..2e2f672af4 100644 --- a/crates/engine/src/cmd/distortcmds.rs +++ b/crates/engine/src/cmd/distortcmds.rs @@ -16,7 +16,7 @@ use vectorcraft_tools::distort::{PinSet, arap, collect_points, mesh_for, project use super::edit::{duplicate_in, outermost, refuse_symbol_part, selected_roots}; use super::{ CommandSpec, Result, Session, bad, check_numbers, check_switches, cmd, f64_or, f64_req, finite_numbers, has_doc, has_selection, matrix_param, - named_id, named_ids, number_or, object_param, ok, point_indices, point_param, str_param, switch_or, targets, + named_id, named_ids, number_or, object_param, ok, point_indices, point_param, str_param, switch_or, targets, text_param, u64_req, }; use crate::EngineError; @@ -35,7 +35,7 @@ pub fn specs() -> Vec<CommandSpec> { "Width Point", [], None, - "{id, t: 0..1 (fraction of the path length), left, right: side widths in pt, index?: width point to edit or move, adjustAdjoining?: bool (the nearest points either side change their widths in proportion, using the sampled widths for a new point)} → {index}. Without index a point already at t is replaced; a point moved onto another one's t joins it as a discontinuous point (on the side it came from), so the width steps there. Creates a uniform profile first if needed", + "{id, t: 0..1 (fraction of the path length), left, right: side widths in pt, index?: width point to edit or move, adjustAdjoining?: bool (the nearest points either side change their widths in proportion, using the sampled widths for a new point), outIndex?, outLeft, outRight: the outgoing half of the discontinuous point whose incoming half is index, single?: \"incoming\" | \"outgoing\"} → {index}. Without index a point already at t is replaced; a point moved onto another one's t joins it as a discontinuous point (on the side it came from), so the width steps there. With outIndex both halves change in one step and keep their place (t must be theirs); adjustAdjoining then changes the nearest point before from the incoming half and the nearest point after from the outgoing half. single keeps only that half's widths, leaving one continuous point. Creates a uniform profile first if needed", has_doc, width_point_set ), @@ -265,8 +265,9 @@ fn place(points: &mut Vec<(f64, f64, f64)>, mut pt: (f64, f64, f64), from_below: } /// Adjust Adjoining Width Points: point `i` changes from `old` to `new` widths, and the nearest -/// points at other positions either side change in proportion (by the same amount from zero). -fn adjust_adjoining(points: &mut [(f64, f64, f64)], i: usize, old: (f64, f64, f64), new: (f64, f64, f64)) { +/// points at other positions on the sides `sides` names (before, after) change in proportion (by +/// the same amount from zero). +fn adjust_adjoining(points: &mut [(f64, f64, f64)], i: usize, old: (f64, f64, f64), new: (f64, f64, f64), sides: [bool; 2]) { let t = points[i].0; let scale = |v: f64, o: f64, n: f64| { let width = if o > 1e-9 { @@ -284,8 +285,8 @@ fn adjust_adjoining(points: &mut [(f64, f64, f64)], i: usize, old: (f64, f64, f6 }; width.max(0.0) }; - let before = (0..i).rev().find(|j| (points[*j].0 - t).abs() > SAME_T); - let after = (i + 1..points.len()).find(|j| (points[*j].0 - t).abs() > SAME_T); + let before = (0..i).rev().find(|j| (points[*j].0 - t).abs() > SAME_T).filter(|_| sides[0]); + let after = (i + 1..points.len()).find(|j| (points[*j].0 - t).abs() > SAME_T).filter(|_| sides[1]); for j in before.into_iter().chain(after) { let q = &mut points[j]; (q.1, q.2) = (scale(q.1, old.1, new.1), scale(q.2, old.2, new.2)); @@ -303,6 +304,45 @@ fn same_points(a: Option<&WidthProfile>, b: Option<&WidthProfile>) -> bool { } } +/// Set both halves of the discontinuous point whose incoming half is `i` and outgoing half `j` to +/// the widths of `inc` and `out` (their places are ignored: the point keeps its place). With +/// `single` (`true` for the outgoing half) only that half's widths remain, as one continuous point. +/// With `adjust`, the nearest point before changes with the incoming half and the nearest point after +/// with the outgoing half, once each. → the index of the point (its incoming half). +fn set_pair( + points: &mut Vec<(f64, f64, f64)>, + (i, inc): (usize, (f64, f64, f64)), + (j, out): (usize, (f64, f64, f64)), + adjust: bool, + single: Option<bool>, +) -> Result<usize> { + const C: &str = "stroke.widthPoint.set"; + let at = points.get(i).map_or(f64::NAN, |q| q.0); + let halves: Vec<usize> = (0..points.len()).filter(|k| (points[*k].0 - at).abs() <= SAME_T).collect(); + if halves != [i, j] { + return Err(bad(C, "`index` and `outIndex` must be the two halves of one discontinuous width point")); + } + let (old_in, old_out) = (points[i], points[j]); + if (old_in.0 - inc.0).abs() > SAME_T { + return Err(bad(C, "a discontinuous width point keeps its place")); + } + let (new_in, new_out) = match single { + None => ((old_in.0, inc.1, inc.2), (old_out.0, out.1, out.2)), + Some(false) => ((old_in.0, inc.1, inc.2), (old_in.0, inc.1, inc.2)), + Some(true) => ((old_in.0, out.1, out.2), (old_in.0, out.1, out.2)), + }; + if adjust { + adjust_adjoining(points, i, old_in, new_in, [true, false]); + adjust_adjoining(points, j, old_out, new_out, [false, true]); + } + points[i] = new_in; + points[j] = new_out; + if single.is_some() { + points.remove(j); + } + Ok(i) +} + fn width_point_set(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "stroke.widthPoint.set"; let id = object_param(p, "id", C)?.ok_or_else(|| bad(C, "missing id"))?; @@ -312,6 +352,23 @@ fn width_point_set(s: &mut Session, p: &Value) -> Result<Value> { return Err(bad(C, "left/right must be non-negative widths")); } let adjust = switch_or(p, "adjustAdjoining", false, C)?; + let single = match text_param(p, "single", C)? { + None => None, + Some(side @ ("incoming" | "outgoing")) => Some(side == "outgoing"), + Some(_) => return Err(bad(C, "`single` must be `incoming` or `outgoing`")), + }; + // The outgoing half of a discontinuous point: its index and side widths (points). + let out = match p.get("outIndex") { + None | Some(Value::Null) if single.is_none() => None, + _ => { + let j = usize::try_from(u64_req(p, "outIndex", C)?).map_err(|_| bad(C, "no such width point"))?; + let (l, r) = (f64_req(p, "outLeft", C)?, f64_req(p, "outRight", C)?); + if !(l.is_finite() && r.is_finite()) || l < 0.0 || r < 0.0 || l.max(r) > 1.0e5 { + return Err(bad(C, "left/right must be non-negative widths")); + } + Some((j, l, r)) + } + }; // When the profile comes out as it was, within a rounding error (1e-9), the document and its undo // history stay as they are. let mut pos = 0; @@ -324,11 +381,19 @@ fn width_point_set(s: &mut Session, p: &Value) -> Result<Value> { return Err(bad(C, "width factors must be finite")); } let mut prof = st.profile.take().unwrap_or_else(uniform); - pos = match point_index(p, &prof, C)? { - Some(i) => { + pos = match (point_index(p, &prof, C)?, out) { + (None, Some(_)) => return Err(bad(C, "missing index")), + (Some(i), Some((j, l, r))) => { + let out = (t, l / half, r / half); + if !out.1.is_finite() || !out.2.is_finite() { + return Err(bad(C, "width factors must be finite")); + } + set_pair(&mut prof.points, (i, pt), (j, out), adjust, single)? + } + (Some(i), None) => { let old = prof.points[i]; if adjust { - adjust_adjoining(&mut prof.points, i, old, pt); + adjust_adjoining(&mut prof.points, i, old, pt, [true, true]); } if (old.0 - t).abs() <= SAME_T { // Widths only: it keeps its place (and its side of a discontinuous point). @@ -339,12 +404,12 @@ fn width_point_set(s: &mut Session, p: &Value) -> Result<Value> { place(&mut prof.points, pt, old.0 < t) } } - None => { + (None, None) => { let old = adjust.then(|| prof.at(t)); prof.points.retain(|q| (q.0 - t).abs() > SAME_T); let i = place(&mut prof.points, pt, true); if let Some((left, right)) = old { - adjust_adjoining(&mut prof.points, i, (t, left, right), pt); + adjust_adjoining(&mut prof.points, i, (t, left, right), pt, [true, true]); } i } diff --git a/crates/engine/src/tests/widthpoints.rs b/crates/engine/src/tests/widthpoints.rs index 6aa324aa90..68b7099d68 100644 --- a/crates/engine/src/tests/widthpoints.rs +++ b/crates/engine/src/tests/widthpoints.rs @@ -167,6 +167,110 @@ fn adjust_adjoining_scales_the_neighbours() { assert_eq!(points(&s, id), vec![(0.5, 4.0, 1.0)]); } +/// A line with a discontinuous point in the middle: 1× before it, 2× after it. +fn pair_session(points: serde_json::Value) -> (Session, NodeId) { + let (mut s, id) = line_session(); + s.execute("stroke.widthProfile.set", &json!({"ids": [id.0], "points": points})).unwrap(); + s.doc_mut().unwrap().mark_saved(); + (s, id) +} + +#[test] +fn paired_set_edits_both_halves_in_one_step() { + let (mut s, id) = pair_session(json!([[0, 1, 1], [0.5, 1, 1], [0.5, 2, 2], [1, 1, 1]])); + let before = s.doc().unwrap().doc.clone(); + let undo = s.doc().unwrap().history.undo.len(); + let p = json!({"id": id.0, "index": 1, "t": 0.5, "left": 10, "right": 5, "outIndex": 2, "outLeft": 15, "outRight": 20}); + assert_eq!(set(&mut s, p.clone()), 1); + assert_eq!(points(&s, id), vec![(0.0, 1.0, 1.0), (0.5, 2.0, 1.0), (0.5, 3.0, 4.0), (1.0, 1.0, 1.0)]); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1); + let after = s.doc().unwrap().doc.clone(); + // The same widths again change nothing and record no undo step. + set(&mut s, p); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc, before); + s.execute("edit.redo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc, after); +} + +#[test] +fn paired_set_adjusts_the_point_before_and_the_point_after_once_each() { + let (mut s, id) = pair_session(json!([[0, 1, 1], [0.5, 1, 1], [0.5, 2, 2], [1, 1, 1]])); + // The incoming half doubles and the outgoing half halves: the start doubles, the end halves. + set( + &mut s, + json!({"id": id.0, "index": 1, "t": 0.5, "left": 10, "right": 10, "outIndex": 2, "outLeft": 5, "outRight": 5, "adjustAdjoining": true}), + ); + assert_eq!(points(&s, id), vec![(0.0, 2.0, 2.0), (0.5, 2.0, 2.0), (0.5, 1.0, 1.0), (1.0, 0.5, 0.5)]); + // A discontinuous point at the start has only a point after it to adjust. + let (mut s, id) = pair_session(json!([[0, 1, 1], [0, 2, 2], [1, 1, 1]])); + set( + &mut s, + json!({"id": id.0, "index": 0, "t": 0, "left": 10, "right": 10, "outIndex": 1, "outLeft": 20, "outRight": 20, "adjustAdjoining": true}), + ); + assert_eq!(points(&s, id), vec![(0.0, 2.0, 2.0), (0.0, 4.0, 4.0), (1.0, 2.0, 2.0)]); +} + +#[test] +fn single_width_only_leaves_one_continuous_point() { + for (single, kept) in [("incoming", (2.0, 1.0)), ("outgoing", (3.0, 4.0))] { + let (mut s, id) = pair_session(json!([[0, 1, 1], [0.5, 1, 1], [0.5, 2, 2], [1, 1, 1]])); + let before = s.doc().unwrap().doc.clone(); + let undo = s.doc().unwrap().history.undo.len(); + let p = json!({"id": id.0, "index": 1, "t": 0.5, "left": 10, "right": 5, "outIndex": 2, "outLeft": 15, "outRight": 20, "single": single}); + assert_eq!(set(&mut s, p), 1); + assert_eq!(points(&s, id), vec![(0.0, 1.0, 1.0), (0.5, kept.0, kept.1), (1.0, 1.0, 1.0)], "{single}"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1); + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().doc, before); + } + // With Adjust Adjoining, each neighbor follows the change of the half beside it. + let (mut s, id) = pair_session(json!([[0, 1, 1], [0.5, 1, 1], [0.5, 2, 2], [1, 1, 1]])); + let p = json!({"id": id.0, "index": 1, "t": 0.5, "left": 5, "right": 5, "outIndex": 2, "outLeft": 5, "outRight": 5, "single": "incoming", "adjustAdjoining": true}); + set(&mut s, p); + assert_eq!(points(&s, id), vec![(0.0, 1.0, 1.0), (0.5, 1.0, 1.0), (1.0, 0.5, 0.5)]); +} + +#[test] +fn paired_set_refuses_what_is_not_one_discontinuous_point() { + let (mut s, id) = pair_session(json!([[0, 1, 1], [0.25, 1, 1], [0.5, 1, 1], [0.5, 2, 2], [0.75, 3, 3], [0.75, 3, 3], [0.75, 3, 3], [1, 1, 1]])); + let before = s.doc().unwrap().doc.clone(); + let undo = s.doc().unwrap().history.undo.len(); + let pair = |extra: serde_json::Value| { + let mut p = json!({"id": id.0, "index": 2, "t": 0.5, "left": 5, "right": 5, "outIndex": 3, "outLeft": 5, "outRight": 5}); + for (k, v) in extra.as_object().unwrap() { + if v.is_null() { + p.as_object_mut().unwrap().remove(k); + } else { + p[k] = v.clone(); + } + } + p + }; + for p in [ + pair(json!({"index": 1, "t": 0.25, "outIndex": 2})), + pair(json!({"outIndex": 4})), + pair(json!({"index": 3, "outIndex": 2})), + pair(json!({"outIndex": 99})), + pair(json!({"outIndex": "3"})), + pair(json!({"outIndex": -1})), + pair(json!({"t": 0.6})), + pair(json!({"index": 4, "t": 0.75, "outIndex": 5})), + pair(json!({"index": null})), + pair(json!({"outLeft": null})), + pair(json!({"outRight": -1})), + pair(json!({"outLeft": 1.0e6})), + pair(json!({"single": "both"})), + pair(json!({"single": true})), + json!({"id": id.0, "index": 2, "t": 0.5, "left": 5, "right": 5, "single": "incoming"}), + ] { + assert!(s.execute("stroke.widthPoint.set", &p).is_err(), "accepted {p}"); + assert_eq!(s.doc().unwrap().doc, before, "{p}"); + assert_eq!(s.doc().unwrap().history.undo.len(), undo); + } +} + #[test] fn flipping_along_swaps_the_sides_of_a_discontinuous_point() { let (mut s, id) = line_session(); diff --git a/crates/ui-egui/src/dialogs/width_point.rs b/crates/ui-egui/src/dialogs/width_point.rs index afa27c2abf..f0d2cfb158 100644 --- a/crates/ui-egui/src/dialogs/width_point.rs +++ b/crates/ui-egui/src/dialogs/width_point.rs @@ -6,11 +6,20 @@ //! OK runs `stroke.widthPoint.set`; Delete removes an existing point (`stroke.widthPoint.remove`) //! or discards a prospective point without changing the document. //! -//! Fields: `id`, `index` (an existing width point, otherwise null), `t` (its place), `side1`, -//! `side2` (the left and right widths, points), `linked`, `adjustAdjoining`; Delete sets `discard: true` and confirms. +//! On either half of a discontinuous point the dialog shows both sets of side widths, Incoming +//! (before the point along the path) and Outgoing (after it), and Single Width Only keeps one of +//! them as a continuous point. OK sets both halves in one `stroke.widthPoint.set` (one undo step), +//! and Delete removes both halves. +//! +//! Fields: `id`, `index` (an existing width point, otherwise null; the incoming half of a +//! discontinuous point), `t` (its place), `side1`, `side2` (the left and right widths, points), +//! `linked`, `adjustAdjoining`; for a discontinuous point also `outIndex`, `outSide1`, `outSide2`, +//! `outLinked` (the outgoing half) and `single` (`""`, `"incoming"` or `"outgoing"`); Delete sets +//! `discard: true` and confirms. use egui::vec2; use serde_json::{Value, json}; +use vectorcraft_doc::Unit; use vectorcraft_engine::doc::NodeId; use super::swatch_options::{grid, label}; @@ -21,6 +30,10 @@ use crate::{VectorcraftApp, widgets}; /// The dialog kind of Width Point Edit. pub const KIND: &str = "widthPoint"; +/// Width points closer than this (in t) are the two halves of one discontinuous point, as the +/// engine and the Width tool count them. +const SAME_T: f64 = 1e-6; + pub(super) const SPEC: DialogSpec = DialogSpec { heading: |_| tl!("Width Point Edit").into(), body, confirm, discard: Some("Delete"), min_width: 300.0, ..DialogSpec::FORM }; @@ -31,9 +44,21 @@ fn point(app: &VectorcraftApp, id: u64, index: usize) -> Option<(f64, f64, f64)> st.profile.as_ref()?.points.get(index).map(|&(t, l, r)| (t, l * half, r * half)) } +/// The incoming and outgoing halves of the discontinuous point that width point `index` of `id` +/// belongs to, or none when no other point shares its place (or more than one does). +fn halves(app: &VectorcraftApp, id: u64, index: usize) -> Option<(usize, usize)> { + let points = &app.session.active()?.doc.node(NodeId(id))?.appearance.stroke()?.profile.as_ref()?.points; + let t = points.get(index)?.0; + match (0..points.len()).filter(|i| (points[*i].0 - t).abs() <= SAME_T).collect::<Vec<_>>()[..] { + [a, b] => Some((a, b)), + _ => None, + } +} + /// Open Width Point Edit for `index`, or a prospective point at fraction `t` without an index /// (`{id, index?, t?, adjustAdjoining?}`). Opening only samples the stroke: confirmation creates -/// the point. Adjoining adjustment defaults to false. +/// the point. Adjoining adjustment defaults to false. Either half of a discontinuous point opens +/// both. pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> { let id = p.get("id").and_then(Value::as_u64).ok_or("give the path `id`")?; let doc = &app.session.active().ok_or("no document")?.doc; @@ -42,6 +67,8 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> { Some(v) => Some(v.as_u64().and_then(|i| usize::try_from(i).ok()).ok_or("no such width point")?), None => None, }; + let pair = index.and_then(|i| halves(app, id, i)); + let index = pair.map_or(index, |(a, _)| Some(a)); let (t, l, r) = if let Some(index) = index { point(app, id, index).ok_or("no such width point")? } else { @@ -59,45 +86,86 @@ pub fn open(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> { (t, l, r) }; let adjust = p.get("adjustAdjoining").and_then(Value::as_bool).unwrap_or(false); - let fields = json!({"id": id, "index": index, "t": t, "side1": l, "side2": r, "linked": (l - r).abs() < 1e-9, "adjustAdjoining": adjust}); + let mut fields = json!({"id": id, "index": index, "t": t, "side1": l, "side2": r, "linked": (l - r).abs() < 1e-9, "adjustAdjoining": adjust}); + if let Some((_, out)) = pair { + let (_, l, r) = point(app, id, out).ok_or("no such width point")?; + for (key, value) in [ + ("outIndex", json!(out)), + ("outSide1", json!(l)), + ("outSide2", json!(r)), + ("outLinked", json!((l - r).abs() < 1e-9)), + ("single", json!("")), + ] { + fields[key] = value; + } + } app.ui.dialog = Some(Dialog::new(KIND, fields)); Ok(Value::Null) } -fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { - let unit = app.session.stroke_unit(); - let (s1, s2, linked) = (d.f64("side1", 0.0), d.f64("side2", 0.0), d.bool("linked")); - let mut sides = None; +/// Whether the dialog edits a discontinuous point. +fn paired(d: &Dialog) -> bool { + d.fields.get("outIndex").is_some_and(|v| !v.is_null()) +} + +/// One set of side widths: Side 1 with its link, Side 2 and Total Width, kept in the fields `keys` +/// (side 1, side 2, linked) and shown in the number fields `ids`. +fn sides(ui: &mut egui::Ui, d: &mut Dialog, unit: Unit, keys: [&str; 3], ids: [&str; 3]) { + let [k1, k2, kl] = keys; + let (s1, s2, linked) = (d.f64(k1, 0.0), d.f64(k2, 0.0), d.bool(kl)); + let mut new = None; grid(ui, |ui| { label(ui, tl!("Side 1:")); ui.horizontal(|ui| { - if let Some(v) = widgets::num_field(ui, "wp-side1", Some(s1), unit, 90.0) { - sides = Some((v, if linked { v } else { s2 })); + if let Some(v) = widgets::num_field(ui, ids[0], Some(s1), unit, 90.0) { + new = Some((v, if linked { v } else { s2 })); } if widgets::icon_button(ui, if linked { "link" } else { "link-2-off" }, tl!("Keep both sides the same width"), linked, 22.0).clicked() { - d.fields.insert("linked".into(), json!(!linked)); + d.fields.insert(kl.into(), json!(!linked)); if !linked { - sides = Some((s1, s1)); + new = Some((s1, s1)); } } }); ui.end_row(); label(ui, tl!("Side 2:")); - if let Some(v) = widgets::num_field(ui, "wp-side2", Some(s2), unit, 90.0) { - sides = Some((if linked { v } else { s1 }, v)); + if let Some(v) = widgets::num_field(ui, ids[1], Some(s2), unit, 90.0) { + new = Some((if linked { v } else { s1 }, v)); } ui.end_row(); label(ui, tl!("Total Width:")); - if let Some(v) = widgets::num_field(ui, "wp-total", Some(s1 + s2), unit, 90.0) { + if let Some(v) = widgets::num_field(ui, ids[2], Some(s1 + s2), unit, 90.0) { // Both sides in proportion (equal halves from nothing). let k = if s1 + s2 > 1e-9 { v / (s1 + s2) } else { 0.0 }; - sides = Some(if k > 0.0 { (s1 * k, s2 * k) } else { (v / 2.0, v / 2.0) }); + new = Some(if k > 0.0 { (s1 * k, s2 * k) } else { (v / 2.0, v / 2.0) }); } ui.end_row(); }); - if let Some((a, b)) = sides { - d.fields.insert("side1".into(), json!(a.max(0.0))); - d.fields.insert("side2".into(), json!(b.max(0.0))); + if let Some((a, b)) = new { + d.fields.insert(k1.into(), json!(a.max(0.0))); + d.fields.insert(k2.into(), json!(b.max(0.0))); + } +} + +fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { + let unit = app.session.stroke_unit(); + let incoming = (["side1", "side2", "linked"], ["wp-side1", "wp-side2", "wp-total"]); + if paired(d) { + widgets::section_header(ui, tl!("Incoming")); + ui.push_id("wp-incoming", |ui| sides(ui, d, unit, incoming.0, incoming.1)); + widgets::section_header(ui, tl!("Outgoing")); + ui.push_id("wp-outgoing", |ui| sides(ui, d, unit, ["outSide1", "outSide2", "outLinked"], ["wp-out-side1", "wp-out-side2", "wp-out-total"])); + widgets::section_header(ui, tl!("Single Width Only")); + ui.horizontal(|ui| { + let single = d.str("single"); + for (value, text) in [("", tl!("None")), ("incoming", tl!("Incoming")), ("outgoing", tl!("Outgoing"))] { + if widgets::radio(ui, text, single == value, true) { + d.fields.insert("single".into(), json!(value)); + } + } + }); + } else { + sides(ui, d, unit, incoming.0, incoming.1); } ui.add_space(4.0); ui.allocate_ui(vec2(ui.available_width(), 22.0), |ui| { @@ -110,16 +178,30 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> { let (id, index) = (d.fields.get("id").cloned().unwrap_or_default(), d.fields.get("index").cloned().unwrap_or_default()); + let out = d.fields.get("outIndex").filter(|_| paired(d)).cloned(); if d.bool("discard") { if index.is_null() { // Deleting a prospective point discards the dialog; no document point exists yet. app.ui.dialog = None; return Ok(Value::Null); } - return run_and_close(app, "stroke.widthPoint.remove", json!({"id": id, "index": index})); + let p = match out { + Some(out) => json!({"id": id, "indices": [index, out]}), + None => json!({"id": id, "index": index}), + }; + return run_and_close(app, "stroke.widthPoint.remove", p); } let (left, right) = (d.f64("side1", 0.0), d.f64("side2", 0.0)); - let p = json!({"id": id, "index": index, "t": d.f64("t", 0.0), "left": left, "right": right, "adjustAdjoining": d.bool("adjustAdjoining")}); + let mut p = json!({"id": id, "index": index, "t": d.f64("t", 0.0), "left": left, "right": right, "adjustAdjoining": d.bool("adjustAdjoining")}); + if let Some(out) = out { + p["outIndex"] = out; + p["outLeft"] = json!(d.f64("outSide1", 0.0)); + p["outRight"] = json!(d.f64("outSide2", 0.0)); + let single = d.str("single"); + if !single.is_empty() { + p["single"] = json!(single); + } + } run_and_close(app, "stroke.widthPoint.set", p) } diff --git a/crates/ui-egui/src/dialogs/width_point/tests.rs b/crates/ui-egui/src/dialogs/width_point/tests.rs index 4c5b972f12..ab07b971ae 100644 --- a/crates/ui-egui/src/dialogs/width_point/tests.rs +++ b/crates/ui-egui/src/dialogs/width_point/tests.rs @@ -400,3 +400,146 @@ fn new_width_point_checkbox_adjusts_adjoining_in_one_step() { fn new_width_point_checkbox_off_preserves_adjoining() { creation_adjoining_checkbox(false); } + +/// [`app`]'s line with a discontinuous point in the middle: 4 + 4 pt before it, 2 + 6 pt after it. +fn pair_app() -> (VectorcraftApp, u64) { + let (mut app, id) = app(); + app.run("stroke.widthProfile.set", json!({"ids": [id], "points": [[0, 1, 1], [0.5, 0.8, 0.8], [0.5, 0.4, 1.2], [1, 1, 1]]})).unwrap(); + app.session.doc_mut().unwrap().mark_saved(); + (app, id) +} + +fn assert_pair_fields(d: &Dialog) { + assert_eq!((d.fields["index"].clone(), d.fields["outIndex"].clone()), (json!(1), json!(2))); + assert_eq!((d.f64("side1", 0.0), d.f64("side2", 0.0), d.bool("linked")), (4.0, 4.0, true)); + assert_eq!((d.f64("outSide1", 0.0), d.f64("outSide2", 0.0), d.bool("outLinked")), (2.0, 6.0, false)); + assert_eq!(d.str("single"), ""); +} + +#[test] +fn either_half_of_a_discontinuous_point_shows_both_sets_of_side_widths() { + for index in [1, 2] { + let (mut app, id) = pair_app(); + app.run("ui.widthPointEdit", json!({"id": id, "index": index})).unwrap(); + assert_pair_fields(app.ui.dialog.as_ref().unwrap()); + let shown = frame(&mut app); + for s in ["Incoming", "Outgoing", "Single Width Only", "None", "Adjust Adjoining Width Points", "Delete"] { + assert!(shown.iter().any(|t| t == s), "{s} in {shown:?}"); + } + for s in ["Side 1:", "Side 2:", "Total Width:"] { + assert_eq!(shown.iter().filter(|t| *t == s).count(), 2, "{s} in each set: {shown:?}"); + } + } + // Double-clicking the point with the Width tool opens the same two sets. + let (mut app, _) = pair_app(); + let view = app.view_info(); + app.select_tool("width"); + crate::canvas::dispatch(&mut app, &PointerEvent::new(PointerKind::DoubleClick, 200.0, 150.0), view); + assert_pair_fields(app.ui.dialog.as_ref().expect("Width Point Edit opened")); + // A continuous point keeps one set. + let (mut app, id) = pair_app(); + app.run("ui.widthPointEdit", json!({"id": id, "index": 0})).unwrap(); + assert!(app.ui.dialog.as_ref().unwrap().fields.get("outIndex").is_none()); + let shown = frame(&mut app); + assert!(!shown.iter().any(|t| t == "Incoming" || t == "Outgoing"), "{shown:?}"); + assert_eq!(shown.iter().filter(|t| *t == "Side 1:").count(), 1); +} + +#[test] +fn ok_sets_both_halves_of_a_discontinuous_point_in_one_step() { + let (mut app, id) = pair_app(); + let before = app.session.doc().unwrap().doc.clone(); + let history = creation_history(&app); + // Cancel after edits changes nothing. + app.run("ui.widthPointEdit", json!({"id": id, "index": 2})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("outSide1".into(), json!(9)); + super::super::cancel(&mut app); + assert_eq!(app.session.doc().unwrap().doc, before); + assert_eq!(creation_history(&app), history); + app.run("ui.widthPointEdit", json!({"id": id, "index": 2})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + for (key, value) in [("side1", 6), ("side2", 2), ("outSide1", 1), ("outSide2", 3)] { + d.fields.insert(key.into(), json!(value)); + } + super::super::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(points(&app, id), vec![(0.0, 1.0, 1.0), (0.5, 1.2, 0.4), (0.5, 0.2, 0.6), (1.0, 1.0, 1.0)]); + assert_eq!(creation_history(&app), (history.0 + 1, 0, true)); + let after = app.session.doc().unwrap().doc.clone(); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(app.session.doc().unwrap().doc, before); + app.run("edit.redo", json!({})).unwrap(); + assert_eq!(app.session.doc().unwrap().doc, after); + // OK with nothing changed records no undo step. + app.run("ui.widthPointEdit", json!({"id": id, "index": 1})).unwrap(); + super::super::confirm(&mut app).unwrap(); + assert_eq!(creation_history(&app), (history.0 + 1, 0, true)); +} + +#[test] +fn delete_removes_both_halves_of_a_discontinuous_point() { + let (mut app, id) = pair_app(); + let before = app.session.doc().unwrap().doc.clone(); + let history = creation_history(&app); + app.run("ui.widthPointEdit", json!({"id": id, "index": 1})).unwrap(); + app.ui.dialog.as_mut().unwrap().fields.insert("discard".into(), json!(true)); + super::super::confirm(&mut app).unwrap(); + assert_eq!(points(&app, id), vec![(0.0, 1.0, 1.0), (1.0, 1.0, 1.0)]); + assert_eq!(creation_history(&app).0, history.0 + 1); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(app.session.doc().unwrap().doc, before); +} + +/// Click the last visible text `label` in the dialog (a radio after a heading of the same name). +fn click_last(app: &mut VectorcraftApp, ctx: &egui::Context, label: &str) { + for _ in 0..4 { + creation_dialog_frame(app, ctx, vec![]); + } + let texts = creation_dialog_frame(app, ctx, vec![]); + let pos = texts.iter().rev().find(|(text, _)| text == label).unwrap_or_else(|| panic!("missing visible control {label}: {texts:?}")).1.center(); + for pressed in [true, false] { + let button = egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }; + creation_dialog_frame(app, ctx, vec![egui::Event::PointerMoved(pos), button]); + } + creation_dialog_frame(app, ctx, vec![]); +} + +#[test] +fn single_width_only_keeps_the_chosen_half_as_one_point() { + for (choice, kept) in [("Incoming", (0.8, 0.8)), ("Outgoing", (0.4, 1.2))] { + let (mut app, id) = pair_app(); + let before = app.session.doc().unwrap().doc.clone(); + let history = creation_history(&app); + app.run("ui.widthPointEdit", json!({"id": id, "index": 1})).unwrap(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + crate::theme::apply(&ctx, Default::default()); + click_last(&mut app, &ctx, choice); + assert_eq!(app.ui.dialog.as_ref().unwrap().str("single"), choice.to_lowercase()); + click_last(&mut app, &ctx, "OK"); + assert!(app.ui.dialog.is_none()); + assert_eq!(points(&app, id), vec![(0.0, 1.0, 1.0), (0.5, kept.0, kept.1), (1.0, 1.0, 1.0)], "{choice}"); + assert_eq!(creation_history(&app), (history.0 + 1, 0, true)); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(app.session.doc().unwrap().doc, before); + } +} + +#[test] +fn a_compound_member_edits_both_halves_of_its_owners_point() { + let (mut app, line) = app(); + let second = app.run("shape.line", json!({"x1": 320, "y1": 50, "x2": 320, "y2": 250})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [line, second]})).unwrap(); + let owner = app.run("object.compoundPath.make", json!({})).unwrap()["id"].as_u64().unwrap(); + app.run("stroke.widthProfile.set", json!({"ids": [owner], "points": [[0, 1, 1], [0.5, 0.8, 0.8], [0.5, 0.4, 1.2], [1, 1, 1]]})).unwrap(); + app.run("ui.widthPointEdit", json!({"id": second, "index": 2})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + assert_eq!(d.fields["id"], json!(owner)); + d.fields.insert("adjustAdjoining".into(), json!(true)); + d.fields.insert("side1".into(), json!(8)); + d.fields.insert("outSide2".into(), json!(3)); + super::super::confirm(&mut app).unwrap(); + // The incoming change (Side 1 doubled) doubles the start's Side 1; the outgoing one (Side 2 + // halved) halves the end's Side 2. + assert_eq!(points(&app, owner), vec![(0.0, 2.0, 1.0), (0.5, 1.6, 0.8), (0.5, 0.4, 0.6), (1.0, 1.0, 0.5)]); +} diff --git a/crates/ui-egui/src/i18n/bg.tsv b/crates/ui-egui/src/i18n/bg.tsv index bb039bb08e..c4c9b173fc 100644 --- a/crates/ui-egui/src/i18n/bg.tsv +++ b/crates/ui-egui/src/i18n/bg.tsv @@ -128,6 +128,9 @@ Additional Plug-ins Folder Допълнителна папка за плъгини Additional Fonts Folder Допълнителна папка за шрифтове Adjust Adjoining Width Points Регулиране на прилежащите точки за ширина + Incoming Входяща + Outgoing Изходяща + Single Width Only Само една ширина Adjust Color Balance… Коригиране на цветовия баланс… Adjust Colors Коригиране на цветовете Adjust Options: Параметри на коригиране: @@ -4737,6 +4740,9 @@ axis Both И двете @msg no such user library няма такава потребителска библиотека @msg no such view няма такъв изглед @msg no such width point няма такава точка за ширина +@msg `single` must be `incoming` or `outgoing` `single` трябва да е `incoming` или `outgoing` +@msg `index` and `outIndex` must be the two halves of one discontinuous width point `index` и `outIndex` трябва да са двете половини на една прекъсната точка за ширина +@msg a discontinuous width point keeps its place прекъснатата точка за ширина запазва мястото си @msg no swatch `{name}` няма образец `{name}` @msg no swatch library `{l}` (see swatch.library.list) няма библиотека с образци `{l}` (вижте swatch.library.list) @msg no symbol instances selected няма избрани екземпляри на символ diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 99f23d313c..35a6849e94 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -3329,6 +3329,9 @@ antiAlias Sharp Oštro Variable Options Opcije varijable Define a variable first Prvo definišite varijablu Adjust Adjoining Width Points Podesi susjedne tačke širine + Incoming Ulazna + Outgoing Izlazna + Single Width Only Samo jedna širina Keep both sides the same width Zadrži obje strane iste širine Side 1: Strana 1: Side 2: Strana 2: @@ -5144,6 +5147,9 @@ imageTrace Outline Obris @msg no such user library nema takve korisničke biblioteke @msg no such view nema takvog pogleda @msg no such width point nema takve tačke širine +@msg `single` must be `incoming` or `outgoing` `single` mora biti `incoming` ili `outgoing` +@msg `index` and `outIndex` must be the two halves of one discontinuous width point `index` i `outIndex` moraju biti dvije polovine jedne isprekidane tačke širine +@msg a discontinuous width point keeps its place isprekidana tačka širine zadržava svoje mjesto @msg no swatch `{name}` nema uzorka boje `{name}` @msg no swatch library `{l}` (see swatch.library.list) nema biblioteke uzoraka boja `{l}` (vidi swatch.library.list) @msg no symbol instances selected nisu odabrane instance simbola diff --git a/crates/ui-egui/src/i18n/ca.tsv b/crates/ui-egui/src/i18n/ca.tsv index c54311799d..e1657921f4 100644 --- a/crates/ui-egui/src/i18n/ca.tsv +++ b/crates/ui-egui/src/i18n/ca.tsv @@ -223,6 +223,9 @@ Additional Fonts Folder Carpeta addicional de tipus de lletra Additional Plug-ins Folder Carpeta addicional de complements Adjust Adjoining Width Points Ajusta els punts d’amplada contigus + Incoming Entrant + Outgoing Sortint + Single Width Only Només una amplada Adjust Color Balance… Ajusta l’equilibri de color… Adjust Colors Ajusta els colors Adjust Options: Opcions d’ajust: @@ -6274,6 +6277,9 @@ liquify-list-end {0}, {1} {0} i {1} @msg no such user library no existeix aquesta biblioteca d’usuari @msg no such view no existeix aquesta vista @msg no such width point no existeix aquest punt d’amplada +@msg `single` must be `incoming` or `outgoing` `single` ha de ser `incoming` o `outgoing` +@msg `index` and `outIndex` must be the two halves of one discontinuous width point `index` i `outIndex` han de ser les dues meitats d’un mateix punt d’amplada discontinu +@msg a discontinuous width point keeps its place un punt d’amplada discontinu manté la seva posició @msg no swatch `{name}` no hi ha la mostra `{name}` @msg no swatch library `{l}` (see swatch.library.list) no hi ha la biblioteca de mostres `{l}` (vegeu swatch.library.list) @msg no symbol `{n}` no hi ha el símbol `{n}` diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index a5d7bb948a..d1f49616cf 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -3419,6 +3419,9 @@ antiAlias Sharp Ostré Variable Options Možnosti proměnné Define a variable first Nejprve definujte proměnnou Adjust Adjoining Width Points Upravit sousední body šířky + Incoming Příchozí + Outgoing Odchozí + Single Width Only Pouze jedna šířka Keep both sides the same width Zachovat stejnou šířku obou stran Side 1: Strana 1: Side 2: Strana 2: @@ -5417,6 +5420,9 @@ liquify-list-end {0}, {1} {0} a {1} @msg no such user library taková uživatelská knihovna neexistuje @msg no such view takové zobrazení neexistuje @msg no such width point takový bod šířky neexistuje +@msg `single` must be `incoming` or `outgoing` `single` musí být `incoming` nebo `outgoing` +@msg `index` and `outIndex` must be the two halves of one discontinuous width point `index` a `outIndex` musí být dvě poloviny jednoho nespojitého bodu šířky +@msg a discontinuous width point keeps its place nespojitý bod šířky si zachovává své místo @msg no swatch `{name}` položka vzorníku `{name}` neexistuje @msg no swatch library `{l}` (see swatch.library.list) knihovna vzorníku `{l}` neexistuje (viz swatch.library.list) @msg no symbol instances selected nejsou vybrány žádné instance symbolů diff --git a/crates/ui-egui/src/i18n/da.tsv b/crates/ui-egui/src/i18n/da.tsv index 08100f593f..7be089384e 100644 --- a/crates/ui-egui/src/i18n/da.tsv +++ b/crates/ui-egui/src/i18n/da.tsv @@ -5856,6 +5856,9 @@ antiAlias Sharp Skarp Variable Options Indstillinger for variabel Define a variable first Definér først en variabel Adjust Adjoining Width Points Justér tilstødende breddepunkter + Incoming Indgående + Outgoing Udgående + Single Width Only Kun én bredde Keep both sides the same width Bevar samme bredde på begge sider Side 1: Side 1: Side 2: Side 2: @@ -7595,6 +7598,9 @@ imageTrace Outline Kontur @msg no such user library intet sådant brugerbibliotek @msg no such view ingen sådan visning @msg no such width point intet sådant breddepunkt +@msg `single` must be `incoming` or `outgoing` `single` skal være `incoming` eller `outgoing` +@msg `index` and `outIndex` must be the two halves of one discontinuous width point `index` og `outIndex` skal være de to halvdele af ét diskontinuert breddepunkt +@msg a discontinuous width point keeps its place et diskontinuert breddepunkt bevarer sin placering @msg no swatch `{name}` ingen farveprøve `{name}` @msg no swatch library `{l}` (see swatch.library.list) intet farveprøvebibliotek `{l}` (se swatch.library.list) @msg no symbol instances selected ingen symbolforekomster markeret diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 10147b2d45..518c312c5b 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -117,6 +117,9 @@ Additional Plug-ins Folder Zusätzlicher Plug-in-Ordner Additional Fonts Folder Zusätzlicher Schriftenordner Adjust Adjoining Width Points Angrenzende Breitenpunkte anpassen + Incoming Eingehend + Outgoing Ausgehend + Single Width Only Nur eine Breite Adjust Color Balance… Farbbalance anpassen… Adjust Colors Farben anpassen Adjust Options: Anpassungsoptionen: @@ -5019,6 +5022,9 @@ liquify-list-end {0}, {1} {0} und {1} @msg no such user library keine solche Benutzerbibliothek @msg no such view keine solche Ansicht @msg no such width point kein solcher Breitenpunkt +@msg `single` must be `incoming` or `outgoing` `single` muss `incoming` oder `outgoing` sein +@msg `index` and `outIndex` must be the two halves of one discontinuous width point `index` und `outIndex` müssen die beiden Hälften eines unterbrochenen Breitenpunkts sein +@msg a discontinuous width point keeps its place ein unterbrochener Breitenpunkt behält seine Position @msg no swatch `{name}` kein Farbfeld `{name}` @msg no swatch library `{l}` (see swatch.library.list) keine Farbfeldbibliothek `{l}` (siehe swatch.library.list) @msg no symbol instances selected keine Symbolinstanzen ausgewählt diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 1ebf6e5684..32480d4f66 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -122,6 +122,9 @@ Additional Plug-ins Folder Πρόσθετος φάκελος επεκτάσεων Additional Fonts Folder Πρόσθετος φάκελος γραμματοσειρών Adjust Adjoining Width Points Ρύθμιση γειτονικών σημείων πλάτους + Incoming Εισερχόμενο + Outgoing Εξερχόμενο + Single Width Only Μόνο ένα πλάτος Adjust Color Balance… Ρύθμιση ισορροπίας χρωμάτων… Adjust Colors Ρύθμιση χρωμάτων Adjust Options: Επιλογές ρύθμισης: @@ -5076,6 +5079,9 @@ digits Malayalam Μαλαγιάλαμ @msg no such user library δεν υπάρχει τέτοια βιβλιοθήκη χρήστη @msg no such view δεν υπάρχει τέτοια προβολή @msg no such width point δεν υπάρχει τέτοιο σημείο πλάτους +@msg `single` must be `incoming` or `outgoing` το `single` πρέπει να είναι `incoming` ή `outgoing` +@msg `index` and `outIndex` must be the two halves of one discontinuous width point τα `index` και `outIndex` πρέπει να είναι τα δύο μισά ενός ασυνεχούς σημείου πλάτους +@msg a discontinuous width point keeps its place ένα ασυνεχές σημείο πλάτους διατηρεί τη θέση του @msg no swatch `{name}` δεν υπάρχει δείγμα χρώματος `{name}` @msg no swatch library `{l}` (see swatch.library.list) δεν υπάρχει βιβλιοθήκη δειγμάτων `{l}` (δείτε swatch.library.list) @msg no symbol instances selected δεν έχουν επιλεγεί στιγμιότυπα συμβόλων diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index a456910a16..cc8eb4d0d5 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -142,6 +142,9 @@ Additional Plug-ins Folder Carpeta de plugins adicionales Additional Fonts Folder Carpeta de fuentes adicionales Adjust Adjoining Width Points Ajustar puntos de anchura contiguos + Incoming Entrante + Outgoing Saliente + Single Width Only Solo una anchura Adjust Color Balance… Ajustar equilibrio de color… Adjust Colors Ajustar colores Adjust Options: Opciones de ajuste: @@ -5122,6 +5125,9 @@ liquify-list-end {0}, {1} {0}, {1} @msg no such user library no existe esa biblioteca de usuario @msg no such view no existe esa vista @msg no such width point no existe ese punto de anchura +@msg `single` must be `incoming` or `outgoing` `single` debe ser `incoming` u `outgoing` +@msg `index` and `outIndex` must be the two halves of one discontinuous width point `index` y `outIndex` deben ser las dos mitades de un mismo punto de anchura discontinuo +@msg a discontinuous width point keeps its place un punto de anchura discontinuo conserva su posición @msg no swatch `{name}` no existe la muestra `{name}` @msg no swatch library `{l}` (see swatch.library.list) no existe la biblioteca de muestras `{l}` (consulta swatch.library.list) @msg no symbol instances selected no hay instancias de símbolo seleccionadas diff --git a/crates/ui-egui/src/i18n/fi.tsv b/crates/ui-egui/src/i18n/fi.tsv index bff46fc0d7..42996a4107 100644 --- a/crates/ui-egui/src/i18n/fi.tsv +++ b/crates/ui-egui/src/i18n/fi.tsv @@ -3363,6 +3363,9 @@ antiAlias Sharp Terävä Variable Options Muuttujan asetukset Define a variable first Määritä ensin muuttuja Adjust Adjoining Width Points Säädä viereisiä leveyspisteitä + Incoming Saapuva + Outgoing Lähtevä + Single Width Only Vain yksi leveys Keep both sides the same width Pidä molemmat puolet samanlevyisinä Side 1: Puoli 1: Side 2: Puoli 2: @@ -5346,6 +5349,9 @@ liquify-list-end {0}, {1} {0} ja {1} @msg no such user library käyttäjäkirjastoa ei ole @msg no such view näkymää ei ole @msg no such width point leveyspistettä ei ole +@msg `single` must be `incoming` or `outgoing` `single` on oltava `incoming` tai `outgoing` +@msg `index` and `outIndex` must be the two halves of one discontinuous width point `index` ja `outIndex` on oltava saman epäjatkuvan leveyspisteen kaksi puolikasta +@msg a discontinuous width point keeps its place epäjatkuva leveyspiste pysyy paikallaan @msg no swatch `{name}` ei värimallia `{name}` @msg no swatch library `{l}` (see swatch.library.list) ei värimallikirjastoa `{l}` (ks. swatch.library.list) @msg no symbol instances selected symboli-ilmentymiä ei ole valittu diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 3be3497f97..96b007cbe5 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -143,6 +143,9 @@ Additional Plug-ins Folder Dossier de modules externes supplémentaires Additional Fonts Folder Dossier de polices supplémentaires Adjust Adjoining Width Points Ajuster les points de largeur adjacents + Incoming Entrant + Outgoing Sortant + Single Width Only Une seule largeur Adjust Color Balance… Régler la balance des couleurs… Adjust Colors Régler les couleurs Adjust Options: Options de réglage : @@ -5084,6 +5087,9 @@ liquify-list-end {0}, {1} {0} et {1} @msg no such user library bibliothèque utilisateur inexistante @msg no such view vue inexistante @msg no such width point point de largeur inexistant +@msg `single` must be `incoming` or `outgoing` `single` doit valoir `incoming` ou `outgoing` +@msg `index` and `outIndex` must be the two halves of one discontinuous width point `index` et `outIndex` doivent être les deux moitiés d’un même point de largeur discontinu +@msg a discontinuous width point keeps its place un point de largeur discontinu garde sa position @msg no swatch `{name}` aucune nuance `{name}` @msg no swatch library `{l}` (see swatch.library.list) aucune bibliothèque de nuances `{l}` (voir swatch.library.list) @msg no symbol instances selected aucune instance de symbole sélectionnée diff --git a/crates/ui-egui/src/i18n/gu.tsv b/crates/ui-egui/src/i18n/gu.tsv index c427fc527c..04cb534fcb 100644 --- a/crates/ui-egui/src/i18n/gu.tsv +++ b/crates/ui-egui/src/i18n/gu.tsv @@ -164,6 +164,9 @@ Additional Fonts Folder વધારાનું ફોન્ટ ફોલ્ડર Additional Plug-ins Folder વધારાનું પ્લગ-ઇન ફોલ્ડર Adjust Adjoining Width Points અડીને આવેલા પહોળાઈ બિંદુઓ ગોઠવો + Incoming આવતી બાજુ + Outgoing જતી બાજુ + Single Width Only ફક્ત એક પહોળાઈ Adjust Color Balance… રંગ બૅલેન્સ ગોઠવો… Adjust Colors રંગ ગોઠવો Adjust Options: ગોઠવણ વિકલ્પો: diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index cbfb4f51d1..1d66fd3f60 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -257,6 +257,9 @@ Additional Fonts Folder अतिरिक्त फ़ॉन्ट फ़ोल्डर Additional Plug-ins Folder अतिरिक्त प्लग-इन फ़ोल्डर Adjust Adjoining Width Points सटे हुए चौड़ाई पॉइंट समायोजित करें + Incoming आने वाली ओर + Outgoing जाने वाली ओर + Single Width Only केवल एक चौड़ाई Adjust Color Balance… कलर बैलेंस समायोजित करें… Adjust Colors रंग समायोजित करें Adjust Options: समायोजन ऑप्शन्स: @@ -7831,6 +7834,9 @@ liquify-list-end {0}, {1} {0} और {1} @msg no such user library ऐसी कोई उपयोगकर्ता लाइब्रेरी नहीं @msg no such view कोई ऐसा दृश्य नहीं @msg no such width point ऐसी कोई चौड़ाई बिंदु नहीं +@msg `single` must be `incoming` or `outgoing` `single` का मान `incoming` या `outgoing` होना चाहिए +@msg `index` and `outIndex` must be the two halves of one discontinuous width point `index` और `outIndex` एक ही असतत चौड़ाई बिंदु के दो हिस्से होने चाहिए +@msg a discontinuous width point keeps its place असतत चौड़ाई बिंदु अपनी जगह पर रहता है @msg no swatch `{keep}` कोई स्वॉच `{keep}` नहीं @msg no swatch `{n}` कोई स्वॉच `{n}` नहीं @msg no swatch `{n}` (swatches and colour groups move separately) कोई स्वॉच `{n}` नहीं (स्वॉच और रंग समूह अलग-अलग मूव होते हैं) diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 0f81a72036..bfaf6595a4 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -211,6 +211,9 @@ Additional Fonts Folder További betűtípusok mappája Additional Plug-ins Folder További bővítmények mappája Adjust Adjoining Width Points Szomszédos szélességi pontok igazítása + Incoming Bejövő + Outgoing Kimenő + Single Width Only Csak egy szélesség Adjust Color Balance… Színegyensúly beállítása… Adjust Colors Színek beállítása Adjust Options: Módosítandó: @@ -5794,6 +5797,9 @@ liquify-list-end {0}, {1} {0} és {1} @msg no such user library nincs ilyen felhasználói könyvtár @msg no such view nincs ilyen nézet @msg no such width point nincs ilyen szélességi pont +@msg `single` must be `incoming` or `outgoing` a `single` értéke `incoming` vagy `outgoing` lehet +@msg `index` and `outIndex` must be the two halves of one discontinuous width point az `index` és az `outIndex` egyetlen szakadásos szélességi pont két fele kell legyen +@msg a discontinuous width point keeps its place a szakadásos szélességi pont megtartja a helyét @msg no swatch `{name}` nincs ilyen színminta: `{name}` @msg no swatch library `{l}` (see swatch.library.list) nincs ilyen színminta-könyvtár: `{l}` (lásd: swatch.library.list) @msg no symbol instances selected nincs kijelölt szimbólumpéldány diff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsv index 28ea2b5ab3..ab7574d1b4 100644 --- a/crates/ui-egui/src/i18n/id.tsv +++ b/crates/ui-egui/src/i18n/id.tsv @@ -3108,6 +3108,9 @@ antiAlias Sharp Tajam Variable Options Opsi variabel Define a variable first Tentukan variabel terlebih dahulu Adjust Adjoining Width Points Sesuaikan titik lebar bersebelahan + Incoming Masuk + Outgoing Keluar + Single Width Only Hanya satu lebar Keep both sides the same width Pertahankan kedua sisi tetap sama lebar Side 1: Sisi 1: Side 2: Sisi 2: @@ -4842,6 +4845,9 @@ imageTrace Outline Kontur @msg no such user library tidak ada pustaka pengguna seperti itu @msg no such view tidak ada tampilan seperti itu @msg no such width point tidak ada titik lebar seperti itu +@msg `single` must be `incoming` or `outgoing` `single` harus `incoming` atau `outgoing` +@msg `index` and `outIndex` must be the two halves of one discontinuous width point `index` dan `outIndex` harus berupa dua bagian dari satu titik lebar terputus +@msg a discontinuous width point keeps its place titik lebar terputus tetap di tempatnya @msg no swatch `{name}` tidak ada swatch `{name}` @msg no swatch library `{l}` (see swatch.library.list) tidak ada pustaka swatch `{l}` (lihat swatch.library.list) @msg no symbol instances selected tidak ada instans simbol yang dipilih diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 8f2ed3216c..e027397aa1 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -142,6 +142,9 @@ Additional Plug-ins Folder Cartella plug-in aggiuntivi Additional Fonts Folder Cartella font aggiuntivi Adjust Adjoining Width Points Regola punti di larghezza adiacenti + Incoming In entrata + Outgoing In uscita + Single Width Only Solo una larghezza Adjust Color Balance… Regola bilanciamento colore… Adjust Colors Regola colori Adjust Options: Opzioni di regolazione: @@ -5152,6 +5155,9 @@ liquify-list-end {0}, {1} {0} e {1} @msg no such user library libreria utente inesistente @msg no such view vista inesistente @msg no such width point punto di larghezza inesistente +@msg `single` must be `incoming` or `outgoing` `single` deve essere `incoming` o `outgoing` +@msg `index` and `outIndex` must be the two halves of one discontinuous width point `index` e `outIndex` devono essere le due metà di un unico punto di larghezza discontinuo +@msg a discontinuous width point keeps its place un punto di larghezza discontinuo mantiene la sua posizione @msg no swatch `{name}` nessun campione `{name}` @msg no swatch library `{l}` (see swatch.library.list) nessuna libreria campioni `{l}` (vedi swatch.library.list) @msg no symbol instances selected nessuna istanza di simbolo selezionata diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index c429f204a1..edfb3f603d 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -1075,6 +1075,9 @@ digits Malayalam マラヤーラム数字 Additional Plug-ins Folder 追加プラグインフォルダー Additional Fonts Folder 追加フォントフォルダー Adjust Adjoining Width Points 隣接する幅ポイントを調整 + Incoming 入り側 + Outgoing 出側 + Single Width Only 1 つの幅のみ Adjust Colors カラーを調整 Adjust Options: 調整オプション: Advanced Options 詳細オプション @@ -5264,6 +5267,9 @@ swatch Bright Violet ビビッドバイオレット @msg `{color}` is not a colour (#rrggbb or a preset name) `{color}` はカラーではありません (#rrggbb またはプリセット名で指定してください) @msg give the path `id` and the width point `index` パスの `id` と幅ポイントの `index` を指定してください @msg no such width point 指定された幅ポイントが見つかりません +@msg `single` must be `incoming` or `outgoing` `single` は `incoming` または `outgoing` にしてください +@msg `index` and `outIndex` must be the two halves of one discontinuous width point `index` と `outIndex` は 1 つの不連続な幅ポイントの 2 つの半分である必要があります +@msg a discontinuous width point keeps its place 不連続な幅ポイントの位置は変わりません @msg onto must name a panel floating in another group onto には、別のグループでフローティングしているパネルを指定してください @msg below and above must name a panel floating in another group below と above には別のグループでフローティングしているパネルを指定してください @msg give only one of onto, below and above onto、below、above のうち 1 つだけを指定してください diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index 414f45171c..6113bfc54c 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -5193,6 +5193,9 @@ antiAlias Sharp მკვეთრი Variable Options ცვლადის პარამეტრები Define a variable first ჯერ განსაზღვრეთ ცვლადი Adjust Adjoining Width Points მეზობელი სიგანის წერტილების მორგება + Incoming შემავალი + Outgoing გამავალი + Single Width Only მხოლოდ ერთი სიგანე Keep both sides the same width ორივე მხარის ერთნაირი სიგანე Side 1: მხარე 1: Side 2: მხარე 2: @@ -6926,6 +6929,9 @@ font-technology Variable ცვლადი @msg no such user library მომხმარებლის ასეთი ბიბლიოთეკა არ არის @msg no such view ასეთი ხედი არ არის @msg no such width point ასეთი სიგანის წერტილი არ არის +@msg `single` must be `incoming` or `outgoing` `single` უნდა იყოს `incoming` ან `outgoing` +@msg `index` and `outIndex` must be the two halves of one discontinuous width point `index` და `outIndex` უნდა იყოს ერთი წყვეტილი სიგანის წერტილის ორი ნახევარი +@msg a discontinuous width point keeps its place წყვეტილი სიგანის წერტილი თავის ადგილს ინარჩუნებს @msg no swatch `{name}` ფერის ნიმუში `{name}` არ არის @msg no swatch library `{l}` (see swatch.library.list) ფერის ნიმუშების ბიბლიოთეკა `{l}` არ არის (იხ. swatch.library.list) @msg no symbol instances selected სიმბოლოს ეგზემპლარები მონიშნული არ არის diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index dbda53243f..ddbdb73519 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -1065,6 +1065,9 @@ digits Malayalam 말라얄람어 Additional Plug-ins Folder 추가 플러그인 폴더 Additional Fonts Folder 추가 글꼴 폴더 Adjust Adjoining Width Points 인접한 너비 점 조정 + Incoming 들어오는 쪽 + Outgoing 나가는 쪽 + Single Width Only 한 너비만 Adjust Colors 색상 조정 Adjust Options: 조정 옵션: Advanced Options 고급 옵션 @@ -5191,6 +5194,9 @@ theme Appearance 외관 @msg `{color}` is not a colour (#rrggbb or a preset name) `{color}`은(는) 색상이 아닙니다(#rrggbb 또는 프리셋 이름) @msg give the path `id` and the width point `index` 패스 `id`와 너비 점 `index`를 지정하세요 @msg no such width point 해당 너비 점이 없습니다 +@msg `single` must be `incoming` or `outgoing` `single`은 `incoming` 또는 `outgoing`이어야 합니다 +@msg `index` and `outIndex` must be the two halves of one discontinuous width point `index`와 `outIndex`는 하나의 불연속 너비 점의 두 절반이어야 합니다 +@msg a discontinuous width point keeps its place 불연속 너비 점은 위치를 유지합니다 @msg onto must name a panel floating in another group onto는 다른 그룹에 떠 있는 패널을 지정해야 합니다 @msg below and above must name a panel floating in another group below와 above는 다른 그룹에 떠 있는 패널을 지정해야 합니다 @msg give only one of onto, below and above onto, below, above 중 하나만 지정하세요 diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsv index 69aef91cfc..52280d9c6b 100644 --- a/crates/ui-egui/src/i18n/nl.tsv +++ b/crates/ui-egui/src/i18n/nl.tsv @@ -3730,6 +3730,9 @@ antiAlias Sharp Scherp Variable Options Variabeleopties Define a variable first Definieer eerst een variabele Adjust Adjoining Width Points Aangrenzende breedtepunten aanpassen + Incoming Inkomend + Outgoing Uitgaand + Single Width Only Slechts één breedte Keep both sides the same width Beide zijden dezelfde breedte houden Side 1: Zijde 1: Side 2: Zijde 2: @@ -5468,6 +5471,9 @@ imageTrace Outline Contour @msg no such user library gebruikersbibliotheek bestaat niet @msg no such view weergave bestaat niet @msg no such width point breedtepunt bestaat niet +@msg `single` must be `incoming` or `outgoing` `single` moet `incoming` of `outgoing` zijn +@msg `index` and `outIndex` must be the two halves of one discontinuous width point `index` en `outIndex` moeten de twee helften van één onderbroken breedtepunt zijn +@msg a discontinuous width point keeps its place een onderbroken breedtepunt behoudt zijn plaats @msg no swatch `{name}` geen staal `{name}` @msg no swatch library `{l}` (see swatch.library.list) geen stalenbibliotheek `{l}` (zie swatch.library.list) @msg no symbol instances selected geen symboolinstanties geselecteerd diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 0147515ffe..4f0d60b51f 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -3300,6 +3300,9 @@ antiAlias Sharp Ostre Variable Options Opcje zmiennej Define a variable first Najpierw zdefiniuj zmienną Adjust Adjoining Width Points Dopasuj sąsiednie punkty szerokości + Incoming Wejściowa + Outgoing Wyjściowa + Single Width Only Tylko jedna szerokość Keep both sides the same width Zachowaj jednakową szerokość obu stron Side 1: Strona 1: Side 2: Strona 2: @@ -5240,6 +5243,9 @@ liquify-list-end {0}, {1} {0} i {1} @msg no such user library brak takiej biblioteki użytkownika @msg no such view brak takiego widoku @msg no such width point brak takiego punktu szerokości +@msg `single` must be `incoming` or `outgoing` `single` musi mieć wartość `incoming` lub `outgoing` +@msg `index` and `outIndex` must be the two halves of one discontinuous width point `index` i `outIndex` muszą być dwiema połówkami jednego nieciągłego punktu szerokości +@msg a discontinuous width point keeps its place nieciągły punkt szerokości zachowuje swoje położenie @msg no swatch `{name}` brak próbki `{name}` @msg no swatch library `{l}` (see swatch.library.list) brak biblioteki próbek `{l}` (patrz swatch.library.list) @msg no symbol instances selected nie zaznaczono wystąpień symboli diff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsv index 8201db7ab6..0d3a38037e 100644 --- a/crates/ui-egui/src/i18n/pt-br.tsv +++ b/crates/ui-egui/src/i18n/pt-br.tsv @@ -148,6 +148,9 @@ Additional Plug-ins Folder Pasta Adicional de Plug-ins Additional Fonts Folder Pasta Adicional de Fontes Adjust Adjoining Width Points Ajustar Pontos de Largura Adjacentes + Incoming Entrada + Outgoing Saída + Single Width Only Somente Uma Largura Adjust Color Balance… Ajustar Equilíbrio de Cores… Adjust Colors Ajustar Cores Adjust Options: Opções de Ajuste: @@ -4426,6 +4429,9 @@ axis Both Ambos @msg no such user library biblioteca do usuário inexistente @msg no such view vista inexistente @msg no such width point ponto de largura inexistente +@msg `single` must be `incoming` or `outgoing` `single` deve ser `incoming` ou `outgoing` +@msg `index` and `outIndex` must be the two halves of one discontinuous width point `index` e `outIndex` devem ser as duas metades de um mesmo ponto de largura descontínuo +@msg a discontinuous width point keeps its place um ponto de largura descontínuo mantém sua posição @msg no swatch `{name}` nenhuma amostra `{name}` @msg no swatch library `{l}` (see swatch.library.list) nenhuma biblioteca de amostras `{l}` (veja swatch.library.list) @msg no symbol instances selected nenhuma instância de símbolo selecionada diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index d1593508d3..d995df8349 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -140,6 +140,9 @@ Additional Plug-ins Folder Папка дополнительных модулей Additional Fonts Folder Папка дополнительных шрифтов Adjust Adjoining Width Points Настроить смежные точки ширины + Incoming Входящая + Outgoing Исходящая + Single Width Only Только одна ширина Adjust Color Balance… Настроить цветовой баланс… Adjust Colors Настроить цвета Adjust Options: Параметры настройки: @@ -5146,6 +5149,9 @@ liquify-list-end {0}, {1} {0} и {1} @msg no such user library такой пользовательской библиотеки нет @msg no such view такого вида нет @msg no such width point такой точки ширины нет +@msg `single` must be `incoming` or `outgoing` `single` должен быть `incoming` или `outgoing` +@msg `index` and `outIndex` must be the two halves of one discontinuous width point `index` и `outIndex` должны быть двумя половинами одной разрывной точки ширины +@msg a discontinuous width point keeps its place разрывная точка ширины сохраняет своё место @msg no swatch `{name}` нет образца `{name}` @msg no swatch library `{l}` (see swatch.library.list) нет библиотеки образцов `{l}` (см. swatch.library.list) @msg no symbol instances selected экземпляры символов не выделены diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index 5c0420fcd3..928d85a7d3 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -130,6 +130,9 @@ Additional Plug-ins Folder Mapp för ytterligare plugins Additional Fonts Folder Mapp för ytterligare typsnitt Adjust Adjoining Width Points Justera angränsande breddpunkter + Incoming Inkommande + Outgoing Utgående + Single Width Only Endast en bredd Adjust Color Balance… Justera färgbalans… Adjust Colors Justera färger Adjust Options: Justeringsalternativ: @@ -5019,6 +5022,9 @@ liquify-list-end {0}, {1} {0} och {1} @msg no such user library användarbiblioteket finns inte @msg no such view vyn finns inte @msg no such width point breddpunkten finns inte +@msg `single` must be `incoming` or `outgoing` `single` måste vara `incoming` eller `outgoing` +@msg `index` and `outIndex` must be the two halves of one discontinuous width point `index` och `outIndex` måste vara de två halvorna av en och samma diskontinuerliga breddpunkt +@msg a discontinuous width point keeps its place en diskontinuerlig breddpunkt behåller sin plats @msg no swatch `{name}` ingen färgruta `{name}` @msg no swatch library `{l}` (see swatch.library.list) inget färgrutebibliotek `{l}` (se swatch.library.list) @msg no symbol instances selected inga symbolinstanser är markerade diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 910a7fc5b1..a4a40055e6 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -127,6 +127,9 @@ Additional Plug-ins Folder Ek Eklentiler Klasörü Additional Fonts Folder Ek Yazı Tipleri Klasörü Adjust Adjoining Width Points Bitişik Genişlik Noktalarını Ayarlayın + Incoming Gelen + Outgoing Giden + Single Width Only Yalnızca Tek Genişlik Adjust Color Balance… Renk Dengesini Ayarlayın… Adjust Colors Renkleri Ayarla Adjust Options: Seçenekleri Ayarlayın: @@ -4833,6 +4836,9 @@ liquify-list-end {0}, {1} {0} ve {1} @msg no such user library böyle bir kullanıcı kütüphanesi yok @msg no such view öyle bir görüş yok @msg no such width point böyle bir genişlik noktası yok +@msg `single` must be `incoming` or `outgoing` `single`, `incoming` veya `outgoing` olmalıdır +@msg `index` and `outIndex` must be the two halves of one discontinuous width point `index` ve `outIndex`, tek bir süreksiz genişlik noktasının iki yarısı olmalıdır +@msg a discontinuous width point keeps its place süreksiz genişlik noktası yerini korur @msg no swatch `{name}` renk örneği yok `{name}` @msg no swatch library `{l}` (see swatch.library.list) renk örneği kitaplığı yok `{l}` (bkz. swatch.library.list) @msg no symbol instances selected sembol örneği seçilmedi diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index dbd6d2609e..ee0e19b530 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -136,6 +136,9 @@ Additional Plug-ins Folder Папка додаткових модулів Additional Fonts Folder Папка додаткових шрифтів Adjust Adjoining Width Points Налаштувати суміжні точки ширини + Incoming Вхідна + Outgoing Вихідна + Single Width Only Лише одна ширина Adjust Color Balance… Налаштувати колірний баланс… Adjust Colors Налаштувати кольори Adjust Options: Параметри налаштування: @@ -5136,6 +5139,9 @@ liquify-list-end {0}, {1} {0} і {1} @msg no such user library такої користувацької бібліотеки немає @msg no such view такого виду немає @msg no such width point такої точки ширини немає +@msg `single` must be `incoming` or `outgoing` `single` має бути `incoming` або `outgoing` +@msg `index` and `outIndex` must be the two halves of one discontinuous width point `index` і `outIndex` мають бути двома половинами однієї розривної точки ширини +@msg a discontinuous width point keeps its place розривна точка ширини зберігає своє місце @msg no swatch `{name}` немає зразка `{name}` @msg no swatch library `{l}` (see swatch.library.list) немає бібліотеки зразків `{l}` (див. swatch.library.list) @msg no symbol instances selected екземпляри символів не виділені diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 519c5d8f0d..3989702763 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -157,6 +157,9 @@ Additional Fonts Folder Thư mục phông bổ sung Additional Plug-ins Folder Thư mục plug-in bổ sung Adjust Adjoining Width Points Điều chỉnh các điểm chiều rộng kề nhau + Incoming Phía vào + Outgoing Phía ra + Single Width Only Chỉ một chiều rộng Adjust Color Balance… Điều chỉnh cân bằng màu… Adjust Colors Điều chỉnh màu sắc Adjust Options: Tùy chọn điều chỉnh: @@ -5480,6 +5483,9 @@ liquify-list-end {0}, {1} {0} và {1} @msg no such user library không có thư viện người dùng như vậy @msg no such view không có chế độ xem như vậy @msg no such width point không có điểm chiều rộng như vậy +@msg `single` must be `incoming` or `outgoing` `single` phải là `incoming` hoặc `outgoing` +@msg `index` and `outIndex` must be the two halves of one discontinuous width point `index` và `outIndex` phải là hai nửa của cùng một điểm chiều rộng gián đoạn +@msg a discontinuous width point keeps its place điểm chiều rộng gián đoạn giữ nguyên vị trí @msg no swatch `{name}` không có mẫu màu `{name}` @msg no swatch library `{l}` (see swatch.library.list) không có thư viện mẫu màu `{l}` (xem swatch.library.list) @msg no symbol instances selected chưa chọn đối tượng ký hiệu diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsv index c6696a9ec6..ee850ca586 100644 --- a/crates/ui-egui/src/i18n/zh-hans.tsv +++ b/crates/ui-egui/src/i18n/zh-hans.tsv @@ -91,6 +91,9 @@ Additional Plug-ins Folder 附加增效工具文件夹 Additional Fonts Folder 附加字体文件夹 Adjust Adjoining Width Points 调整相邻宽度点 + Incoming 入侧 + Outgoing 出侧 + Single Width Only 仅保留一个宽度 Adjust Color Balance… 调整色彩平衡… Adjust Colors 调整颜色 Adjust Options: 调整选项: @@ -4945,6 +4948,9 @@ imageTrace Outline 轮廓 @msg `{color}` is not a colour (#rrggbb or a preset name) `{color}` 不是颜色 (#rrggbb 或预设名称) @msg give the path `id` and the width point `index` 请给出路径的 `id` 和宽度点的 `index` @msg no such width point 没有此宽度点 +@msg `single` must be `incoming` or `outgoing` `single` 必须是 `incoming` 或 `outgoing` +@msg `index` and `outIndex` must be the two halves of one discontinuous width point `index` 和 `outIndex` 必须是同一个不连续宽度点的两半 +@msg a discontinuous width point keeps its place 不连续宽度点保持原位 @msg onto must name a panel floating in another group onto 必须指定浮动在另一个组中的面板 @msg below and above must name a panel floating in another group below 和 above 必须指定浮动在另一个组中的面板 @msg give only one of onto, below and above onto、below 和 above 只能给出一个 diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsv index 1480422931..4b620e3162 100644 --- a/crates/ui-egui/src/i18n/zh-hant.tsv +++ b/crates/ui-egui/src/i18n/zh-hant.tsv @@ -100,6 +100,9 @@ Additional Plug-ins Folder 額外的增效模組資料夾 Additional Fonts Folder 額外的字體資料夾 Adjust Adjoining Width Points 調整相鄰寬度點 + Incoming 入側 + Outgoing 出側 + Single Width Only 僅保留一個寬度 Adjust Color Balance… 調整色彩平衡… Adjust Colors 調整顏色 Adjust Options: 調整選項: @@ -2481,6 +2484,9 @@ file-filter Templates 範本 @msg `{color}` is not a colour (#rrggbb or a preset name) `{color}` 不是顏色 (#rrggbb 或預設集名稱) @msg give the path `id` and the width point `index` 請提供路徑的 `id` 和寬度點的 `index` @msg no such width point 沒有這個寬度點 +@msg `single` must be `incoming` or `outgoing` `single` 必須是 `incoming` 或 `outgoing` +@msg `index` and `outIndex` must be the two halves of one discontinuous width point `index` 和 `outIndex` 必須是同一個不連續寬度點的兩半 +@msg a discontinuous width point keeps its place 不連續寬度點保持原位 @msg onto must name a panel floating in another group onto 必須指定浮動在另一個群組中的面板 @msg below and above must name a panel floating in another group below 和 above 必須指定浮動在另一個群組中的面板 @msg give only one of onto, below and above onto、below 和 above 只能提供其中一個 diff --git a/docs/control-protocol.md b/docs/control-protocol.md index adac088a13..e599f9800f 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -592,6 +592,9 @@ Width Point Edit: double-clicking a width point with the Width tool, or `ui.widt `widthPoint` dialog (fields `id`, `index`, `t`, `side1` and `side2`: the left and right widths in points, `linked`, `adjustAdjoining`). `ui.dialog.confirm` runs `stroke.widthPoint.set` with them; `ui.dialog.set {field: "discard", value: true}` then confirm (the Delete button) removes the point with `stroke.widthPoint.remove`. +Either half of a discontinuous point opens both: `index` is the incoming half, and `outIndex`, `outSide1`, `outSide2` +and `outLinked` hold the outgoing half; `single` (`""`, `"incoming"` or `"outgoing"`) is Single Width Only. Confirm +sets both halves in one `stroke.widthPoint.set` (one undo step), and Delete removes both. Corners: double-clicking a Live Corners widget with the Selection or Direct Selection tool, or `ui.corners {id?, corners?}`, opens the `corners` dialog for a path's corners (the Direct-Selected ones, else every corner; fields `id`, diff --git a/docs/mcp.md b/docs/mcp.md index 4c1b661f42..b45ff0563d 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7235,6 +7235,14 @@ writes over it. with `index`, edits or moves one; `adjustAdjoining` changes the nearest points either side in proportion. Moving a point onto another one's `t` (or `stroke.widthPoint.copy {id, index, t}` landing there) makes a discontinuous point: two points at the same `t` (the width before it, then after it), and the stroke's width steps there. +`stroke.widthPoint.set {id, t, index, left, right, outIndex, outLeft, outRight, single?, adjustAdjoining?}` sets both +halves of one in one undo step: `index` is the incoming half, `outIndex` the outgoing half after it, and `t` must be +their place. With `adjustAdjoining`, the nearest point before changes with the incoming half and the nearest point +after with the outgoing half. `single: "incoming"` or `"outgoing"` keeps only that half's widths, leaving one +continuous point. Indices that are not the two halves of one discontinuous point (three or more points at one `t` +included), another `t`, or another `single` value are errors that leave the document and its undo history unchanged. +Width Point Edit on either half shows both halves as Incoming and Outgoing, with Single Width Only, and its Delete +removes both. `document.inspect` reports a path's `strokeOptions.widthPoints` (`[t, left, right]`, factors of half the weight; null for a uniform stroke). `stroke.widthPoint.remove {id, index | indices}` deletes points; `stroke.widthProfile.set {ids, points}` replaces them all, as dragging several Shift-selected points with the Width tool does in one undo step. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index ef83de54ad..db7068cd52 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -773,6 +773,7 @@ since 2026-10-01. - **Tab stop drag guide:** while a stop is dragged on the Tabs panel's ruler, the canvas draws a line through the text whose stops the ruler shows, where the stop would land: across the frame cell the paragraph starts in for area type, measured from where the frame lets the paragraph's first line start (the cell's edge inside the inset, or past a text wrap object), and across the paragraph's lines from the type's origin for point type. It turns with rotated type and runs across the columns of vertical type. In a Ctrl-drag (Command on macOS) it follows the grabbed stop. No line is drawn while a release would delete the stop, and the line goes on release, on Escape, when no button is down, and when the panel is closed. It is not a document object and records no undo step. Its extent, color and these rules are VectorCraft's own. A stop drag whose release the ruler does not get also ends then, as a marker drag already did. Tests `panels::tabs::tests::dragging_a_stop_draws_a_guide_through_the_text`, `a_command_drag_guide_follows_the_grabbed_stop`, `the_stop_guide_ends_with_the_drag`, `the_stop_guide_follows_rotated_point_and_vertical_type` and `the_stop_guide_starts_where_a_wrap_object_lets_the_line_start`. Public reference: [Manage tab stops](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/manage-tab-stops.html), which describes a guide shown through the selected text during a tab stop move. - **Tabs indent markers on threaded frames:** when a marker drag gives the paragraphs of a threaded story values of their own, the Tabs panel sends one `text.setFormat {paragraphIndents}` with an entry for each paragraph of the story, whatever order the frames were selected in with the Selection tool, so the story flows through its frames again once rather than once for each paragraph, and a drag that changes no paragraph runs nothing; a paragraph that runs on from one frame into the next gets one entry, after Type tool Select All too. A selected story is one text: with the Selection tool, a marker drag on any of its frames sets every paragraph of the story, in its locked and hidden frames too. Tests `panels::tabs::tests::indent_markers_on_selected_threaded_frames_follow_the_story_and_set_a_split_paragraph_once`, `indent_markers_over_many_threaded_paragraphs_send_one_format_command`, `indent_markers_after_select_all_list_a_split_paragraph_once`, `indent_markers_on_some_threaded_frames_list_the_whole_story_once`, `indent_markers_on_one_threaded_frame_set_its_locked_and_hidden_frames`, `cmd::threads::tests::paragraph_indents_flow_a_threaded_story_once_as_one_command_per_paragraph_would`, `paragraph_indents_over_thousands_of_paragraphs_flow_the_story_once` and `paragraph_indents_check_every_entry_and_skip_a_change_that_changes_nothing`, and `cmd::typecmd::area_tests::set_format_refuses_a_param_of_the_wrong_type`. Public reference: [Indent text](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/indent-text.html). - **Width Point Edit:** Shift-double-click enables Adjust Adjoining Width Points; plain double-click and direct opening retain the default. Tool dispatch and headless dialog tests cover neighboring widths, Undo/Redo and Cancel. Public reference: [Variable-width strokes](https://helpx.adobe.com/illustrator/using/stroke-object.html). +- **Width Point Edit on a discontinuous point:** opening the dialog on either half shows both sets of side widths, Incoming and Outgoing, each with Side 1, Side 2, Total Width and its own link; OK sets both halves in one `stroke.widthPoint.set` and one undo step, and Delete removes both. Single Width Only keeps the incoming or the outgoing widths as one continuous point. With Adjust Adjoining Width Points, the nearest point before follows the incoming change and the nearest point after follows the outgoing change; the group layout and that rule are VectorCraft's own. Tests `dialogs::width_point::tests::either_half_of_a_discontinuous_point_shows_both_sets_of_side_widths`, `ok_sets_both_halves_of_a_discontinuous_point_in_one_step`, `delete_removes_both_halves_of_a_discontinuous_point`, `single_width_only_keeps_the_chosen_half_as_one_point` and `a_compound_member_edits_both_halves_of_its_owners_point`, and `tests::widthpoints::paired_set_*` and `single_width_only_leaves_one_continuous_point`. Public references: [Apply stroke on an object](https://helpx.adobe.com/illustrator/using/stroke-object.html), which describes editing the widths before and after a discontinuous point in that dialog, and an [archived user guide, p. 161](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=167), which describes keeping either the incoming or the outgoing width to leave one continuous point. Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a feature lands. - **New ruler guides (G1):** Alt swaps orientation while dragging from either ruler, following the [public shortcut reference](https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html). Preview, snapping and final placement use the current axis. Tool and egui event tests exercise both rulers, modifier changes, cancellation and one-step Undo/Redo; existing-guide Alt-copy and ruler-origin gestures are unchanged. From 8cc5f194c8debd2f428b54f727684c697b493721 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 17 Nov 2026 15:50:52 -0800 Subject: [PATCH 150/176] Color Themes: Set Active Color paints selected characters as a swatch click does With characters selected with the Type tool, the button colors only those characters and leaves the default for new art as it was, as a Color panel or Swatches click does through the same paint.setFill and paint.setStroke path. The code comment and the docs/target-app-parity.md line now say so, and a test compares the button with paint.setFill on a selected range. --- crates/ui-egui/src/panels/color_themes.rs | 47 ++++++++++++++++++++++- docs/target-app-parity.md | 2 +- 2 files changed, 47 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/panels/color_themes.rs b/crates/ui-egui/src/panels/color_themes.rs index efa55f284e..25e0c3e1f3 100644 --- a/crates/ui-egui/src/panels/color_themes.rs +++ b/crates/ui-egui/src/panels/color_themes.rs @@ -128,7 +128,9 @@ fn add_draft_to_swatches(app: &mut VectorcraftApp, ctx: &egui::Context) { /// Paint the active proxy (Fill or Stroke) with the selected colour of the theme being made, in its /// own model: the selection and the new-art default take it in one paint command, so one undo -/// step, and no step when the art already has it. The theme stays as it is. +/// step, and no step when the art already has it. With characters selected with the Type tool, +/// only those characters take it and the new-art default stays as it was, as with a swatch click. +/// The theme stays as it is. fn set_active_color(app: &mut VectorcraftApp, d: &Draft) { if let Some(c) = d.colors.get(d.sel) { app.run(proxy_cmd(app, false), json!({ "color": color_json(c), "keepModel": true })).ok(); @@ -597,6 +599,49 @@ mod tests { assert!(matches!(d.colors[2], Color::Rgb { .. })); } + /// With characters selected with the Type tool, Set Active Color paints those characters as a + /// swatch click does: the type and the undo history come out as they do from `paint.setFill` with + /// the same color, and the new-art default stays as it was. + #[test] + fn set_active_color_paints_selected_characters_as_a_swatch_click_does() { + use vectorcraft_doc::{NodeId, NodeKind}; + // The editing handshake of text_styles::tests::select_type_range. + let typed = || { + let mut app = app(); + let id = NodeId(app.run("text.create", json!({"x": 10, "y": 50, "text": "ABcdef", "size": 18})).unwrap()["id"].as_u64().unwrap()); + app.session.select_tool("type", Default::default()).unwrap(); + app.session.apply_actions(vec![vectorcraft_tools::Action::Notify("text.editNew".into())]).unwrap(); + app.session.set_tool_option("select", &json!({"start": 2, "end": 4})); + super::super::character::end_typing(&mut app); + assert_eq!(super::super::character::text_editing(&app), Some((id, 2, 4))); + (app, id) + }; + let runs = |app: &VectorcraftApp, id: NodeId| match &app.session.doc().unwrap().doc.node(id).unwrap().kind { + NodeKind::Text(t) => t.runs.clone(), + _ => panic!("not type"), + }; + let (mut by_button, id) = typed(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let d = five_colors(&ctx); + let undo = undo_len(&by_button); + let default = (by_button.session.paint.fill.clone(), by_button.session.paint.stroke.clone()); + assert_ne!(default.0, vectorcraft_color::Paint::solid(d.colors[2])); + click(&mut by_button, &ctx, SET_ACTIVE); + let (mut by_command, _) = typed(); + by_command.run("paint.setFill", json!({"color": color_json(&d.colors[2]), "keepModel": true})).unwrap(); + let painted = runs(&by_button, id); + assert!(painted.iter().any(|r| r.style.fill == vectorcraft_color::Paint::solid(d.colors[2])), "the characters take the color"); + assert!(painted.iter().any(|r| r.style.fill != vectorcraft_color::Paint::solid(d.colors[2])), "the other characters keep theirs"); + assert_eq!(painted, runs(&by_command, id)); + assert_eq!((&by_button.session.paint.fill, &by_button.session.paint.stroke), (&default.0, &default.1), "the default stays"); + assert_eq!( + (&by_button.session.paint.fill, &by_button.session.paint.stroke), + (&by_command.session.paint.fill, &by_command.session.paint.stroke) + ); + assert_eq!((undo_len(&by_button), undo_len(&by_command)), (undo + 1, undo + 1)); + } + /// In a CMYK document the theme being made goes to Swatches with its colors in their own model. #[test] fn the_theme_being_made_keeps_its_model_in_a_cmyk_document() { diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index bc3ae3941c..963a06ddb2 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1776,7 +1776,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **RGB input to other commands in a CMYK document:** type colors (`text.create`, `text.setStyle`, `text.setRangeStyle`), a Shape Builder hex fill, `paint.editGradient` stops, freeform gradient points, gradient mesh points (the Mesh tool gives a new point the fill's color in its own model), the Symbol Stainer's color and the swatch commands (`swatch.new {colors}`, `swatch.newGroup`, `swatch.editGroup`, `swatch.edit`) separate RGB through the color settings as `paint.setFill` does: with Generic CMYK, `text.setStyle {fill: "#53aadf"}` gives C62 M19 Y0 K0. A color a swatch already has keeps its model, and a swatch color given with `mode` is converted into that mode only. - **Generic CMYK (SWOP-like):** each ink's 40% and 50% tints gain as [CGATS TR 001](https://registry.color.org/cmyk-registry/cgats_tr_001) gives for SWOP printing, and separations stay within SWOP's [300% total ink limit](https://en.wikipedia.org/wiki/Specifications_for_Web_Offset_Publications). The paper, solid and overprint colors, the black-generation curve and the black point are VectorCraft's own values: RGB black separates to 90% black under neutral cyan, magenta and yellow that fill the ink limit (C75 M68 Y67 K90). - **Swatches made from a shown color in a CMYK document:** the Color panel menu's Create New Swatch, an Alt-click on the Swatches panel's New Swatch button, the New Swatch dialog for a gradient, a Fill or Stroke proxy or the Gradient panel's thumbnail dropped on the Swatches panel (or Alt-dropped on a swatch of its kind), and the Gradient panel's Add to Swatches and Save to Swatches keep each color's model, as the Color Guide's and Color Themes' saved colors do: an RGB object's color gives an RGB swatch, and a gradient's RGB stops stay RGB. - - **Color Themes Set Active Color:** a button on the Color Themes panel's Create tab makes the selected theme color the current color, the action the [help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=222) describes for creating a color theme. VectorCraft's own rules: the color goes to the proxy in front (Fill or Stroke), on the selection and the default for new art, in its own color model, through `paint.setFill` or `paint.setStroke`; a click is one undo step, a click that changes no art adds none, and the button is off without a document. Tests: `set_active_color_*` in `crates/ui-egui/src/panels/color_themes.rs`. + - **Color Themes Set Active Color:** a button on the Color Themes panel's Create tab makes the selected theme color the current color, the action the [help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=222) describes for creating a color theme. VectorCraft's own rules: the color goes to the proxy in front (Fill or Stroke), on the selection and the default for new art, in its own color model, through `paint.setFill` or `paint.setStroke`; with characters selected with the Type tool, only those characters take it and the default for new art stays as it was, as with a swatch click; a click is one undo step, a click that changes no art adds none, and the button is off without a document. Tests: `set_active_color_*` in `crates/ui-egui/src/panels/color_themes.rs`. - **Sample Color from Screen:** an eyedropper button in the Color Picker and `ui.sampleScreenColor` (which can be given a key in Keyboard Shortcuts) pick a color anywhere on the screen with the system's sampler: `NSColorSampler` on macOS, the XDG desktop portal's [PickColor](https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.Screenshot.html) on Linux, a still copy of every monitor under a crosshair on Windows, and the EyeDropper API in browsers that have it. The color becomes the fill or the stroke as one undo step, or the Color Picker's color, converted from display sRGB into the working RGB space. On Linux, a session without a portal that has PickColor, a portal that does not return from the call within 25 seconds (VectorCraft's own limit) or leaves the bus before it answers, and a portal that ends the request another way each show a status message and end the wait. On Windows, the copy is read as sRGB, so the colors of HDR and wide-gamut displays are not converted; Escape, a click of another mouse button or switching to another window cancels (VectorCraft's own rules). The BSDs and other browsers have no sampler yet; the button is gray there. - **Color Guide color groups:** with variation cells selected, the Color Guide's Save Color Group to Swatches button saves those cells as one swatch group, and with none selected it saves the harmony colors, as the [help page](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf) describes saving several selected variations together (printed page 135). The group takes the cells in grid order (row by row, left to right, each cell once), is named after the harmony rule and is one undo step; these are VectorCraft's own rules. A selection lasts until the base, the Color Guide Options, the variation mode, the harmony rule, the library limit or the colors the grid shows (for example after a new swatch while the guide is limited to the document's swatches) change. - **Color Guide colors dragged to Swatches:** a variation cell dragged from the Color Guide onto the Swatches panel's list becomes a swatch of that color, as the [help page](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf) describes for saving variations as individual swatches (printed page 135). In VectorCraft a harmony strip color drags the same way, a drag carries only the grabbed color (the selected cells stay selected and the selection is not saved), it carries the color the cell shows (snapped to the Limit to Library colors), keeps the color's model and does not paint the selected art; the swatch follows the panel's rules for a dropped color (`swatch.new`, one undo step, a color that is already a swatch is added again under another name, a drop on a color group joins it). These are VectorCraft's own rules. Tests: `a_dragged_guide_color_carries_its_color_and_applies_nothing` and `a_guide_color_dragged_onto_the_swatches_panel_becomes_a_swatch` in `crates/ui-egui/src/panels/color_guide.rs`. From 9ed14dd264265b4641ddfb6acf247c7d95d423ca Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 17 Nov 2026 15:52:04 -0800 Subject: [PATCH 151/176] Color Themes: Show Find Field lists My Themes by theme name On the My Themes tab, the panel menu has a checked Show Find Field item that shows a Find field above the list. The list then shows only the saved themes whose names hold the field's text, anywhere and in any letter case, in their saved order; colors are not searched, and a search with no result shows "No matches.". A picked theme the field hides stays picked, but Edit Theme, Add to Swatches and Delete Theme are off until the list shows it again. The field is off in a new session and does not change the saved themes or colorTheme.list. The help page describes searching saved themes by name this way: https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=255 --- crates/ui-egui/src/panels/color_themes.rs | 213 +++++++++++++++++++++- docs/target-app-parity.md | 1 + 2 files changed, 210 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/panels/color_themes.rs b/crates/ui-egui/src/panels/color_themes.rs index 25e0c3e1f3..da72c15aac 100644 --- a/crates/ui-egui/src/panels/color_themes.rs +++ b/crates/ui-egui/src/panels/color_themes.rs @@ -1,6 +1,7 @@ //! Color Themes panel (local only): the Create tab makes a five-colour theme on a harmony wheel (a //! harmony rule from the selected colour, or Custom: each colour moves on its own; with a rule the -//! colours move together), the My Themes tab lists the themes saved in the preferences. Themes are +//! colours move together), the My Themes tab lists the themes saved in the preferences (the panel +//! menu's Show Find Field adds a field that lists only the themes whose names hold its text). Themes are //! saved, edited, deleted and added to Swatches as colour groups through `colorTheme.*`; the theme //! being made is panel state. @@ -90,9 +91,35 @@ fn set_draft(ctx: &egui::Context, d: Draft) { set_pstate(ctx, "ct-draft", Some(d)); } -/// The saved theme picked on the My Themes tab. +/// The saved theme picked on the My Themes tab, while the list shows it: a theme that the find +/// field hides stays picked, but nothing acts on it until the list shows it again. fn picked(app: &VectorcraftApp, ctx: &egui::Context) -> Option<String> { - pstate::<Option<String>>(ctx, "ct-picked").filter(|n| app.session.prefs.color_themes.iter().any(|t| t.name == *n)) + let q = query(ctx); + pstate::<Option<String>>(ctx, "ct-picked").filter(|n| app.session.prefs.color_themes.iter().any(|t| t.name == *n && matches(&t.name, &q))) +} + +/// The My Themes find field's text, kept while the panel menu hides the field. +fn find_id() -> egui::Id { + egui::Id::unique("ct-find") +} + +/// Whether the panel menu's Show Find Field shows the find field (off in a new session). +fn show_find(ctx: &egui::Context) -> bool { + pstate(ctx, "ct-show-find") +} + +/// The find field's text, trimmed and lowercased; empty while the field is hidden. +fn query(ctx: &egui::Context) -> String { + if !show_find(ctx) { + return String::new(); + } + ctx.data(|d| d.get_temp::<String>(find_id())).unwrap_or_default().trim().to_lowercase() +} + +/// Whether the find field lists theme `name` for `query` (trimmed and lowercased): its name holds +/// the text anywhere, in any letter case. An empty query lists every theme. +fn matches(name: &str, query: &str) -> bool { + query.is_empty() || name.to_lowercase().contains(query) } /// The tab shown: 0 Create, 1 My Themes. @@ -257,6 +284,12 @@ enum Action { fn my_themes(app: &mut VectorcraftApp, ui: &mut Ui) { let t = Tokens::get(ui.ctx()); let ctx = ui.ctx().clone(); + // The find field lists the saved themes whose names hold its text, in their saved order. + if show_find(&ctx) { + widgets::search_field(ui, find_id(), tl!("Find")); + ui.add_space(4.0); + } + let q = query(&ctx); let pick = picked(app, &ctx); let mut action = None; if app.session.prefs.color_themes.is_empty() { @@ -264,7 +297,11 @@ fn my_themes(app: &mut VectorcraftApp, ui: &mut Ui) { } else { widgets::list_box(ui, |ui| { egui::ScrollArea::vertical().id_salt("ct-list").max_height(300.0).auto_shrink([false, true]).show(ui, |ui| { - for th in &app.session.prefs.color_themes { + let mut shown = app.session.prefs.color_themes.iter().filter(|th| matches(&th.name, &q)).peekable(); + if shown.peek().is_none() { + widgets::dim_label(ui, tl!("No matches.")); + } + for th in shown { let (r, _) = ui.allocate_exact_size(vec2(ui.available_width(), 44.0), Sense::hover()); let resp = ui.interact(r, ui.scope_id().with(("ct-theme", &th.name)), Sense::click()); let selected = pick.as_deref() == Some(th.name.as_str()); @@ -356,6 +393,11 @@ pub fn menu(app: &mut VectorcraftApp, ui: &mut Ui) { { delete(app, &ctx, n); } + ui.separator(); + let find = show_find(&ctx); + if menu_item(ui, tl!("Show Find Field"), true, find) { + set_pstate(&ctx, "ct-show-find", !find); + } } else { if menu_item(ui, tl!("Save Theme"), true, false) { save(app, &ctx); @@ -470,6 +512,169 @@ mod tests { frame(&mut app, &ctx); } + /// The texts one frame draws: the panel, or with `menu_only` its panel menu, with `events`. + fn drawn(app: &mut VectorcraftApp, ctx: &egui::Context, menu_only: bool, events: Vec<egui::Event>) -> Vec<(String, Rect)> { + crate::i18n::set_current(crate::i18n::Lang::EN); + let screen = Rect::from_min_size(egui::Pos2::ZERO, vec2(320.0, 700.0)); + let input = egui::RawInput { events, screen_rect: Some(screen), ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| if menu_only { menu(app, ui) } else { show(app, ui) }); + out.textures_delta.clear(); + fn texts(s: &egui::Shape, out: &mut Vec<(String, Rect)>) { + match s { + egui::Shape::Text(t) => out.push((t.galley.text().to_string(), t.visual_bounding_rect())), + egui::Shape::Vec(v) => v.iter().for_each(|s| texts(s, out)), + _ => {} + } + } + let mut found = vec![]; + out.shapes.iter().for_each(|s| texts(&s.shape, &mut found)); + found + } + + /// The saved themes the My Themes list draws, in order. + fn listed(app: &mut VectorcraftApp, ctx: &egui::Context) -> Vec<String> { + drawn(app, ctx, false, vec![]); + let names: Vec<String> = themes(app).iter().map(|t| t.name.clone()).collect(); + drawn(app, ctx, false, vec![]).into_iter().map(|(t, _)| t).filter(|t| names.contains(t)).collect() + } + + /// Click panel menu item `label` (with its check mark, or three spaces when unchecked). + fn click_menu(app: &mut VectorcraftApp, ctx: &egui::Context, label: &str) { + let texts = drawn(app, ctx, true, vec![]); + let at = texts.iter().find(|(t, _)| t == label).unwrap_or_else(|| panic!("no {label:?} in {texts:?}")).1.center(); + let button = + |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + drawn(app, ctx, true, vec![egui::Event::PointerMoved(at), button(true), button(false)]); + } + + /// My Themes with three saved themes and the find field holding `text`. + fn three_themes(text: &str) -> (VectorcraftApp, egui::Context) { + let mut app = app(); + for (name, color) in [("Harbor", "#2266aa"), ("Harvest", "#cc8822"), ("Forest", "#227744")] { + app.run("colorTheme.save", json!({"color": color, "rule": "complementary", "name": name})).unwrap(); + } + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + set_pstate(&ctx, "ct-tab", 1usize); + set_pstate(&ctx, "ct-show-find", true); + ctx.data_mut(|d| d.insert_temp(find_id(), text.to_string())); + (app, ctx) + } + + /// Show Find Field is a checked item of the My Themes menu only, off in a new session; each + /// choice turns the field on or off. + #[test] + fn show_find_field_toggles_the_find_field_on_my_themes() { + let mut app = app(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let has = |texts: &[(String, Rect)], label: &str| texts.iter().any(|(t, _)| t == label); + let texts = drawn(&mut app, &ctx, true, vec![]); + assert!(!has(&texts, " Show Find Field") && !has(&texts, "✓ Show Find Field"), "the Create tab has no find field"); + set_pstate(&ctx, "ct-tab", 1usize); + assert!(has(&drawn(&mut app, &ctx, true, vec![]), " Show Find Field"), "off in a new session"); + assert!(!has(&drawn(&mut app, &ctx, false, vec![]), "Find"), "no field while it is off"); + click_menu(&mut app, &ctx, " Show Find Field"); + assert!(show_find(&ctx)); + assert!(has(&drawn(&mut app, &ctx, true, vec![]), "✓ Show Find Field")); + assert!(has(&drawn(&mut app, &ctx, false, vec![]), "Find"), "the field shows its hint"); + click_menu(&mut app, &ctx, "✓ Show Find Field"); + assert!(!show_find(&ctx)); + } + + /// The find field lists the themes whose names hold its text, in any letter case, anywhere in + /// the name, in their saved order; it reads names only, and its text is plain text. + #[test] + fn the_find_field_lists_themes_whose_names_hold_its_text() { + let (mut app, ctx) = three_themes(" HAR "); + assert_eq!(listed(&mut app, &ctx), ["Harbor", "Harvest"]); + ctx.data_mut(|d| d.insert_temp(find_id(), "vest".to_string())); + assert_eq!(listed(&mut app, &ctx), ["Harvest"], "a match in the middle of a name"); + // Colours are not searched: no name holds "2266aa". + ctx.data_mut(|d| d.insert_temp(find_id(), "2266aa".to_string())); + assert!(listed(&mut app, &ctx).is_empty()); + assert!(drawn(&mut app, &ctx, false, vec![]).iter().any(|(t, _)| t == "No matches.")); + assert_eq!(themes(&app).len(), 3, "the saved themes stay"); + // Pattern characters are plain text, and letters outside ASCII match in either case. + app.run("colorTheme.save", json!({"color": "#aa2266", "rule": "complementary", "name": "Été a.b*"})).unwrap(); + ctx.data_mut(|d| d.insert_temp(find_id(), "ÉTÉ A.B*".to_string())); + assert_eq!(listed(&mut app, &ctx), ["Été a.b*"]); + ctx.data_mut(|d| d.insert_temp(find_id(), ".*".to_string())); + assert!(listed(&mut app, &ctx).is_empty()); + // Blank text, or the field turned off, lists every theme; turned on again the text applies. + ctx.data_mut(|d| d.insert_temp(find_id(), " ".to_string())); + assert_eq!(listed(&mut app, &ctx).len(), 4); + ctx.data_mut(|d| d.insert_temp(find_id(), "har".to_string())); + set_pstate(&ctx, "ct-show-find", false); + assert_eq!(listed(&mut app, &ctx).len(), 4); + set_pstate(&ctx, "ct-show-find", true); + assert_eq!(listed(&mut app, &ctx), ["Harbor", "Harvest"]); + } + + /// With no saved themes the panel says so, whatever the find field holds. + #[test] + fn no_saved_themes_is_not_no_matches() { + let mut app = app(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + set_pstate(&ctx, "ct-tab", 1usize); + set_pstate(&ctx, "ct-show-find", true); + ctx.data_mut(|d| d.insert_temp(find_id(), "har".to_string())); + drawn(&mut app, &ctx, false, vec![]); + let texts: Vec<String> = drawn(&mut app, &ctx, false, vec![]).into_iter().map(|(t, _)| t).collect(); + assert!(texts.iter().any(|t| t == "No saved themes"), "{texts:?}"); + assert!(!texts.iter().any(|t| t == "No matches.")); + } + + /// A picked theme that the find field hides stays picked, but neither the menu nor the footer + /// acts on it until the list shows it again. + #[test] + fn a_theme_the_find_field_hides_is_not_acted_on() { + let (mut app, ctx) = three_themes("har"); + set_pstate(&ctx, "ct-picked", Some("Forest".to_string())); + assert_eq!(picked(&app, &ctx), None); + drawn(&mut app, &ctx, true, vec![]); + click_menu(&mut app, &ctx, " Delete Theme"); + assert_eq!(themes(&app).len(), 3, "Delete Theme is off"); + click_menu(&mut app, &ctx, " Edit Theme"); + assert_eq!(tab(&ctx), 1, "Edit Theme is off"); + let undo = undo_len(&app); + click_menu(&mut app, &ctx, " Add to Swatches"); + assert_eq!(undo_len(&app), undo, "Add to Swatches is off"); + // Cleared, the field lists Forest again and it is picked as before. + ctx.data_mut(|d| d.insert_temp(find_id(), String::new())); + assert_eq!(picked(&app, &ctx).as_deref(), Some("Forest")); + ctx.data_mut(|d| d.insert_temp(find_id(), "har".to_string())); + set_pstate(&ctx, "ct-show-find", false); + assert_eq!(picked(&app, &ctx).as_deref(), Some("Forest"), "the field turned off lists it too"); + set_pstate(&ctx, "ct-show-find", true); + // A theme the field shows is acted on. + set_pstate(&ctx, "ct-picked", Some("Harvest".to_string())); + click_menu(&mut app, &ctx, " Delete Theme"); + assert_eq!(themes(&app).iter().map(|t| t.name.as_str()).collect::<Vec<_>>(), ["Harbor", "Forest"]); + } + + /// The footer buttons are off for a picked theme that the find field hides. + #[test] + fn footer_buttons_are_off_for_a_hidden_pick() { + use crate::widgets::accessibility_tests::{named, tree}; + let mut app = app(); + app.run("colorTheme.save", json!({"color": "#227744", "rule": "complementary", "name": "Forest"})).unwrap(); + for (text, off) in [("har", true), ("for", false)] { + let shown = tree(|ui| { + let ctx = ui.ctx().clone(); + set_pstate(&ctx, "ct-tab", 1usize); + set_pstate(&ctx, "ct-show-find", true); + set_pstate(&ctx, "ct-picked", Some("Forest".to_string())); + ctx.data_mut(|d| d.insert_temp(find_id(), text.to_string())); + show(&mut app, ui); + }); + for label in ["Edit theme", "Add to Swatches", "Delete theme"] { + assert_eq!(named(&shown, label).is_disabled(), off, "{label} with {text:?}"); + } + } + } + const SET_ACTIVE: &str = "Set the current fill or stroke to the selected color"; /// A click on the panel button that screen readers name `label`. egui finds what the pointer is diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 963a06ddb2..8fb16bbaa4 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1777,6 +1777,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Generic CMYK (SWOP-like):** each ink's 40% and 50% tints gain as [CGATS TR 001](https://registry.color.org/cmyk-registry/cgats_tr_001) gives for SWOP printing, and separations stay within SWOP's [300% total ink limit](https://en.wikipedia.org/wiki/Specifications_for_Web_Offset_Publications). The paper, solid and overprint colors, the black-generation curve and the black point are VectorCraft's own values: RGB black separates to 90% black under neutral cyan, magenta and yellow that fill the ink limit (C75 M68 Y67 K90). - **Swatches made from a shown color in a CMYK document:** the Color panel menu's Create New Swatch, an Alt-click on the Swatches panel's New Swatch button, the New Swatch dialog for a gradient, a Fill or Stroke proxy or the Gradient panel's thumbnail dropped on the Swatches panel (or Alt-dropped on a swatch of its kind), and the Gradient panel's Add to Swatches and Save to Swatches keep each color's model, as the Color Guide's and Color Themes' saved colors do: an RGB object's color gives an RGB swatch, and a gradient's RGB stops stay RGB. - **Color Themes Set Active Color:** a button on the Color Themes panel's Create tab makes the selected theme color the current color, the action the [help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=222) describes for creating a color theme. VectorCraft's own rules: the color goes to the proxy in front (Fill or Stroke), on the selection and the default for new art, in its own color model, through `paint.setFill` or `paint.setStroke`; with characters selected with the Type tool, only those characters take it and the default for new art stays as it was, as with a swatch click; a click is one undo step, a click that changes no art adds none, and the button is off without a document. Tests: `set_active_color_*` in `crates/ui-egui/src/panels/color_themes.rs`. + - **Color Themes find field:** on the Color Themes panel's My Themes tab, Show Find Field in the panel menu shows a Find field that lists only the saved themes whose names hold its text; the [help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=255) describes looking up a saved theme by its name this way (printed page 249). VectorCraft's own rules: the menu item is checked while the field shows and is off in a new session; a name matches when it holds the text anywhere, in any letter case, with spaces at either end of the text ignored; colors are not searched; the list keeps its saved order and shows No matches. when nothing matches; a picked theme the field hides stays picked, but Edit Theme, Add to Swatches and Delete Theme are off until the list shows it again; turning the field off lists every theme, and turning it on again in the same session restores its text. The field does not change the saved themes or `colorTheme.list`. Tests: `show_find_field_toggles_the_find_field_on_my_themes`, `the_find_field_lists_themes_whose_names_hold_its_text`, `no_saved_themes_is_not_no_matches`, `a_theme_the_find_field_hides_is_not_acted_on` and `footer_buttons_are_off_for_a_hidden_pick` in `crates/ui-egui/src/panels/color_themes.rs`. - **Sample Color from Screen:** an eyedropper button in the Color Picker and `ui.sampleScreenColor` (which can be given a key in Keyboard Shortcuts) pick a color anywhere on the screen with the system's sampler: `NSColorSampler` on macOS, the XDG desktop portal's [PickColor](https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.Screenshot.html) on Linux, a still copy of every monitor under a crosshair on Windows, and the EyeDropper API in browsers that have it. The color becomes the fill or the stroke as one undo step, or the Color Picker's color, converted from display sRGB into the working RGB space. On Linux, a session without a portal that has PickColor, a portal that does not return from the call within 25 seconds (VectorCraft's own limit) or leaves the bus before it answers, and a portal that ends the request another way each show a status message and end the wait. On Windows, the copy is read as sRGB, so the colors of HDR and wide-gamut displays are not converted; Escape, a click of another mouse button or switching to another window cancels (VectorCraft's own rules). The BSDs and other browsers have no sampler yet; the button is gray there. - **Color Guide color groups:** with variation cells selected, the Color Guide's Save Color Group to Swatches button saves those cells as one swatch group, and with none selected it saves the harmony colors, as the [help page](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf) describes saving several selected variations together (printed page 135). The group takes the cells in grid order (row by row, left to right, each cell once), is named after the harmony rule and is one undo step; these are VectorCraft's own rules. A selection lasts until the base, the Color Guide Options, the variation mode, the harmony rule, the library limit or the colors the grid shows (for example after a new swatch while the guide is limited to the document's swatches) change. - **Color Guide colors dragged to Swatches:** a variation cell dragged from the Color Guide onto the Swatches panel's list becomes a swatch of that color, as the [help page](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf) describes for saving variations as individual swatches (printed page 135). In VectorCraft a harmony strip color drags the same way, a drag carries only the grabbed color (the selected cells stay selected and the selection is not saved), it carries the color the cell shows (snapped to the Limit to Library colors), keeps the color's model and does not paint the selected art; the swatch follows the panel's rules for a dropped color (`swatch.new`, one undo step, a color that is already a swatch is added again under another name, a drop on a color group joins it). These are VectorCraft's own rules. Tests: `a_dragged_guide_color_carries_its_color_and_applies_nothing` and `a_guide_color_dragged_onto_the_swatches_panel_becomes_a_swatch` in `crates/ui-egui/src/panels/color_guide.rs`. From c580548ef2c239199007cc51af113ffd05a721cb Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 17 Nov 2026 15:55:07 -0800 Subject: [PATCH 152/176] Symbols: find selected symbol instances once per document revision The Properties panel's Reset quick action and the Symbols panel's Break Link to Symbol each walked the selected subtrees on every repaint, reading each one in full until one held an instance, to learn whether the selection holds a symbol instance. One walk per document revision now records the instances and whether one has appearance changes of its own, and later frames reuse it. Whether Reset Transformation would change an instance is worked out from those instances on the first request and kept with them. The buttons and menu items are enabled exactly as before. With one selected group of 300,000 paths, the two panels' reads took a median 5.1 to 5.7 ms of thread CPU time per repaint; the first read after a change now takes about 3 ms and later repaints about 5 ns. --- crates/ui-egui/src/app.rs | 1 + crates/ui-egui/src/caches.rs | 15 +++ crates/ui-egui/src/panels/symbols.rs | 183 ++++++++++++++++++++++++--- docs/target-app-parity.md | 1 + 4 files changed, 183 insertions(+), 17 deletions(-) diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index e3d2a13d64..c256c17a3c 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -90,6 +90,7 @@ impl VectorcraftApp { selection_bounds: None, content_bounds: None, pixel_aligned: None, + symbol_instances: None, plugin_keys: Default::default(), placed_keys: Default::default(), cursors: Default::default(), diff --git a/crates/ui-egui/src/caches.rs b/crates/ui-egui/src/caches.rs index 6dc036fcf2..c2fd1de1d8 100644 --- a/crates/ui-egui/src/caches.rs +++ b/crates/ui-egui/src/caches.rs @@ -64,6 +64,9 @@ pub struct CanvasCache { /// The Transform panel's Align to Pixel Grid state (on, off or mixed, and whether every /// selected object can be aligned) for (document uid, revision). pub pixel_aligned: Option<((u64, u64), Option<PixelAligned>)>, + /// The symbol instances in the selection and its groups, for (document uid, revision): the + /// Properties and Symbols panels read them every frame. + pub symbol_instances: Option<((u64, u64), SymbolInstances)>, /// [`CacheKey::plugins`] by document uid, with the plug-in revision /// ([`vectorcraft_render::effects::plugin_revision`]) it was last checked at. pub plugin_keys: std::collections::HashMap<u64, (u64, u64)>, @@ -115,6 +118,18 @@ pub type LivePaintGapsCache = ((u64, u64), std::sync::Arc<Vec<vectorcraft_tools: /// agree and `None` when they differ, with whether every one can be aligned. pub type PixelAligned = (Option<bool>, bool); +/// [`CanvasCache::symbol_instances`]: the symbol instances in the selection and its groups. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct SymbolInstances { + /// Each instance's id, in the order the selection's subtrees list them. + pub ids: Vec<vectorcraft_doc::NodeId>, + /// One of them has appearance changes of its own (`symbol_overrides`). + pub changed: bool, + /// One of them has a scale, rotation or shear that Reset Transformation would change; measured + /// on the first read. + pub transformed: Option<bool>, +} + /// [`CanvasCache::print_tiling`]: the print tiling of (document uid, revision). pub type PrintTilingCache = ((u64, u64), std::sync::Arc<Vec<vectorcraft_pdf::TilingPage>>); diff --git a/crates/ui-egui/src/panels/symbols.rs b/crates/ui-egui/src/panels/symbols.rs index 0be9e7111c..6b500e6b3a 100644 --- a/crates/ui-egui/src/panels/symbols.rs +++ b/crates/ui-egui/src/panels/symbols.rs @@ -19,6 +19,7 @@ use super::library_panel::{self, LibraryKind, LibraryRef, Row}; use super::memo::Memo; use super::{pstate, set_pstate}; use crate::VectorcraftApp; +use crate::caches::SymbolInstances; use crate::menus::Item; use crate::theme::Tokens; use crate::widgets::{self, PanelDrag, menu_item}; @@ -139,21 +140,37 @@ fn current(app: &VectorcraftApp) -> Option<String> { app.session.active().and_then(|st| vectorcraft_engine::cmd::current_symbol(&st.doc)) } -/// Does the selection hold (in it or in its groups) a symbol instance that `wanted` takes? -fn instance_selected(app: &VectorcraftApp, wanted: impl Fn(&Node) -> bool) -> bool { - app.session.active().is_some_and(|st| { - st.selection.objects.iter().any(|id| { - let mut any = false; - if let Some(n) = st.doc.node(*id) { - n.walk(&mut |c| any |= matches!(c.kind, NodeKind::SymbolInstance { .. }) && wanted(c)); - } - any - }) - }) +#[cfg(test)] +thread_local! { + /// How many times [`selected_instances`] walked the selection on this thread. + static INSTANCE_SCANS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; } -fn has_instances_selected(app: &VectorcraftApp) -> bool { - instance_selected(app, |_| true) +/// The symbol instances in the selection and in its groups, found in one walk of the selected +/// subtrees per (document uid, revision) ([`crate::caches::CanvasCache::symbol_instances`]); +/// `None` without a document. +fn selected_instances(app: &mut VectorcraftApp) -> Option<&mut SymbolInstances> { + let st = app.session.active()?; + let key = (st.uid, st.revision); + if app.canvas.symbol_instances.as_ref().is_none_or(|(k, _)| *k != key) { + #[cfg(test)] + INSTANCE_SCANS.with(|n| n.set(n.get() + 1)); + let mut found = SymbolInstances::default(); + for n in st.selection.objects.iter().filter_map(|id| st.doc.node(*id)) { + n.walk(&mut |c| { + if matches!(c.kind, NodeKind::SymbolInstance { .. }) { + found.changed |= !c.extras().symbol_overrides.is_empty(); + found.ids.push(c.id); + } + }); + } + app.canvas.symbol_instances = Some((key, found)); + } + app.canvas.symbol_instances.as_mut().map(|(_, found)| found) +} + +fn has_instances_selected(app: &mut VectorcraftApp) -> bool { + selected_instances(app).is_some_and(|found| !found.ids.is_empty()) } /// Collect the IDs of selected instances of symbol `name` (including inside groups). @@ -221,15 +238,19 @@ fn item_context_menu(app: &mut VectorcraftApp, ui: &mut Ui, name: &str) { /// Does the selection hold a symbol instance with appearance changes of its own (a dynamic /// symbol's), which Reset drops? -pub(crate) fn changed_instances_selected(app: &VectorcraftApp) -> bool { - instance_selected(app, |c| !c.extras().symbol_overrides.is_empty()) +pub(crate) fn changed_instances_selected(app: &mut VectorcraftApp) -> bool { + selected_instances(app).is_some_and(|found| found.changed) } /// Does the selection hold a symbol instance whose scale, rotation or shear differs from its /// symbol's, which Reset Transformation restores? -fn transformed_instances_selected(app: &VectorcraftApp) -> bool { +fn transformed_instances_selected(app: &mut VectorcraftApp) -> bool { let Some(doc) = app.session.active().map(|st| st.doc.clone()) else { return false }; - instance_selected(app, |c| vectorcraft_engine::cmd::reset_transformation_changes(&doc, c)) + let Some(found) = selected_instances(app) else { return false }; + let ids = &found.ids; + *found + .transformed + .get_or_insert_with(|| ids.iter().filter_map(|id| doc.node(*id)).any(|n| vectorcraft_engine::cmd::reset_transformation_changes(&doc, n))) } /// The symbols of the selected objects when every one is a symbol instance; `None` otherwise. @@ -1008,6 +1029,134 @@ mod tests { assert_eq!(app.run("symbol.list", json!({})).unwrap()["symbols"][0]["alignToPixelGrid"], false); } + /// Does the selection hold a symbol instance that `wanted` takes, found by walking every + /// selected subtree on each call: what the cached flags must match. + fn walked(app: &VectorcraftApp, wanted: impl Fn(&Node) -> bool) -> bool { + app.session.active().is_some_and(|st| { + st.selection.objects.iter().any(|id| { + let mut any = false; + if let Some(n) = st.doc.node(*id) { + n.walk(&mut |c| any |= matches!(c.kind, NodeKind::SymbolInstance { .. }) && wanted(c)); + } + any + }) + }) + } + + /// Any instance, one with appearance changes, one Reset Transformation changes: walked again. + fn walked_flags(app: &VectorcraftApp) -> [bool; 3] { + let Some(doc) = app.session.active().map(|st| st.doc.clone()) else { return [false; 3] }; + [ + walked(app, |_| true), + walked(app, |c| !c.extras().symbol_overrides.is_empty()), + walked(app, |c| vectorcraft_engine::cmd::reset_transformation_changes(&doc, c)), + ] + } + + fn cached_flags(app: &mut VectorcraftApp) -> [bool; 3] { + [has_instances_selected(app), changed_instances_selected(app), transformed_instances_selected(app)] + } + + fn scans() -> usize { + INSTANCE_SCANS.with(std::cell::Cell::get) + } + + /// The Symbols and Properties panels' instance flags (Break Link, Reset Symbol Instance and the + /// Properties panel's Reset, Reset Transformation) are those a walk of the selection gives, for + /// plain, changed, scaled and grouped instances, several selected objects, nothing selected, + /// Undo and another document; the selection is walked once per document revision, however + /// often they are read. + #[test] + fn instance_flags_are_found_once_per_revision_and_match_a_walk_of_the_selection() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 400, "height": 200})).unwrap(); + let id = |v: Value| v["id"].as_u64().unwrap(); + let rect = id(app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap()); + let second = id(app.run("shape.rectangle", json!({"x": 60, "y": 10, "width": 40, "height": 40})).unwrap()); + let other = id(app.run("shape.rectangle", json!({"x": 300, "y": 10, "width": 40, "height": 40})).unwrap()); + // Reads every flag several times; the walk runs only when the revision changed. + let check = |app: &mut VectorcraftApp, want: [bool; 3], what: &str| { + let before = scans(); + for _ in 0..3 { + assert_eq!(cached_flags(app), want, "{what}"); + } + assert_eq!(walked_flags(app), want, "{what}: a walk of the selection agrees"); + assert!(scans() - before <= 1, "{what}: walked {} times", scans() - before); + }; + app.run("select.set", json!({"ids": [rect]})).unwrap(); + check(&mut app, [false; 3], "no instance"); + // Two objects, so the instance's art is a group whose first object can be painted. + let inst = id(app.run("symbol.new", json!({"name": "S", "ids": [rect, second], "type": "dynamic"})).unwrap()); + app.run("select.set", json!({"ids": [inst]})).unwrap(); + check(&mut app, [true, false, false], "a plain instance"); + app.run("symbol.instance.setAppearance", json!({"id": inst, "path": [0], "fill": "#ff0000"})).unwrap(); + app.run("select.set", json!({"ids": [inst]})).unwrap(); + check(&mut app, [true, true, false], "an instance with appearance changes"); + let scaled = id(app.run("symbol.place", json!({"name": "S", "x": 200, "y": 100})).unwrap()); + app.run("select.set", json!({"ids": [scaled]})).unwrap(); + app.run("object.scale", json!({"sx": 150, "sy": 50})).unwrap(); + check(&mut app, [true, false, true], "a scaled instance"); + app.run("select.set", json!({"ids": [scaled, other]})).unwrap(); + let group = id(app.run("object.group", json!({})).unwrap()); + app.run("select.set", json!({"ids": [group]})).unwrap(); + check(&mut app, [true, false, true], "an instance in a selected group"); + app.run("select.set", json!({"ids": [inst, group]})).unwrap(); + check(&mut app, [true, true, true], "several selected objects"); + app.run("select.set", json!({"ids": [other]})).unwrap(); + check(&mut app, [false; 3], "select.set to a path"); + app.run("select.none", json!({})).unwrap(); + check(&mut app, [false; 3], "nothing selected"); + // Undo takes the group apart again. + app.run("edit.undo", json!({})).unwrap(); + let undone = walked_flags(&app); + check(&mut app, undone, "after Undo"); + // At one revision the walk runs once; a new revision walks again. + app.run("select.set", json!({"ids": [inst, scaled]})).unwrap(); + let before = scans(); + cached_flags(&mut app); + cached_flags(&mut app); + assert_eq!(scans(), before + 1); + app.run("select.set", json!({"ids": [inst]})).unwrap(); + cached_flags(&mut app); + assert_eq!(scans(), before + 2); + // Another document has its own uid, so its flags are found again. + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + let plain = id(app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 40, "height": 40})).unwrap()); + app.run("select.set", json!({"ids": [plain]})).unwrap(); + check(&mut app, [false; 3], "another document"); + } + + /// The Properties panel (its Reset quick action) and the Symbols panel (Break Link) share one + /// walk of the selection while the document does not change. + #[test] + fn properties_and_symbols_panels_walk_the_selection_once_per_revision() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + let rect = |app: &mut VectorcraftApp, x: f64| { + app.run("shape.rectangle", json!({"x": x, "y": 10, "width": 40, "height": 40})).unwrap()["id"].as_u64().unwrap() + }; + let ids = [rect(&mut app, 10.0), rect(&mut app, 60.0)]; + let inst = app.run("symbol.new", json!({"name": "S", "ids": ids, "type": "dynamic"})).unwrap()["id"].as_u64().unwrap(); + app.run("symbol.instance.setAppearance", json!({"id": inst, "path": [0], "fill": "#ff0000"})).unwrap(); + app.run("select.set", json!({"ids": [inst]})).unwrap(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let before = scans(); + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| super::super::properties::show(&mut app, ui)); + out.textures_delta.clear(); + assert_eq!(scans(), before + 1, "the Properties panel reads the flags"); + for _ in 0..3 { + let mut out = ctx.run_ui(egui::RawInput::default(), |ui| { + super::super::properties::show(&mut app, ui); + show(&mut app, ui); + }); + out.textures_delta.clear(); + } + assert_eq!(scans(), before + 1, "one walk for both panels over four frames"); + assert_eq!(cached_flags(&mut app), [true, true, false]); + assert_eq!(scans(), before + 1); + } + /// F8 is Symbol Options… (`ui.symbolOptions`) by default, on every platform. Shift+F8 and Cmd+F8 /// are still the Transform and Info panels' keys, and Cmd+Shift+F8 is still Edit Pattern's. No /// other command, tool or panel has F8 by default. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index ef83de54ad..1c16a48e04 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1103,6 +1103,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **The Symbols panel reads its current symbol from the document:** the Symbols panel and its panel menu read the current symbol on each frame without running `symbol.list`, which counts every symbol's instances by walking the whole document. The current symbol they show and act on is the one `symbol.list` reports, and an idle frame of the panel or its menu runs no command, so on macOS the native menu is not brought up to date on every frame while the panel is open. In a document with 200 symbols and 50,000 objects, the read takes 0.035 µs instead of 48.5 ms in a release build (thread CPU time on Linux, median of 7 runs); in a small document the difference is too small to notice. Tests: `tests::brushsym::current_symbol_is_the_current_symbol_list_answers`, `panels::symbols::tests::current_is_the_current_symbol_list_answers`, `panels::symbols::tests::idle_frames_of_the_panel_and_its_menu_run_no_command`; the timing probe is `panels::symbols::tests::current_symbol_read_timing`. - **Expand of symbol instances:** Object › Expand turns selected symbol instances (without effects, not in perspective, in groups or placed documents too) into their art as Break Link to Symbol places it, one level deep, as one undo step; the Expand dialog's Fill and Stroke reach that art (`object.expand`, `crates/engine/src/tests/expand_symbols.rs`; estimated, score unchanged). - **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`. + - **The Symbols and Properties panels find selected symbol instances once per revision:** whether the selection or its groups hold a symbol instance (Break Link to Symbol), one with appearance changes of its own (Reset Symbol Instance and the Properties panel's Reset), or one Reset Transformation would change is worked out in one walk of the selected objects for each document revision, and later frames reuse it. The buttons and menu items are enabled as before. With one selected group of 300,000 paths, the two panels' reads took a median 5.1 to 5.7 ms of thread CPU time per frame; the first read after a change now takes about 3 ms and later frames about 5 ns (Linux, opt-level 3, median of 7 runs). In a small document the difference is too small to notice. Tests: `panels::symbols::tests::instance_flags_are_found_once_per_revision_and_match_a_walk_of_the_selection`, `properties_and_symbols_panels_walk_the_selection_once_per_revision`. - **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, Ink and Wash, Calligraphic Nibs, Bristle Brushes, Pattern Borders, Scatter Shapes, Game Trails, Energy Beams, Dry Media, Tech Circuit) 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; Ink and Wash adds ink and wash brushes (the [help page](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html) lists an Ink brush library of strokes with varied thickness and texture; the names, shapes and opacities are VectorCraft's own): Tapered Ink, an art brush broad near its start that thins to a fine tip; Brush Pen, a calligraphic brush whose size follows the pen pressure; and Soft Wash and Pooling Wash, art brushes of translucent gray layers that take the stroke color as tints; Game Trails adds motion art brushes (Speed Line, Dash Trail, Burst Ray, Zigzag); Energy Beams adds laser and plasma art brushes (Laser Bolt, Plasma Arc, Charge Wave, Spark Trail); Dry Media adds grainy art brushes (Chalk Grain, Graphite Pencil, Wax Crayon, Charcoal Dust). 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`. - **Bristle Brushes library** ([What's new](https://helpx.adobe.com/illustrator/desktop/new-features/whats-new.html), [About brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html)): Window › Brush Libraries › Bristle Brushes holds ten bristle brushes, one for each tip shape (Fine Liner, Pointed Flat, Stubby Round, Dry Scrub, Soft Dome, Filbert, Angled Round, Angled Flat, Fan Blender, Grass Fan). The brushes, their names and their values are VectorCraft's own, and every value lies inside the range the bristle brush keeps (`brush.libraries`, `brush.addFromLibrary`; `the_bristle_brushes_library_covers_every_tip_shape_within_the_bristle_ranges`). From b16e5f633e943889639700cfa48dd4c13769fc59 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 17 Nov 2026 16:15:56 -0800 Subject: [PATCH 153/176] Docs: SVG export's single type layout is for its writers The progress line now says that the writers share one layout of each type object, and that the check for glyphs hanging outside a path's brackets and the advances a reader gives live text can still lay out a changed copy. --- docs/target-app-parity.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 45bbff0c80..ff938202c8 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1973,7 +1973,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur `.ai` and EPS editing-data import reads a text document whose keys are written by name, as files saved for version 11 write them, and the keys that later files write by name among the numbered ones (a font record's version, a paragraph's direction). The type of such a file comes from its text document, so type outside the artboards opens and each text object keeps its own story A run that names its paragraph or character style by the style's number takes that style (`a_text_document_with_named_keys_gives_type_off_the_page_too`, `a_text_document_with_named_keys_takes_a_runs_style_by_its_number`, `crates/eps/src/import/ate/names.rs`). In SVG export without Fewer `<tspan>` Elements, each character of live type that justification or Mojikumi moves (the letter gaps of a Justify All line without word spaces, the gaps between the characters of a justified Japanese line, closed-up punctuation, the space between Japanese and Latin letters) starts its own positioned `<tspan>`, and type scaled horizontally on a justified line is stretched to its own width (`crates/svg/tests/it/text_layout.rs`). To find those characters, SVG export lays a type object out a second time only when the second layout can differ from the first: point type with Line-end Punctuation Half Width and no Japanese punctuation or letters, the setting new type gets, is laid out once. Exporting 5,000 such objects takes a median of 109.4 ms instead of 171.5 ms on Windows 11, with the same SVG (`crates/svg/src/export/text/tests.rs`). - SVG export lays each type object out once and draws that layout in all of its writers (live text, type on a path, outlines, and inside or outside character strokes), and groups the glyphs of type written as outlines or with such strokes by run in one pass, with the same SVG. Exporting 1,000 objects of type on a path, 1,000 of bidirectional type and 300 with an outside character stroke lays type out 2,300 times instead of 4,900 and takes a median of 665 ms of CPU time instead of 893 ms over seven runs each, alternating, on Linux; grouping the glyphs of 300 texts of 1,000 runs by run takes 10 ms instead of 190 ms (`crates/svg/src/export/text/tests.rs`). + SVG export lays each type object out once for all of its writers and draws that one layout in each of them (live text, type on a path, outlines, and inside or outside character strokes). Two checks still lay out a changed copy of the type: the check for glyphs hanging outside the brackets of type on a path with Optical Margin Alignment or Roman Hanging Punctuation on, and the advances a reader gives live text when they differ from the drawn layout. The export also groups the glyphs of type written as outlines or with such strokes by run in one pass, with the same SVG. Exporting 1,000 objects of type on a path, 1,000 of bidirectional type and 300 with an outside character stroke lays type out 2,300 times instead of 4,900 and takes a median of 665 ms of CPU time instead of 893 ms over seven runs each, alternating, on Linux; grouping the glyphs of 300 texts of 1,000 runs by run takes 10 ms instead of 190 ms (`crates/svg/src/export/text/tests.rs`). SVG export (live text), legacy `.ai` saves (text objects), DXF export (`TEXT` entities) and the CSS Properties panel write area type that Shrink Text to Fit scales down at the size it draws at, and scale its tracking, kerning, leading and baseline shifts the same way where the format holds them. Legacy `.ai` saves (version 7) write type with rotated characters (Character Rotation, Touch Type turns) as its outlines, with a warning that it is no longer editable text (unless `outlineText` already asks for every type object as outlines): a version 7 text object has no character rotation ([Adobe Illustrator File Format Specification 7.0](https://www.nationalarchives.gov.uk/PRONOM/fmt/423), §15), and the outlines keep each character's rotation, baseline shift and scale (`legacy_ai::tests::type_with_rotated_characters_is_outlines_that_keep_the_rotation`). Legacy `.ai` type keeps its manual kerning pairs (`Tk`, `TK`), its discretionary hyphens (`T+`, `T-`) as soft hyphens and its hyphenation language (`XL`) when it opens, and legacy `.ai` saves write manual kerning as `Tk` and soft hyphens as `T+` ([file format specification, version 7](https://web.archive.org/web/20050126105313/https://partners.adobe.com/public/developer/en/illustrator/sdk/AI7FileFormat.pdf), §15.4.6.1, §15.4.10.1 and §22.6). A file whose type sets a line breaking value (`TG`) or Japanese layout rules (`Xu`, `Tu`), which VectorCraft doesn't keep, opens with a warning for each (`import::ai::tests::legacy_manual_pair_kerning_is_kept`, `legacy_line_breaking_and_japanese_layout_rules_are_warned_once`, `legacy_ai::tests::manual_kerning_and_soft_hyphens_are_written_and_read_back`). From de501d73f2aac7d79a5a85e0ade6cadf142267a0 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 17 Nov 2026 16:20:14 -0800 Subject: [PATCH 154/176] PDF export: Patch::apply finds where each object moved with a binary search Patch::apply wrote each cross-reference entry by walking every edit, so a pass with many edits took time in proportion to objects times edits. It now keeps the running total of the length changes and finds, by binary search over the edits' ends, how far each object moved. For every edit set that apply still accepts, the written file is byte for byte the same. An offset that no longer fits the ten digits of a cross-reference entry (ISO 32000-1, 7.5.4) is now refused with an error instead of writing an eleven-digit entry that breaks the table. A change in length too large for an isize is refused with an error instead of wrapping. --- crates/pdf/src/patch.rs | 326 +++++++++++++++++++++++++++++++++++++++- 1 file changed, 319 insertions(+), 7 deletions(-) diff --git a/crates/pdf/src/patch.rs b/crates/pdf/src/patch.rs index 8b9d69b908..9235f22cea 100644 --- a/crates/pdf/src/patch.rs +++ b/crates/pdf/src/patch.rs @@ -107,6 +107,42 @@ impl Xref { /// A replacement of bytes `start..end` of the file. type Edit = (usize, usize, Vec<u8>); +/// Where byte offsets of the old file land in the new one, for edits sorted by start that do not +/// overlap, whose ends therefore never decrease. +struct Moves { + /// Each edit's end, in order. + ends: Vec<usize>, + /// The change in length made by the edits up to and including each one. + shifts: Vec<isize>, +} + +impl Moves { + /// `None` when a change in length doesn't fit an `isize`. + fn new(edits: &[Edit]) -> Option<Self> { + let mut total: isize = 0; + let mut shifts = Vec::with_capacity(edits.len()); + for (start, end, new) in edits { + let removed = isize::try_from(end.checked_sub(*start)?).ok()?; + total = total.checked_add(isize::try_from(new.len()).ok()?)?.checked_sub(removed)?; + shifts.push(total); + } + Some(Self { ends: edits.iter().map(|e| e.1).collect(), shifts }) + } + + /// Where `off` lands: moved by every edit that ends at or before it. + fn at(&self, off: usize) -> Option<usize> { + match self.ends.partition_point(|&end| end <= off) { + 0 => Some(off), + n => off.checked_add_signed(*self.shifts.get(n - 1)?), + } + } +} + +/// `off` as the ten digits of a cross-reference entry; `None` past what ten digits hold. +fn entry_offset(off: usize) -> Option<String> { + (u64::try_from(off).ok()? < 10_000_000_000).then(|| format!("{off:010}")) +} + /// The edits of one PDF, applied together by [`Self::apply`]. pub(crate) struct Patch { edits: Vec<Edit>, @@ -139,18 +175,17 @@ impl Patch { } /// `pdf` with the edits, new objects and trailer entries, and a cross-reference table that - /// matches. Refused when an edit overlaps another or reaches past the objects. + /// matches. Refused when an edit overlaps another or reaches past the objects, or when an + /// object would start past the ten digits a cross-reference entry gives its offset in. pub fn apply(mut self, pdf: &[u8], xref: &Xref) -> Result<Vec<u8>, PdfError> { let bad = |why: &str| PdfError::Write(format!("can't edit the written PDF: {why}")); self.edits.sort_by_key(|e| (e.0, e.1)); if self.edits.windows(2).any(|w| w[0].1 > w[1].0) || self.edits.iter().any(|e| e.0 > e.1 || e.1 > xref.at) { return Err(bad("edits overlap")); } - // Where a byte offset of the old file lands in the new one. let edits = &self.edits; - let moved = |off: usize| -> usize { - edits.iter().filter(|e| e.1 <= off).fold(off as isize, |o, e| o + e.2.len() as isize - (e.1 - e.0) as isize) as usize - }; + let moves = Moves::new(edits).ok_or_else(|| bad("edits too large"))?; + let too_far = || bad("an object lies past what the cross-reference table holds"); let added: usize = self.edits.iter().map(|e| e.2.len()).sum::<usize>() + self.objects.iter().map(|o| o.len() + 32).sum::<usize>(); let mut out = Vec::with_capacity(pdf.len() + added + 64); let mut at = 0; @@ -175,7 +210,7 @@ impl Patch { for e in old.chunks(20) { match number(e, 0) { Some((off, _)) if e.get(17) == Some(&b'n') => { - out.extend_from_slice(format!("{:010}", moved(off)).as_bytes()); + out.extend_from_slice(moves.at(off).and_then(entry_offset).ok_or_else(too_far)?.as_bytes()); out.extend_from_slice(e.get(10..).unwrap_or_default()); } _ => out.extend_from_slice(e), @@ -183,7 +218,8 @@ impl Patch { } let eol = old.get(18..20).unwrap_or(b"\r\n"); for off in offsets { - out.extend_from_slice(format!("{off:010} 00000 n").as_bytes()); + out.extend_from_slice(entry_offset(off).ok_or_else(too_far)?.as_bytes()); + out.extend_from_slice(b" 00000 n"); out.extend_from_slice(eol); } // The trailer, with its size and the new entries. @@ -201,3 +237,279 @@ impl Patch { Ok(out) } } + +#[cfg(test)] +mod tests { + use super::*; + use std::time::{Duration, Instant}; + + /// A PDF written as the export writes one: objects `<< /N n >>` numbered from 1, those `free` + /// picks left out with a free entry, then one cross-reference table and the trailer. + fn written(count: usize, free: impl Fn(usize) -> bool) -> Vec<u8> { + let mut pdf = b"%PDF-1.7\n".to_vec(); + let mut entries = b"0000000000 65535 f\r\n".to_vec(); + for n in 1..=count { + if free(n) { + entries.extend_from_slice(b"0000000000 00001 f\r\n"); + continue; + } + entries.extend(format!("{:010} 00000 n\r\n", pdf.len()).bytes()); + pdf.extend(format!("{n} 0 obj\n<< /N {n} >>\nendobj\n").bytes()); + } + let at = pdf.len(); + pdf.extend(format!("xref\n0 {}\n", count + 1).bytes()); + pdf.extend(entries); + pdf.extend(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{at}\n%%EOF", count + 1).bytes()); + pdf + } + + /// A small linear congruential generator, so every run makes the same edits. + struct Rng(u64); + + impl Rng { + /// A number in `0..n` (0 when `n` is 0). + fn below(&mut self, n: usize) -> usize { + self.0 = self.0.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1_442_695_040_888_963_407); + usize::try_from(self.0 >> 33).unwrap() % n.max(1) + } + + fn bytes(&mut self) -> Vec<u8> { + (0..self.below(9)).map(|i| b'a' + u8::try_from(i).unwrap()).collect() + } + } + + /// About `wanted` edits that don't overlap, in shuffled order, at random places among the + /// objects and at object starts: replacements that grow, shrink or remove bytes, edits that end + /// at an object's start, and inserts, several of them at one place. None when `wanted` is 0. + fn edits(pdf: &[u8], xref: &Xref, rng: &mut Rng, wanted: usize) -> Vec<Edit> { + if wanted == 0 { + return vec![]; + } + let first = b"%PDF-1.7\n".len(); + let mut points: Vec<usize> = xref.objects(pdf).into_iter().map(|(_, off)| off).collect(); + points.extend((0..wanted).map(|_| first + rng.below(xref.at() - first + 1))); + points.push(xref.at()); + points.sort_unstable(); + points.dedup(); + let mut out = vec![]; + for w in points.windows(2) { + let (p, q) = (w[0], w[1]); + match rng.below(6) { + 0 => {} + 1 => out.push((p, q, rng.bytes())), + 2 => out.push((p, p, rng.bytes())), + 3 => { + out.push((p, p, rng.bytes())); + out.push((p, p, rng.bytes())); + out.push((p, q.min(p + rng.below(4)), rng.bytes())); + } + 4 => out.push((p + (q - p) / 2, q, rng.bytes())), + _ => out.push((q, q, rng.bytes())), + } + } + for i in (1..out.len()).rev() { + out.swap(i, rng.below(i + 1)); + } + out + } + + fn patch(xref: &Xref, edits: &[Edit], objects: bool) -> Patch { + let mut patch = Patch::new(xref); + for (start, end, with) in edits { + patch.replace(*start, *end, with.clone()); + } + if objects { + patch.add_object(b"<< /Added 1 >>".to_vec()); + patch.trailer_entry(b" /Info 2 0 R"); + } + patch + } + + /// Where `off` lands, by walking every edit: how [`Patch::apply`] found it before [`Moves`]. + fn scan(edits: &[Edit], off: usize) -> usize { + edits.iter().filter(|e| e.1 <= off).fold(off as isize, |o, e| o + e.2.len() as isize - (e.1 - e.0) as isize) as usize + } + + /// [`Patch::apply`] as it was written before [`Moves`], walking every edit for every object. + fn apply_by_scan(mut patch: Patch, pdf: &[u8], xref: &Xref) -> Result<Vec<u8>, PdfError> { + let bad = |why: &str| PdfError::Write(format!("can't edit the written PDF: {why}")); + patch.edits.sort_by_key(|e| (e.0, e.1)); + if patch.edits.windows(2).any(|w| w[0].1 > w[1].0) || patch.edits.iter().any(|e| e.0 > e.1 || e.1 > xref.at) { + return Err(bad("edits overlap")); + } + let edits = &patch.edits; + let moved = |off: usize| -> usize { scan(edits, off) }; + let added: usize = patch.edits.iter().map(|e| e.2.len()).sum::<usize>() + patch.objects.iter().map(|o| o.len() + 32).sum::<usize>(); + let mut out = Vec::with_capacity(pdf.len() + added + 64); + let mut at = 0; + for (start, end, new) in edits.iter() { + out.extend_from_slice(pdf.get(at..*start).ok_or_else(|| bad("bad edit"))?); + out.extend_from_slice(new); + at = *end; + } + out.extend_from_slice(pdf.get(at..xref.at).ok_or_else(|| bad("bad edit"))?); + let mut offsets = Vec::with_capacity(patch.objects.len()); + for (i, body) in patch.objects.iter().enumerate() { + offsets.push(out.len()); + out.extend_from_slice(format!("{} 0 obj\n", patch.size + i).as_bytes()); + out.extend_from_slice(body); + out.extend_from_slice(b"\nendobj\n"); + } + let table = out.len(); + let size = patch.size + patch.objects.len(); + out.extend_from_slice(format!("xref\n0 {size}\n").as_bytes()); + let old = pdf.get(xref.entries..xref.entries + 20 * xref.count).ok_or_else(|| bad("bad cross-reference table"))?; + for e in old.chunks(20) { + match number(e, 0) { + Some((off, _)) if e.get(17) == Some(&b'n') => { + out.extend_from_slice(format!("{:010}", moved(off)).as_bytes()); + out.extend_from_slice(e.get(10..).unwrap_or_default()); + } + _ => out.extend_from_slice(e), + } + } + let eol = old.get(18..20).unwrap_or(b"\r\n"); + for off in offsets { + out.extend_from_slice(format!("{off:010} 00000 n").as_bytes()); + out.extend_from_slice(eol); + } + let (ts, te) = xref.trailer; + let dict = pdf.get(ts..te.saturating_sub(2)).ok_or_else(|| bad("bad trailer"))?; + let size_at = find(dict, b"/Size", 0).ok_or_else(|| bad("the trailer has no size"))? + 5; + let (_, size_end) = number(dict, size_at).ok_or_else(|| bad("the trailer has no size"))?; + let (Some(head), Some(tail)) = (dict.get(..size_at), dict.get(size_end..)) else { return Err(bad("bad trailer")) }; + out.extend_from_slice(b"trailer\n"); + out.extend_from_slice(head); + out.extend_from_slice(format!(" {size}").as_bytes()); + out.extend_from_slice(tail); + out.extend_from_slice(&patch.trailer); + out.extend_from_slice(format!(">>\nstartxref\n{table}\n%%EOF").as_bytes()); + Ok(out) + } + + #[test] + fn every_offset_moves_by_the_edits_that_end_at_or_before_it() { + let mut rng = Rng(7661); + for round in 0..100 { + let pdf = written(1 + rng.below(30), |n| n % 7 == 3); + let xref = Xref::read(&pdf).unwrap(); + let mut edits = edits(&pdf, &xref, &mut rng, [0, 1, 3, 20, 80][round % 5]); + edits.sort_by_key(|e| (e.0, e.1)); + let moves = Moves::new(&edits).unwrap(); + for off in 0..=pdf.len() { + assert_eq!(moves.at(off), Some(scan(&edits, off)), "round {round}, offset {off}, edits {edits:?}"); + } + } + } + + #[test] + fn apply_writes_the_bytes_a_walk_of_every_edit_wrote() { + let mut rng = Rng(1378); + for round in 0..300 { + let pdf = written(1 + rng.below(40), |n| n % 7 == 3); + let xref = Xref::read(&pdf).unwrap(); + let edits = edits(&pdf, &xref, &mut rng, [0, 1, 3, 20, 80][round % 5]); + let objects = round % 3 == 0; + let fast = patch(&xref, &edits, objects).apply(&pdf, &xref).unwrap(); + let walked = apply_by_scan(patch(&xref, &edits, objects), &pdf, &xref).unwrap(); + assert_eq!(String::from_utf8_lossy(&fast), String::from_utf8_lossy(&walked), "round {round}"); + } + } + + #[test] + fn every_entry_points_at_its_object_after_the_edits() { + let pdf = written(30, |n| n % 7 == 3); + let xref = Xref::read(&pdf).unwrap(); + let mut patch = Patch::new(&xref); + for (n, off) in xref.objects(&pdf) { + let (at, end) = xref.dict(&pdf, n).unwrap(); + match n % 4 { + 0 => patch.replace(at, at, b" /Grown [1 2 3]".to_vec()), + 1 => patch.replace(at, end, b">>\n".to_vec()), + // An insert at an object's start goes before the object. + 2 => patch.replace(off, off, b"% before\n".to_vec()), + _ => {} + } + } + let added = patch.add_object(b"<< /Added 1 >>".to_vec()); + let out = patch.apply(&pdf, &xref).unwrap(); + let after = Xref::read(&out).unwrap(); + assert_eq!((after.count(), added), (32, 31)); + for n in 1..32u32 { + let Some(off) = after.offset(&out, n) else { + assert!(n % 7 == 3, "object {n} is in use"); + let e = xref.entries + 20 * n as usize; + assert_eq!(out[after.entries + 20 * n as usize..][..20], pdf[e..e + 20], "free entry {n}"); + continue; + }; + assert!(out[off..].starts_with(format!("{n} 0 obj\n").as_bytes()), "object {n} at {off}"); + } + } + + #[test] + fn an_object_moved_past_ten_digits_is_refused() { + let mut pdf = written(2, |_| false); + let entry = Xref::read(&pdf).unwrap().entries + 40; + // Object 2's entry gives the last offset ten digits hold. + pdf[entry..entry + 10].copy_from_slice(b"9999999999"); + let xref = Xref::read(&pdf).unwrap(); + let out = Patch::new(&xref).apply(&pdf, &xref).unwrap(); + assert!(find(&out, b"9999999999 00000 n\r\n", 0).is_some()); + let mut patch = Patch::new(&xref); + patch.replace(9, 9, b"%\n".to_vec()); + let refused = patch.apply(&pdf, &xref); + assert!(matches!(&refused, Err(PdfError::Write(why)) if why.contains("cross-reference table holds")), "{refused:?}"); + } + + /// CPU time this thread has used, where the system reports it (`/proc` on Linux). + fn thread_cpu() -> Option<Duration> { + let stat = std::fs::read_to_string("/proc/thread-self/schedstat").ok()?; + stat.split_whitespace().next()?.parse().ok().map(Duration::from_nanos) + } + + /// How long `f` takes, in thread CPU time where the system reports it, else wall time. + fn time<T>(f: impl FnOnce() -> T) -> (Duration, T) { + let (cpu, wall) = (thread_cpu(), Instant::now()); + let out = f(); + (thread_cpu().zip(cpu).map_or_else(|| wall.elapsed(), |(b, a)| b.saturating_sub(a)), out) + } + + fn median(mut runs: Vec<Duration>) -> Duration { + runs.sort_unstable(); + runs[runs.len() / 2] + } + + /// `cargo test --release -p vectorcraft-pdf --lib patch::tests::bench -- --ignored --nocapture`. + /// The edits are those of forms in overprint: two inside each form's stream (its `/Length` and + /// data) and an insert into its dictionary, for `n` forms among `n + 20` objects. Each run + /// applies the patch `reps` times, so that small files take long enough for the clock. + #[test] + #[ignore = "timing; run explicitly"] + fn bench_apply_with_many_edits() { + println!("clock: {}", if thread_cpu().is_some() { "thread CPU time" } else { "wall time" }); + println!("| forms | objects | edits | walk every edit (median of 7) | binary search (median of 7) |"); + println!("| ---: | ---: | ---: | ---: | ---: |"); + for n in [100, 1_000, 5_000, 20_000] { + let pdf = written(n + 20, |_| false); + let xref = Xref::read(&pdf).unwrap(); + let mut edits = vec![]; + for (obj, _) in xref.objects(&pdf).into_iter().take(n) { + let (at, _) = xref.dict(&pdf, obj).unwrap(); + edits.push((at, at + 1, b" /Length 120 ".to_vec())); + edits.push((at + 1, at + 3, b"/Data".to_vec())); + edits.push((at + 3, at + 3, b" /Resources << /ExtGState << /GS0 9 0 R >> >>".to_vec())); + } + let reps = (200_000_000 / (3 * n * n)).clamp(1, 2_000); + let (mut walked, mut searched) = (vec![], vec![]); + for _ in 0..7 { + let (t, old) = time(|| (0..reps).fold(None, |_, _| apply_by_scan(patch(&xref, &edits, false), &pdf, &xref).ok())); + walked.push(t); + let (t, new) = time(|| (0..reps).fold(None, |_, _| patch(&xref, &edits, false).apply(&pdf, &xref).ok())); + searched.push(t); + assert!(old.is_some() && old == new, "{n} forms: the files differ"); + } + let ms = |d: Duration| d.as_secs_f64() * 1000.0 / reps as f64; + println!("| {n} | {} | {} | {:.3} ms | {:.3} ms |", n + 20, edits.len(), ms(median(walked)), ms(median(searched))); + } + } +} From ed0a241b7d413b46cd128d2aad9595f5f478aa44 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 17 Nov 2026 16:27:47 -0800 Subject: [PATCH 155/176] Brushes: Make bristle strokes follow recorded pen pose --- crates/brush/src/calli.rs | 104 ++++++++++++++++++++++++++-- crates/brush/src/lib.rs | 2 +- crates/brush/src/tests.rs | 80 +++++++++++++++++++++ crates/engine/src/tests/brushsym.rs | 28 ++++++++ docs/target-app-parity.md | 1 + 5 files changed, 208 insertions(+), 7 deletions(-) diff --git a/crates/brush/src/calli.rs b/crates/brush/src/calli.rs index 888294356c..69a8463c92 100644 --- a/crates/brush/src/calli.rs +++ b/crates/brush/src/calli.rs @@ -9,7 +9,6 @@ //! the stroke with what the pen recorded on it (`StrokeLayer::pressure`, `tilt`, `bearing` and //! `rotation`): the sweep is sampled densely and each sample takes the nib for the pen there. -use vectorcraft_color::Paint; use vectorcraft_doc::{Node, StrokeLayer}; use vectorcraft_geom::{BezPath, PathData, Point, SubPath, Vec2}; @@ -198,7 +197,70 @@ fn offset_track(t: &Track, d: f64, trim0: f64, trim1: f64) -> Option<BezPath> { Some(bp) } -pub(crate) fn bristle(b: &Bristle, bp: &BezPath, weight: f64, paint: &Paint, name: &str) -> Vec<Node> { +/// A strand that follows the recorded pen pose. Pressure and tilt change its spread; bearing and +/// barrel rotation turn that spread in the path's local frame. Original path corners are included +/// in the samples so a turn is not rounded away by the pose sampling interval. +fn posed_bristle_track( + t: &Track, + d: f64, + trim0: f64, + trim1: f64, + size: f64, + stroke: &StrokeLayer, + varies: bool, +) -> Option<(BezPath, Vec<(f64, f64)>)> { + let l = t.len(); + let (s0, s1) = (trim0.clamp(0.0, l), (l - trim1).clamp(0.0, l)); + if s1 - s0 < 1e-6 { + return None; + } + let steps = if varies { ((s1 - s0) / (size * 0.2).max(0.25)).ceil().clamp(1.0, MAX_STEPS) as usize } else { 1 }; + let mut positions: Vec<f64> = (0..=steps).map(|i| s0 + (s1 - s0) * i as f64 / steps as f64).collect(); + positions.extend(t.cum.iter().copied().filter(|&s| s > s0 && s < s1)); + positions.sort_by(f64::total_cmp); + positions.dedup_by(|a, b| (*a - *b).abs() < 1e-6); + let mut path = BezPath::new(); + // Distance along the posed strand -> fraction along the original, untrimmed path. + let mut source = Vec::with_capacity(positions.len()); + let mut previous: Option<Point> = None; + let mut distance = 0.0; + for (i, s) in positions.into_iter().enumerate() { + let pen = PenAt::of(stroke, s / l); + let pressure = pen.control(Variation::Pressure).unwrap_or(0.5); + let tilt = pen.control(Variation::Tilt).unwrap_or(0.5); + let bearing = pen.control(Variation::Bearing).unwrap_or(0.5); + let rotation = pen.control(Variation::Rotation).unwrap_or(0.5); + let spread = d * (0.5 + pressure) * (1.25 - 0.5 * tilt); + let angle = std::f64::consts::TAU * (bearing + rotation - 1.0); + let p = t.map(s + spread * angle.sin(), spread * angle.cos()); + if i == 0 { + path.move_to(p) + } else { + path.line_to(p) + } + if let Some(previous) = previous { + distance += previous.distance(p); + } + source.push((distance, s / l)); + previous = Some(p); + } + Some((path, source)) +} + +fn source_fraction(source: &[(f64, f64)], distance: f64) -> f64 { + let next = source.partition_point(|(d, _)| *d < distance); + if next == 0 { + return source.first().map_or(0.0, |(_, f)| *f); + } + if next >= source.len() { + return source.last().map_or(1.0, |(_, f)| *f); + } + let (d0, f0) = source[next - 1]; + let (d1, f1) = source[next]; + if d1 - d0 < 1e-9 { f1 } else { f0 + (f1 - f0) * ((distance - d0) / (d1 - d0)) } +} + +pub(crate) fn bristle(b: &Bristle, bp: &BezPath, weight: f64, stroke: &StrokeLayer, name: &str) -> Vec<Node> { let mut rng = Rng::new(seed_of(bp, name)); let size = b.size.max(0.1) * weight; let strands = (3.0 + b.density.clamp(1.0, 100.0) / 100.0 * 13.0).round() as usize; @@ -210,6 +272,13 @@ pub(crate) fn bristle(b: &Bristle, bp: &BezPath, weight: f64, paint: &Paint, nam let wobble = (100.0 - b.stiffness.clamp(1.0, 100.0)) / 100.0; let ragged = b.length.clamp(25.0, 300.0) / 100.0; let opacity = (b.opacity.clamp(1.0, 100.0) / 100.0) as f32; + let posed = stroke.pressure.is_some() || stroke.tilt.is_some() || stroke.bearing.is_some() || stroke.rotation.is_some(); + let varies = |points: &[(f64, f64)]| points.first().is_some_and(|(_, first)| points.iter().any(|(_, value)| (value - first).abs() > 1e-6)); + let pressure_varies = stroke.pressure.as_ref().is_some_and(|p| varies(&p.points)); + let pose_varies = pressure_varies + || stroke.tilt.as_ref().is_some_and(|p| varies(&p.points)) + || stroke.bearing.as_ref().is_some_and(|p| varies(&p.points)) + || stroke.rotation.as_ref().is_some_and(|p| varies(&p.points)); let mut out = vec![]; for t in tracks(bp, tolerance(size)) { let l = t.len(); @@ -220,14 +289,37 @@ pub(crate) fn bristle(b: &Bristle, bp: &BezPath, weight: f64, paint: &Paint, nam let edge = 1.0 - lane.abs(); let trim = |r: &mut Rng| r.unit() * ragged * size * (1.2 - edge) * 0.8; let (t0, t1) = (trim(&mut rng), trim(&mut rng)); - let Some(sp) = offset_track(&t, off, t0.min(l * 0.3), t1.min(l * 0.3)) else { continue }; + let (t0, t1) = (t0.min(l * 0.3), t1.min(l * 0.3)); + let sp = if posed { + posed_bristle_track(&t, off, t0, t1, size, stroke, pose_varies) + } else { + offset_track(&t, off, t0, t1).map(|path| (path, Vec::new())) + }; + let Some((sp, source)) = sp else { continue }; let w = thick * (0.6 + 0.4 * edge) * rng.range(0.8, 1.2); - let nib = Nib::new(0.0, 1.0, w); - let subs: Vec<SubPath> = tracks(&sp, tolerance(w)).iter().flat_map(|tt| sweep(tt, &|_| nib, None)).collect(); + let subs: Vec<SubPath> = tracks(&sp, tolerance(w)) + .iter() + .flat_map(|tt| { + if posed { + sweep( + tt, + &|f| { + let original_fraction = source_fraction(&source, f * tt.len()); + let pressure = PenAt::of(stroke, original_fraction).control(Variation::Pressure).unwrap_or(0.5); + Nib::new(0.0, 1.0, w * (0.5 + pressure)) + }, + pressure_varies.then_some((tt.len() / MAX_STEPS).max(0.25)), + ) + } else { + let nib = Nib::new(0.0, 1.0, w); + sweep(tt, &|_| nib, None) + } + }) + .collect(); if subs.is_empty() { continue; } - let mut n = filled(PathData::new(subs), paint); + let mut n = filled(PathData::new(subs), &stroke.paint); n.opacity = (opacity * rng.range(0.7, 1.0) as f32).clamp(0.0, 1.0); out.push(n); } diff --git a/crates/brush/src/lib.rs b/crates/brush/src/lib.rs index 0b48f586cd..ff3a9248e7 100644 --- a/crates/brush/src/lib.rs +++ b/crates/brush/src/lib.rs @@ -847,7 +847,7 @@ pub fn stroke_pieces(doc: &Document, brush: &Brush, bp: &BezPath, stroke: &Strok let w = if stroke.width > 0.0 { stroke.width } else { 1.0 }; let mut out = match &brush.kind { BrushKind::Calligraphic(c) => calli::calligraphic(c, bp, w, stroke, &brush.name), - BrushKind::Bristle(b) => calli::bristle(b, bp, w, &stroke.paint, &brush.name), + BrushKind::Bristle(b) => calli::bristle(b, bp, w, stroke, &brush.name), BrushKind::Art(a) => warp::art(a, bp, w, stroke), BrushKind::Scatter(s) => warp::scatter(s, bp, w, stroke, &brush.name), BrushKind::Pattern(p) => warp::pattern(p, bp, w), diff --git a/crates/brush/src/tests.rs b/crates/brush/src/tests.rs index de178c76ac..fa3df98a34 100644 --- a/crates/brush/src/tests.rs +++ b/crates/brush/src/tests.rs @@ -826,6 +826,86 @@ fn bristle_makes_translucent_strands() { assert!(bb.height() <= 6.0 * 1.3 && bb.height() >= 3.0, "{bb:?}"); } +#[test] +fn bristle_pen_pressure_changes_its_footprint() { + let b = Brush { name: "b".into(), kind: BrushKind::Bristle(Bristle::default()) }; + let render = |pressure| { + let s = StrokeLayer { pressure: Some(vectorcraft_doc::PressureProfile { points: vec![(0.0, pressure), (1.0, pressure)] }), ..stroke(1.0) }; + stroke_pieces(&Document::new(1.0, 1.0), &b, &line(0.0, 0.0, 200.0, 0.0), &s) + }; + let light = render(0.0); + let heavy = render(1.0); + assert_eq!(light.len(), heavy.len()); + assert!(bounds(&heavy).height() > bounds(&light).height() * 1.8); +} + +#[test] +fn bristle_pen_pressure_is_sampled_along_the_stroke() { + let b = Brush { name: "b".into(), kind: BrushKind::Bristle(Bristle::default()) }; + let s = StrokeLayer { pressure: Some(vectorcraft_doc::PressureProfile { points: vec![(0.0, 0.0), (1.0, 1.0)] }), ..stroke(1.0) }; + let out = stroke_pieces(&Document::new(1.0, 1.0), &b, &line(0.0, 0.0, 200.0, 0.0), &s); + let mut points = Vec::new(); + for n in &out { + all_points(n, &mut points); + } + let early = points.iter().filter(|p| p.x > 20.0 && p.x < 60.0).map(|p| p.y.abs()).fold(0.0_f64, f64::max); + let late = points.iter().filter(|p| p.x > 140.0 && p.x < 180.0).map(|p| p.y.abs()).fold(0.0_f64, f64::max); + assert!(late > early * 1.4, "spread along stroke: {early} -> {late}"); +} + +#[test] +fn trimmed_bristle_strands_read_pressure_where_they_begin() { + let b = Brush { name: "b".into(), kind: BrushKind::Bristle(Bristle { size: 20.0, length: 300.0, ..Default::default() }) }; + let render = |points| { + let s = StrokeLayer { pressure: Some(vectorcraft_doc::PressureProfile { points }), ..stroke(1.0) }; + stroke_pieces(&Document::new(1.0, 1.0), &b, &line(0.0, 0.0, 80.0, 0.0), &s) + }; + let ramp = render(vec![(0.0, 0.0), (1.0, 1.0)]); + let neutral = render(vec![(0.0, 0.5), (1.0, 0.5)]); + assert_eq!(ramp.len(), neutral.len()); + let start = |n: &Node| { + let anchors = &n.path_data().unwrap().subpaths[0].anchors; + let first = anchors[0].p; + let opposite = anchors[anchors.len() - 16].p; + (first.x, (first.y - opposite.y).abs()) + }; + let mut checked = false; + for (ramp, neutral) in ramp.iter().zip(&neutral) { + let (x, width) = start(ramp); + if x < 12.0 { + continue; + } + let (_, neutral_width) = start(neutral); + let expected = 0.5 + x / 80.0; + assert!(width / neutral_width > expected - 0.08, "strand at {x}: {width} vs {neutral_width}, expected ratio {expected}"); + checked = true; + } + assert!(checked, "at least one strand begins past the pressure ramp's first eighth"); +} + +#[test] +fn bristle_pen_orientation_changes_its_footprint() { + let b = Brush { name: "b".into(), kind: BrushKind::Bristle(Bristle::default()) }; + let render = |tilt, bearing, rotation| { + let flat = |x| vec![(0.0, x), (1.0, x)]; + let s = StrokeLayer { + tilt: Some(vectorcraft_doc::PressureProfile { points: flat(tilt) }), + bearing: Some(vectorcraft_doc::AngleProfile { points: flat(bearing) }), + rotation: Some(vectorcraft_doc::AngleProfile { points: flat(rotation) }), + ..stroke(1.0) + }; + stroke_pieces(&Document::new(1.0, 1.0), &b, &line(0.0, 0.0, 200.0, 0.0), &s) + }; + let neutral = bounds(&render(0.5, 0.0, 0.0)).height(); + let flat = bounds(&render(1.0, 0.0, 0.0)).height(); + let upright = bounds(&render(0.0, 0.0, 0.0)).height(); + let bearing = bounds(&render(0.5, 90.0, 0.0)).height(); + let rotation = bounds(&render(0.5, 0.0, 90.0)).height(); + assert!(flat > neutral && neutral > upright, "tilt: {flat} > {neutral} > {upright}"); + assert!(bearing < neutral * 0.7, "bearing: {bearing} vs {neutral}"); + assert!(rotation < neutral * 0.7, "rotation: {rotation} vs {neutral}"); +} + #[test] fn tints_colorization_uses_stroke_colour() { let b = art_brush(rect_art(10.0, 4.0), ArtScale::Stretch); diff --git a/crates/engine/src/tests/brushsym.rs b/crates/engine/src/tests/brushsym.rs index 77258b7eb7..9f2a47a7f9 100644 --- a/crates/engine/src/tests/brushsym.rs +++ b/crates/engine/src/tests/brushsym.rs @@ -1351,6 +1351,34 @@ fn paintbrush_records_the_pens_tilt_on_the_stroke() { assert_eq!(back.node(pen).unwrap().appearance.stroke(), doc.node(pen).unwrap().appearance.stroke()); } +/// A Bristle path made from pen samples keeps its input when saved and uses it when exported. +#[test] +fn bristle_path_keeps_and_draws_its_pen_pose() { + let mut s = session(); + let id = NodeId( + s.execute( + "brush.freehand", + &json!({"points": [[20, 60, 0.1, 10, 0, 0], [200, 60, 0.9, 35, 0, 90]], "style": "brush", "brush": "Bristle Round"}), + ) + .unwrap()["id"] + .as_u64() + .unwrap(), + ); + let doc: Document = (*s.doc().unwrap().doc).clone(); + let st = doc.node(id).unwrap().appearance.stroke().unwrap(); + assert!(st.pressure.is_some() && st.tilt.is_some() && st.bearing.is_some() && st.rotation.is_some()); + let back = vectorcraft_format::load(&vectorcraft_format::save(&doc, false)).unwrap(); + assert_eq!(back.node(id).unwrap().appearance.stroke(), Some(st)); + + let mut neutral = doc.clone(); + let st = neutral.node_mut(id).unwrap().appearance.stroke_mut().unwrap(); + st.pressure = None; + st.tilt = None; + st.bearing = None; + st.rotation = None; + assert_ne!(vectorcraft_svg::export(&doc, &Default::default()), vectorcraft_svg::export(&neutral, &Default::default())); +} + /// Pen pressure belongs to its path: new art, graphic styles and Brush Options' edits leave it. #[test] fn pressure_stays_with_its_own_path() { diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index ef83de54ad..989979f8b0 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1106,6 +1106,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **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, Ink and Wash, Calligraphic Nibs, Bristle Brushes, Pattern Borders, Scatter Shapes, Game Trails, Energy Beams, Dry Media, Tech Circuit) 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; Ink and Wash adds ink and wash brushes (the [help page](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html) lists an Ink brush library of strokes with varied thickness and texture; the names, shapes and opacities are VectorCraft's own): Tapered Ink, an art brush broad near its start that thins to a fine tip; Brush Pen, a calligraphic brush whose size follows the pen pressure; and Soft Wash and Pooling Wash, art brushes of translucent gray layers that take the stroke color as tints; Game Trails adds motion art brushes (Speed Line, Dash Trail, Burst Ray, Zigzag); Energy Beams adds laser and plasma art brushes (Laser Bolt, Plasma Arc, Charge Wave, Spark Trail); Dry Media adds grainy art brushes (Chalk Grain, Graphite Pencil, Wax Crayon, Charcoal Dust). 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`. - **Bristle Brushes library** ([What's new](https://helpx.adobe.com/illustrator/desktop/new-features/whats-new.html), [About brushes](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html)): Window › Brush Libraries › Bristle Brushes holds ten bristle brushes, one for each tip shape (Fine Liner, Pointed Flat, Stubby Round, Dry Scrub, Soft Dome, Filbert, Angled Round, Angled Flat, Fan Blender, Grass Fan). The brushes, their names and their values are VectorCraft's own, and every value lies inside the range the bristle brush keeps (`brush.libraries`, `brush.addFromLibrary`; `the_bristle_brushes_library_covers_every_tip_shape_within_the_bristle_ranges`). + - **Bristle strokes follow recorded pen input** ([brush documentation](https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=201)): a Bristle brush in VectorCraft widens its strand spread and thickness with pressure along the stroke; pen tilt changes the spread, and bearing and barrel rotation turn it in the path's local frame. Missing pen channels use neutral values, and mouse strokes keep their existing appearance. This is VectorCraft's own rendering model; hardware-specific output has not been verified. `bristle_pen_pressure_changes_its_footprint`, `bristle_pen_pressure_is_sampled_along_the_stroke`, `trimmed_bristle_strands_read_pressure_where_they_begin` and `bristle_pen_orientation_changes_its_footprint` cover the geometry in `crates/brush/src/tests.rs`; `bristle_path_keeps_and_draws_its_pen_pose` covers saving and export in `crates/engine/src/tests/brushsym.rs`; area scores unchanged. - **Tech Circuit library:** Circuit Trace is a chamfered art brush with 45-degree elbows and terminal pads; Bus Lines repeats three parallel conductor lanes; Terminal Nodes repeats solder pads, circular test points and connecting leads. Original vector geometry generated in code, with Tints colorization and continuous pattern tile edges. Evidence: `the_tech_circuit_library_constructs_adds_and_applies_each_brush` in `crates/engine/src/tests/brushlib.rs` covers listing, finite geometry on straight, curved, short and closed paths, add/apply, undo/redo, deduplication and saved-library round trips. G5 remaining estimate 3–13 h (estimated); area scores unchanged. - **Dry Media library** ([help page](https://helpx.adobe.com/illustrator/desktop/paint-and-fill/apply-and-edit-strokes/about-brushes.html)): Window › Brush Libraries › Dry Media holds four art brushes with textured strokes like dry drawing materials, each 100 pt long: Chalk Grain (about 8 pt high), Graphite Pencil (about 2.3 pt), Wax Crayon (about 5.5 pt) and Charcoal Dust (about 7 pt). The brushes, their names, sizes and art are VectorCraft's own: each is filled vector paths from a fixed seed, at most 80 paths and 500 anchors, stretched along the path with Tints colorization, and the chalk and crayon art has even-odd gaps where the paper shows (`brush.libraries`, `brush.addFromLibrary`; `the_dry_media_library_holds_grainy_art_brushes_with_bounded_art`). - **Brush names in library panels**: a built-in brush library's panel shows its brushes' names in the UI language, in its list rows and tooltips, and its Find field matches the name shown or the English name. This is VectorCraft's own rule. A User Defined or Other Library… library's brushes, and the document's Brushes panel, show names as they are stored. A click, a drag, Add to Brushes and `brush.addFromLibrary` still use the English name, so the brush comes into the document under that name (`built_in_library_brushes_are_listed_in_the_ui_language`, `built_in_library_brush_names_are_in_complete_catalogs`). From b4404cceb09d08c2746b76ec4704766707ee618c Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 17 Nov 2026 16:31:15 -0800 Subject: [PATCH 156/176] Rerun CI From fd26667fbfb9608459fd1ce417226f1cea312d5f Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 17 Nov 2026 16:31:16 -0800 Subject: [PATCH 157/176] Rerun CI From 92020b43bc17788ca5e26762d0a22eb67c22bc57 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 17 Nov 2026 16:31:34 -0800 Subject: [PATCH 158/176] Rerun CI From 579b8a031670e9f4cbbd8991e44d7ea835f6d127 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 17 Nov 2026 16:31:36 -0800 Subject: [PATCH 159/176] Rerun CI From 8dabfbabab31fb83f14ae6d6c4b4e85d0caf32a8 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 17 Nov 2026 16:31:45 -0800 Subject: [PATCH 160/176] Rerun CI From 2829343e00ecf98e90cfa268b6df0114dd1ef2ff Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 17 Nov 2026 16:32:03 -0800 Subject: [PATCH 161/176] Rerun CI From afcf8b6f7800ca91def9d515c3a67113d84ab676 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 17 Nov 2026 16:32:15 -0800 Subject: [PATCH 162/176] Rerun CI From f2f33b3a323971ffb518ebad72f8809dd6d198d2 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 17 Nov 2026 16:33:11 -0800 Subject: [PATCH 163/176] Width Point Edit: either half finds its pair as the engine pairs it The dialog paired the points within 1e-6 of the opened point, so with three points each that close to the next it paired the opened point with a different neighbor than stroke.widthPoint.set accepts, and OK failed. It now pairs a point with the next one when they are the only points within 1e-6 of the first one's place, as the engine does, so either half opens the same pair. --- crates/ui-egui/src/dialogs/width_point.rs | 16 ++++++---- .../ui-egui/src/dialogs/width_point/tests.rs | 30 +++++++++++++++++++ 2 files changed, 40 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/dialogs/width_point.rs b/crates/ui-egui/src/dialogs/width_point.rs index f0d2cfb158..0c4c41c356 100644 --- a/crates/ui-egui/src/dialogs/width_point.rs +++ b/crates/ui-egui/src/dialogs/width_point.rs @@ -45,14 +45,18 @@ fn point(app: &VectorcraftApp, id: u64, index: usize) -> Option<(f64, f64, f64)> } /// The incoming and outgoing halves of the discontinuous point that width point `index` of `id` -/// belongs to, or none when no other point shares its place (or more than one does). +/// belongs to, or none when it is a continuous point. As `stroke.widthPoint.set` pairs them, a +/// point `a` and the next one are the two halves when they are the only points within +/// [`SAME_T`] of `a`'s place, so either half finds the same pair. fn halves(app: &VectorcraftApp, id: u64, index: usize) -> Option<(usize, usize)> { let points = &app.session.active()?.doc.node(NodeId(id))?.appearance.stroke()?.profile.as_ref()?.points; - let t = points.get(index)?.0; - match (0..points.len()).filter(|i| (points[*i].0 - t).abs() <= SAME_T).collect::<Vec<_>>()[..] { - [a, b] => Some((a, b)), - _ => None, - } + points.get(index)?; + let pair = |a: usize| { + let t = points.get(a)?.0; + let at: Vec<usize> = (0..points.len()).filter(|i| (points[*i].0 - t).abs() <= SAME_T).collect(); + (at == [a, a + 1]).then_some((a, a + 1)) + }; + pair(index).or_else(|| index.checked_sub(1).and_then(pair)) } /// Open Width Point Edit for `index`, or a prospective point at fraction `t` without an index diff --git a/crates/ui-egui/src/dialogs/width_point/tests.rs b/crates/ui-egui/src/dialogs/width_point/tests.rs index ab07b971ae..bf32a6124f 100644 --- a/crates/ui-egui/src/dialogs/width_point/tests.rs +++ b/crates/ui-egui/src/dialogs/width_point/tests.rs @@ -445,6 +445,36 @@ fn either_half_of_a_discontinuous_point_shows_both_sets_of_side_widths() { assert_eq!(shown.iter().filter(|t| *t == "Side 1:").count(), 1); } +/// Three width points each within 1e-6 of the next, but the outer two farther apart: the halves +/// are paired as `stroke.widthPoint.set` pairs them, from the incoming half's place, whichever +/// of them is opened. The first two make one discontinuous point, and the third stays a +/// continuous point. +#[test] +fn points_in_a_chain_pair_as_the_engine_pairs_them() { + let chain = json!([[0, 1, 1], [0.5, 0.8, 0.8], [0.50000075, 0.4, 1.2], [0.5000015, 0.6, 0.6], [1, 1, 1]]); + for index in [1, 2] { + let (mut app, id) = app(); + app.run("stroke.widthProfile.set", json!({"ids": [id], "points": chain})).unwrap(); + app.run("ui.widthPointEdit", json!({"id": id, "index": index})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + assert_eq!((d.fields["index"].clone(), d.fields["outIndex"].clone()), (json!(1), json!(2)), "opened {index}"); + d.fields.insert("outSide1".into(), json!(1)); + super::super::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none(), "opened {index}"); + assert_eq!(points(&app, id)[2], (0.50000075, 0.2, 1.2), "opened {index}"); + } + let (mut app, id) = app(); + app.run("stroke.widthProfile.set", json!({"ids": [id], "points": chain})).unwrap(); + app.run("ui.widthPointEdit", json!({"id": id, "index": 3})).unwrap(); + let d = app.ui.dialog.as_mut().unwrap(); + assert_eq!(d.fields["index"], json!(3)); + assert!(d.fields.get("outIndex").is_none()); + d.fields.insert("side1".into(), json!(1)); + super::super::confirm(&mut app).unwrap(); + assert!(app.ui.dialog.is_none()); + assert_eq!(points(&app, id)[3], (0.5000015, 0.2, 0.6)); +} + #[test] fn ok_sets_both_halves_of_a_discontinuous_point_in_one_step() { let (mut app, id) = pair_app(); From 099de92455487ada1cbf1540bcd3dc07b45d928d Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 17 Nov 2026 17:02:33 -0800 Subject: [PATCH 164/176] Width Point: the outgoing half adjusts the point after its pair With Adjust Adjoining on, the outgoing half of a discontinuous point looked for the point after it as the first one farther than 1e-6 from its own place, so a point within 1e-6 of the outgoing half but not of the pair's place was skipped. Both halves now measure from the pair's place. --- crates/engine/src/cmd/distortcmds.rs | 17 +++++++++-------- crates/engine/src/tests/widthpoints.rs | 12 ++++++++++++ 2 files changed, 21 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/cmd/distortcmds.rs b/crates/engine/src/cmd/distortcmds.rs index 2e2f672af4..c1ca7ac644 100644 --- a/crates/engine/src/cmd/distortcmds.rs +++ b/crates/engine/src/cmd/distortcmds.rs @@ -265,10 +265,9 @@ fn place(points: &mut Vec<(f64, f64, f64)>, mut pt: (f64, f64, f64), from_below: } /// Adjust Adjoining Width Points: point `i` changes from `old` to `new` widths, and the nearest -/// points at other positions on the sides `sides` names (before, after) change in proportion (by -/// the same amount from zero). -fn adjust_adjoining(points: &mut [(f64, f64, f64)], i: usize, old: (f64, f64, f64), new: (f64, f64, f64), sides: [bool; 2]) { - let t = points[i].0; +/// points farther than [`SAME_T`] from place `t` on the sides `sides` names (before, after) +/// change in proportion (by the same amount from zero). +fn adjust_adjoining(points: &mut [(f64, f64, f64)], i: usize, t: f64, old: (f64, f64, f64), new: (f64, f64, f64), sides: [bool; 2]) { let scale = |v: f64, o: f64, n: f64| { let width = if o > 1e-9 { let product = v * n; @@ -331,9 +330,11 @@ fn set_pair( Some(false) => ((old_in.0, inc.1, inc.2), (old_in.0, inc.1, inc.2)), Some(true) => ((old_in.0, out.1, out.2), (old_in.0, out.1, out.2)), }; + // Both halves measure their neighbors from the point's place, so a point within SAME_T of the + // outgoing half but not of that place is the point after the pair. if adjust { - adjust_adjoining(points, i, old_in, new_in, [true, false]); - adjust_adjoining(points, j, old_out, new_out, [false, true]); + adjust_adjoining(points, i, at, old_in, new_in, [true, false]); + adjust_adjoining(points, j, at, old_out, new_out, [false, true]); } points[i] = new_in; points[j] = new_out; @@ -393,7 +394,7 @@ fn width_point_set(s: &mut Session, p: &Value) -> Result<Value> { (Some(i), None) => { let old = prof.points[i]; if adjust { - adjust_adjoining(&mut prof.points, i, old, pt, [true, true]); + adjust_adjoining(&mut prof.points, i, old.0, old, pt, [true, true]); } if (old.0 - t).abs() <= SAME_T { // Widths only: it keeps its place (and its side of a discontinuous point). @@ -409,7 +410,7 @@ fn width_point_set(s: &mut Session, p: &Value) -> Result<Value> { prof.points.retain(|q| (q.0 - t).abs() > SAME_T); let i = place(&mut prof.points, pt, true); if let Some((left, right)) = old { - adjust_adjoining(&mut prof.points, i, (t, left, right), pt, [true, true]); + adjust_adjoining(&mut prof.points, i, pt.0, (t, left, right), pt, [true, true]); } i } diff --git a/crates/engine/src/tests/widthpoints.rs b/crates/engine/src/tests/widthpoints.rs index 68b7099d68..a76e1a2227 100644 --- a/crates/engine/src/tests/widthpoints.rs +++ b/crates/engine/src/tests/widthpoints.rs @@ -212,6 +212,18 @@ fn paired_set_adjusts_the_point_before_and_the_point_after_once_each() { assert_eq!(points(&s, id), vec![(0.0, 2.0, 2.0), (0.0, 4.0, 4.0), (1.0, 2.0, 2.0)]); } +/// Three points each within 1e-6 of the next: the first two are the pair, and the third, though +/// within 1e-6 of the outgoing half, is the point after the pair that the outgoing half adjusts. +#[test] +fn paired_set_adjusts_the_point_after_a_chained_pair() { + let (mut s, id) = pair_session(json!([[0, 1, 1], [0.5, 1, 1], [0.50000075, 2, 2], [0.5000015, 1, 1], [1, 1, 1]])); + set( + &mut s, + json!({"id": id.0, "index": 1, "t": 0.5, "left": 5, "right": 5, "outIndex": 2, "outLeft": 5, "outRight": 5, "adjustAdjoining": true}), + ); + assert_eq!(points(&s, id), vec![(0.0, 1.0, 1.0), (0.5, 1.0, 1.0), (0.50000075, 1.0, 1.0), (0.5000015, 0.5, 0.5), (1.0, 1.0, 1.0)]); +} + #[test] fn single_width_only_leaves_one_continuous_point() { for (single, kept) in [("incoming", (2.0, 1.0)), ("outgoing", (3.0, 4.0))] { From e5d1186412ffd6415ad64a4e1eb2cf751352a630 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 17 Nov 2026 17:04:35 -0800 Subject: [PATCH 165/176] Color Themes: the Create tab edits the selected color with CMYK, RGB, Lab and HSB sliders The Create tab had only a hex field for typing the selected theme color's values. The help page describes changing the selected color's values in CMYK, RGB, Lab, HSB or hex while making a theme: https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=221 A Color Mode menu (CMYK, RGB, Lab, HSB) under the theme's colors shows a rail and a number field for each component, beside the hex field. The rails are the Recolor dialog's, so they step with the arrow keys and take screen readers' set-value action. VectorCraft's own rules: the menu starts in the selected color's model (HSB for a gray) and keeps the mode picked while the app runs; picking a mode changes no color. Ranges and whole-number steps are the Color panel's (Lab a and b from -128 to 127); a number past the range sets its end and text that is not a number changes nothing. A CMYK edit keeps the color CMYK and a Lab edit keeps it Lab; RGB and HSB edits make it RGB. An edit works as a hex edit does: with a harmony rule the edited color becomes the theme's base and is selected, and in Custom only the selected color changes. The sliders keep the numbers they set, so a color taken to no saturation keeps its hue on the H slider. --- crates/ui-egui/src/dialogs/recolor.rs | 2 +- crates/ui-egui/src/panels/color_themes.rs | 314 +++++++++++++++++++++- docs/target-app-parity.md | 1 + 3 files changed, 315 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/dialogs/recolor.rs b/crates/ui-egui/src/dialogs/recolor.rs index e3829f92b5..ee17df3abd 100644 --- a/crates/ui-egui/src/dialogs/recolor.rs +++ b/crates/ui-egui/src/dialogs/recolor.rs @@ -1334,7 +1334,7 @@ fn global_sliders(ui: &mut Ui, d: &mut Dialog, sample: Color) { /// and its number field, showing `shown` with `suffix`. Returns the whole number in `shown`'s /// range that a drag, a key or the field sets. #[allow(clippy::too_many_arguments)] -fn slider_cell( +pub(crate) fn slider_cell( ui: &mut Ui, id: impl std::hash::Hash + Copy, label: &str, diff --git a/crates/ui-egui/src/panels/color_themes.rs b/crates/ui-egui/src/panels/color_themes.rs index da72c15aac..3590d70812 100644 --- a/crates/ui-egui/src/panels/color_themes.rs +++ b/crates/ui-egui/src/panels/color_themes.rs @@ -1,6 +1,7 @@ //! Color Themes panel (local only): the Create tab makes a five-colour theme on a harmony wheel (a //! harmony rule from the selected colour, or Custom: each colour moves on its own; with a rule the -//! colours move together), the My Themes tab lists the themes saved in the preferences (the panel +//! colours move together; the selected color is also edited in its hex field or with CMYK, RGB, Lab +//! or HSB sliders), the My Themes tab lists the themes saved in the preferences (the panel //! menu's Show Find Field adds a field that lists only the themes whose names hold its text). Themes are //! saved, edited, deleted and added to Swatches as colour groups through `colorTheme.*`; the theme //! being made is panel state. @@ -11,8 +12,10 @@ use vectorcraft_color::Color; use vectorcraft_color::harmony::{Harmony, THEME_SIZE, move_on_wheel}; use vectorcraft_engine::cmd::colortheme::ColorTheme; +use super::color::{Mode, components, from_components, track_color}; use super::{active_paint, c32, color_json, empty_state, proxy_cmd, pstate, set_pstate}; use crate::VectorcraftApp; +use crate::dialogs::recolor::slider_cell; use crate::theme::{self, Tokens}; use crate::widgets::{self, menu_item}; @@ -22,6 +25,11 @@ const DEFAULT_RULE: Harmony = Harmony::Analogous2; const DEFAULT_BASE: Color = Color::Rgb { r: 0.1, g: 0.55, b: 0.6 }; /// Diameter of the harmony wheel. const WHEEL: f32 = 150.0; +/// The color modes of the selected color's sliders, in the order the Color Mode menu lists them. +const SLIDER_MODES: [Mode; 4] = [Mode::Cmyk, Mode::Rgb, Mode::Lab, Mode::Hsb]; +/// Widths of a slider's label and of its number field (the field's width is the Recolor dialog's). +const SLIDER_LABEL_W: f32 = 12.0; +const SLIDER_FIELD_W: f32 = 48.0; /// The theme being made on the Create tab. #[derive(Clone, Debug, Default, PartialEq)] @@ -127,6 +135,78 @@ fn tab(ctx: &egui::Context) -> usize { pstate(ctx, "ct-tab") } +/// The color mode of the sliders: the one last picked from their Color Mode menu while the app +/// runs, or else the selected color's own model (HSB for a gray). Picking a mode changes no color. +fn slider_mode(ctx: &egui::Context, c: Option<&Color>) -> Mode { + pstate::<Option<Mode>>(ctx, "ct-mode").unwrap_or_else(|| match c.map(Mode::of) { + Some(m @ (Mode::Cmyk | Mode::Rgb | Mode::Lab)) => m, + _ => Mode::Hsb, + }) +} + +/// The slider values a slider edit last set: the selected place and the color they made in +/// `mode`. While those still hold, the sliders show `v` as it was set, so an edit of one slider +/// leaves the others' numbers as they were instead of converting them back from the color. +#[derive(Clone, Debug, PartialEq)] +struct Held { + sel: usize, + color: Color, + mode: Mode, + v: Vec<f32>, +} + +/// The numbers the sliders show for the selected color of `d` in `mode`. +fn slider_values(ctx: &egui::Context, d: &Draft, mode: Mode) -> Option<Vec<f32>> { + let c = d.colors.get(d.sel)?; + let held = + pstate::<Option<Held>>(ctx, "ct-held").filter(|h| h.sel == d.sel && h.color == *c && h.mode == mode && h.v.len() == mode.labels().len()); + Some(held.map_or_else(|| components(mode, c), |h| h.v)) +} + +/// The Color Mode menu (CMYK, RGB, Lab and HSB) and its sliders, each a rail and a number field, for +/// the selected color of `d`. An edit sets the selected color in the menu's mode (an RGB or HSB +/// edit makes it RGB, a CMYK edit CMYK and a Lab edit Lab) as the hex field does: with a rule the +/// theme follows from it as the new base. +fn sliders(ui: &mut Ui, d: &mut Draft) { + let t = Tokens::get(ui.ctx()); + let ctx = ui.ctx().clone(); + let current = slider_mode(&ctx, d.colors.get(d.sel)); + ui.horizontal(|ui| { + ui.label(egui::RichText::new(tl!("Color Mode:")).color(t.text_dim)); + let labels: Vec<&str> = SLIDER_MODES.iter().map(|m| m.label()).collect(); + if let Some(&m) = + widgets::dropdown_named(ui, "ct-mode", Some(tl!("Color Mode:")), current.label(), &labels, 90.0).and_then(|i| SLIDER_MODES.get(i)) + { + set_pstate(&ctx, "ct-mode", Some(m)); + } + }); + ui.add_space(2.0); + let mode = slider_mode(&ctx, d.colors.get(d.sel)); + let Some(comps) = slider_values(&ctx, d, mode) else { return }; + let spacing = 6.0; + let rail = (ui.available_width() - SLIDER_LABEL_W - SLIDER_FIELD_W - 2.0 * spacing - 4.0).max(40.0); + let mut set: Option<Vec<f32>> = None; + egui::Grid::new("ct-sliders").num_columns(3).spacing([spacing, 4.0]).show(ui, |ui| { + for (n, lbl) in mode.labels().iter().enumerate() { + let v = comps.get(n).copied().unwrap_or(0.0); + let shown = widgets::SliderValue::field(f64::from(v), f64::from(mode.min(n))..=f64::from(mode.max(n)), mode.suffix(n), 0); + let track = |x: f32| c32(&track_color(mode, &comps, n, x)); + if let Some(nv) = slider_cell(ui, ("ct", mode.label(), n), lbl, shown, mode.suffix(n), &track, SLIDER_LABEL_W, rail) { + let mut c2 = comps.clone(); + c2[n] = nv as f32; + set = Some(c2); + } + ui.end_row(); + } + }); + if let Some(v) = set { + d.set_selected(from_components(mode, &v)); + if let Some(&color) = d.colors.get(d.sel) { + set_pstate(&ctx, "ct-held", Some(Held { sel: d.sel, color, mode, v })); + } + } +} + /// Save the theme being made (overwriting the theme it edits); it then edits the saved theme. fn save(app: &mut VectorcraftApp, ctx: &egui::Context) { let mut d = draft(app, ctx); @@ -225,6 +305,8 @@ fn create(app: &mut VectorcraftApp, ui: &mut Ui) { } } ui.add_space(6.0); + sliders(ui, &mut d); + ui.add_space(4.0); ui.horizontal(|ui| { let hex = d.colors.get(d.sel).map(|c| c.to_hex().trim_start_matches('#').to_string()).unwrap_or_default(); if let Some(c) = widgets::hex_field_named(ui, "ct-hex", Some(tl!("Color")), &hex).and_then(|h| Color::from_hex(&h)) { @@ -864,4 +946,234 @@ mod tests { let g = app.session.doc().unwrap().doc.swatch_groups.last().expect("the group"); assert_eq!(g.swatches.iter().filter_map(|w| w.paint.color()).collect::<Vec<_>>(), colors); } + + /// One frame of the panel in a 260 × 700 window with `events`, in English, with screen readers on. + fn step(app: &mut VectorcraftApp, ctx: &egui::Context, events: Vec<egui::Event>) -> egui::FullOutput { + crate::i18n::set_current(crate::i18n::Lang::EN); + ctx.enable_accesskit(); + let time = ctx.input(|i| i.time) + 0.1; + let screen = Rect::from_min_size(egui::Pos2::ZERO, vec2(260.0, 700.0)); + let input = egui::RawInput { events, time: Some(time), screen_rect: Some(screen), ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| show(app, ui)); + out.textures_delta.clear(); + out + } + + /// The screen-reader nodes of the frame after a settling one. + fn nodes(app: &mut VectorcraftApp, ctx: &egui::Context) -> Vec<(egui::accesskit::NodeId, egui::accesskit::Node)> { + step(app, ctx, vec![]); + step(app, ctx, vec![]).platform_output.accesskit_update.expect("an accessibility tree").nodes + } + + /// The labels of the color sliders the Create tab shows (named by one letter, unlike the wheel's + /// Brightness slider), with each one's range, in order. + fn slider_ranges(app: &mut VectorcraftApp, ctx: &egui::Context) -> Vec<(String, f64, f64)> { + let mut found: Vec<(f64, String, f64, f64)> = nodes(app, ctx) + .into_iter() + .filter(|(_, n)| n.role() == egui::accesskit::Role::Slider && n.label().is_some_and(|l| l.chars().count() == 1)) + .filter_map(|(_, n)| { + let top = n.bounds()?.y0; + Some((top, n.label()?.to_string(), n.min_numeric_value()?, n.max_numeric_value()?)) + }) + .collect(); + found.sort_by(|a, b| a.0.total_cmp(&b.0)); + found.into_iter().map(|(_, l, lo, hi)| (l, lo, hi)).collect() + } + + /// The node id and bounds of the screen-reader node named `label` whose role is (with `rail`) or + /// is not a slider. + fn node(app: &mut VectorcraftApp, ctx: &egui::Context, label: &str, rail: bool) -> (egui::accesskit::NodeId, egui::Pos2) { + let all = nodes(app, ctx); + let (id, n) = all + .iter() + .find(|(_, n)| n.label() == Some(label) && (n.role() == egui::accesskit::Role::Slider) == rail) + .unwrap_or_else(|| panic!("nothing named {label:?}")); + let b = n.bounds().expect("bounds"); + (*id, egui::pos2((b.x0 + b.x1) as f32 * 0.5, (b.y0 + b.y1) as f32 * 0.5)) + } + + /// A screen reader's set-value action on the slider named `label`. + fn set_slider(app: &mut VectorcraftApp, ctx: &egui::Context, label: &str, value: f64) { + use egui::accesskit::{Action, ActionData, ActionRequest, TreeId}; + let (target_node, _) = node(app, ctx, label, true); + let data = Some(ActionData::NumericValue(value)); + step( + app, + ctx, + vec![egui::Event::AccessKitActionRequest(ActionRequest { action: Action::SetValue, target_node, target_tree: TreeId::ROOT, data })], + ); + step(app, ctx, vec![]); + } + + /// A click at `at`, each event in a frame of its own. + fn press_at(app: &mut VectorcraftApp, ctx: &egui::Context, at: egui::Pos2) { + let button = + |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }; + step(app, ctx, vec![egui::Event::PointerMoved(at)]); + step(app, ctx, vec![button(true)]); + step(app, ctx, vec![button(false)]); + } + + fn key(app: &mut VectorcraftApp, ctx: &egui::Context, key: egui::Key, modifiers: egui::Modifiers) { + step(app, ctx, vec![egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers }]); + step(app, ctx, vec![egui::Event::Key { key, physical_key: None, pressed: false, repeat: false, modifiers }]); + } + + /// Type `text` into the number field named `label` in place of its number, and press Enter. + fn type_into(app: &mut VectorcraftApp, ctx: &egui::Context, label: &str, text: &str) { + let (_, at) = node(app, ctx, label, false); + press_at(app, ctx, at); + key(app, ctx, egui::Key::A, egui::Modifiers::COMMAND); + step(app, ctx, vec![egui::Event::Text(text.into())]); + key(app, ctx, egui::Key::Enter, egui::Modifiers::NONE); + step(app, ctx, vec![]); + } + + /// The Create tab offers a Color Mode menu of CMYK, RGB, Lab and HSB with a rail and a number + /// field for each component over its range, beside the hex field. It starts in the selected + /// color's own model (HSB for a gray), keeps the mode picked while the app runs, and picking a + /// mode changes no color. + #[test] + fn the_create_tab_offers_cmyk_rgb_lab_and_hsb_sliders() { + let mut app = app(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let mut d = five_colors(&ctx); + let named = |app: &mut VectorcraftApp, ctx: &egui::Context, label: &str| nodes(app, ctx).iter().any(|(_, n)| n.label() == Some(label)); + assert!(named(&mut app, &ctx, "Color Mode:"), "the menu is named"); + assert!(named(&mut app, &ctx, "Color"), "the hex field stays"); + let rgb = vec![("R".to_string(), 0.0, 255.0), ("G".into(), 0.0, 255.0), ("B".into(), 0.0, 255.0)]; + assert_eq!(slider_ranges(&mut app, &ctx), rgb, "an RGB color starts in RGB"); + for (c, first) in [(Color::cmyk(0.1, 0.2, 0.3, 0.4), "C"), (Color::lab(50.0, -20.0, 30.0), "L"), (Color::gray(0.5), "H")] { + d.colors[2] = c; + set_draft(&ctx, d.clone()); + assert_eq!(slider_ranges(&mut app, &ctx)[0].0, first, "{c:?}"); + } + let expect = [ + vec![("C", 0.0, 100.0), ("M", 0.0, 100.0), ("Y", 0.0, 100.0), ("K", 0.0, 100.0)], + vec![("R", 0.0, 255.0), ("G", 0.0, 255.0), ("B", 0.0, 255.0)], + vec![("L", 0.0, 100.0), ("a", -128.0, 127.0), ("b", -128.0, 127.0)], + vec![("H", 0.0, 360.0), ("S", 0.0, 100.0), ("B", 0.0, 100.0)], + ]; + for (m, rows) in SLIDER_MODES.into_iter().zip(expect) { + set_pstate(&ctx, "ct-mode", Some(m)); + let rows: Vec<(String, f64, f64)> = rows.into_iter().map(|(l, lo, hi)| (l.to_string(), lo, hi)).collect(); + assert_eq!(slider_ranges(&mut app, &ctx), rows, "{m:?}"); + assert_eq!(draft(&app, &ctx), d, "picking a mode changes no color"); + } + // The picked mode stays when another color is selected. + set_draft(&ctx, Draft { sel: 0, ..d.clone() }); + assert_eq!(slider_ranges(&mut app, &ctx)[0].0, "H"); + } + + /// In Custom, a rail, the arrow keys and the number field change the selected color alone, in + /// the menu's mode, and the selection stays; the other numbers stay as they were set. + #[test] + fn a_slider_edit_changes_only_the_selected_custom_color() { + let mut app = app(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let d = five_colors(&ctx); + let start = components(Mode::Rgb, &d.colors[2]); + set_slider(&mut app, &ctx, "R", 10.0); + let now = draft(&app, &ctx); + assert_eq!(now.colors[2], from_components(Mode::Rgb, &[10.0, start[1], start[2]])); + assert_eq!(now.sel, 2); + for i in [0, 1, 3, 4] { + assert_eq!(now.colors[i], d.colors[i], "color {i} stays"); + } + // The arrow keys step the focused rail by one. + let (_, at) = node(&mut app, &ctx, "G", true); + press_at(&mut app, &ctx, at); + let held = pstate::<Option<Held>>(&ctx, "ct-held").expect("held").v; + key(&mut app, &ctx, egui::Key::ArrowRight, egui::Modifiers::NONE); + let after = pstate::<Option<Held>>(&ctx, "ct-held").expect("held").v; + assert_eq!(after, vec![10.0, held[1] + 1.0, start[2]]); + // The number field. + type_into(&mut app, &ctx, "B", "40"); + let now = draft(&app, &ctx); + assert_eq!(now.colors[2], from_components(Mode::Rgb, &[10.0, held[1] + 1.0, 40.0])); + assert_eq!((now.sel, now.rule), (2, None)); + assert_eq!(now.colors[0], d.colors[0]); + } + + /// The sliders keep the numbers they set: an HSB color taken to no saturation keeps its hue on + /// the H slider, and S back up brings that hue back. Another color shows its own numbers. + #[test] + fn the_sliders_keep_the_numbers_they_set() { + let mut app = app(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + five_colors(&ctx); + set_pstate(&ctx, "ct-mode", Some(Mode::Hsb)); + let hue = |app: &mut VectorcraftApp, ctx: &egui::Context| { + let (id, _) = node(app, ctx, "H", true); + nodes(app, ctx).into_iter().find(|(n, _)| *n == id).and_then(|(_, n)| n.numeric_value()) + }; + set_slider(&mut app, &ctx, "H", 200.0); + set_slider(&mut app, &ctx, "S", 0.0); + assert_eq!(hue(&mut app, &ctx), Some(200.0), "a gray keeps the hue it was set to"); + set_slider(&mut app, &ctx, "S", 80.0); + let [h, s, _] = draft(&app, &ctx).colors[2].to_hsb(); + assert!((h - 200.0).abs() < 0.5 && (s - 0.8).abs() < 1e-3, "{h} {s}"); + set_draft(&ctx, Draft { sel: 0, ..draft(&app, &ctx) }); + let own = components(Mode::Hsb, &draft(&app, &ctx).colors[0])[0].round(); + assert_eq!(hue(&mut app, &ctx), Some(f64::from(own)), "another color shows its own numbers"); + } + + /// With a rule, a slider edit makes the edited color the theme's new base, as a hex edit does, + /// and selects it. + #[test] + fn with_a_rule_a_slider_edit_rebuilds_the_theme_from_the_edited_color() { + let mut app = app(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let d = Draft { rule: Some(Harmony::Triad), ..five_colors(&ctx) }; + set_draft(&ctx, d.clone()); + set_pstate(&ctx, "ct-mode", Some(Mode::Hsb)); + let start = components(Mode::Hsb, &d.colors[2]); + set_slider(&mut app, &ctx, "H", 200.0); + let base = from_components(Mode::Hsb, &[200.0, start[1], start[2]]); + let now = draft(&app, &ctx); + assert_eq!((now.colors, now.sel), (Harmony::Triad.theme(base), 0)); + } + + /// A CMYK edit keeps the color CMYK and a Lab edit keeps it Lab, with the numbers set, through + /// Save and Add to Swatches in a CMYK document; a number that is not one, or not finite, changes + /// nothing, and one past the range sets its end. + #[test] + fn cmyk_and_lab_slider_edits_keep_their_models() { + let mut app = app(); + app.run("file.documentColorMode", json!({"mode": "cmyk"})).unwrap(); + let ctx = egui::Context::default(); + crate::theme::install_fonts(&ctx); + let d = five_colors(&ctx); + set_pstate(&ctx, "ct-mode", Some(Mode::Cmyk)); + let start = components(Mode::Cmyk, &d.colors[2]); + set_slider(&mut app, &ctx, "C", 20.0); + set_slider(&mut app, &ctx, "K", 40.0); + let cmyk = from_components(Mode::Cmyk, &[20.0, start[1], start[2], 40.0]); + assert_eq!(draft(&app, &ctx).colors[2], cmyk); + assert!(matches!(cmyk, Color::Cmyk { k, .. } if (k - 0.4).abs() < 1e-6)); + // Lab on another color. + set_draft(&ctx, Draft { sel: 3, ..draft(&app, &ctx) }); + set_pstate(&ctx, "ct-mode", Some(Mode::Lab)); + let start = components(Mode::Lab, &d.colors[3]); + set_slider(&mut app, &ctx, "b", -60.0); + let lab = Color::lab(start[0], start[1], -60.0); + assert_eq!(draft(&app, &ctx).colors[3], lab); + // Not numbers, not finite, past the range. + let before = draft(&app, &ctx); + type_into(&mut app, &ctx, "L", "abc"); + set_slider(&mut app, &ctx, "a", f64::NAN); + assert_eq!(draft(&app, &ctx), before); + set_slider(&mut app, &ctx, "a", 500.0); + assert_eq!(draft(&app, &ctx).colors[3], Color::lab(start[0], 127.0, -60.0)); + let colors = draft(&app, &ctx).colors; + save(&mut app, &ctx); + assert_eq!(themes(&app)[0].colors, colors, "saved in their models"); + add_draft_to_swatches(&mut app, &ctx); + let g = app.session.doc().unwrap().doc.swatch_groups.last().expect("the group"); + assert_eq!(g.swatches.iter().filter_map(|w| w.paint.color()).collect::<Vec<_>>(), colors); + } } diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 8fb16bbaa4..1d29c76cba 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1778,6 +1778,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Swatches made from a shown color in a CMYK document:** the Color panel menu's Create New Swatch, an Alt-click on the Swatches panel's New Swatch button, the New Swatch dialog for a gradient, a Fill or Stroke proxy or the Gradient panel's thumbnail dropped on the Swatches panel (or Alt-dropped on a swatch of its kind), and the Gradient panel's Add to Swatches and Save to Swatches keep each color's model, as the Color Guide's and Color Themes' saved colors do: an RGB object's color gives an RGB swatch, and a gradient's RGB stops stay RGB. - **Color Themes Set Active Color:** a button on the Color Themes panel's Create tab makes the selected theme color the current color, the action the [help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=222) describes for creating a color theme. VectorCraft's own rules: the color goes to the proxy in front (Fill or Stroke), on the selection and the default for new art, in its own color model, through `paint.setFill` or `paint.setStroke`; with characters selected with the Type tool, only those characters take it and the default for new art stays as it was, as with a swatch click; a click is one undo step, a click that changes no art adds none, and the button is off without a document. Tests: `set_active_color_*` in `crates/ui-egui/src/panels/color_themes.rs`. - **Color Themes find field:** on the Color Themes panel's My Themes tab, Show Find Field in the panel menu shows a Find field that lists only the saved themes whose names hold its text; the [help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=255) describes looking up a saved theme by its name this way (printed page 249). VectorCraft's own rules: the menu item is checked while the field shows and is off in a new session; a name matches when it holds the text anywhere, in any letter case, with spaces at either end of the text ignored; colors are not searched; the list keeps its saved order and shows No matches. when nothing matches; a picked theme the field hides stays picked, but Edit Theme, Add to Swatches and Delete Theme are off until the list shows it again; turning the field off lists every theme, and turning it on again in the same session restores its text. The field does not change the saved themes or `colorTheme.list`. Tests: `show_find_field_toggles_the_find_field_on_my_themes`, `the_find_field_lists_themes_whose_names_hold_its_text`, `no_saved_themes_is_not_no_matches`, `a_theme_the_find_field_hides_is_not_acted_on` and `footer_buttons_are_off_for_a_hidden_pick` in `crates/ui-egui/src/panels/color_themes.rs`. + - **Color Themes sliders:** on the Color Themes panel's Create tab, a Color Mode menu (CMYK, RGB, Lab and HSB) shows a rail and a number field for each component of the selected theme color, beside its hex field; the [help page](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=221) describes changing the selected color's values in these color systems or as hex while making a theme. VectorCraft's own rules: the menu starts in the selected color's own model (HSB for a gray) and keeps the mode picked while the app runs; picking a mode changes no color; the ranges and whole-number steps are the Color panel's (Lab a and b from -128 to 127), a number past the range sets its end and text that is not a number changes nothing; a CMYK edit keeps the color CMYK and a Lab edit keeps it Lab, while RGB and HSB edits make it RGB, and the theme saves and goes to Swatches in those models; an edit works as a hex edit does: with a harmony rule the edited color becomes the theme's base and is selected, and in Custom only the selected color changes. Tests: `the_create_tab_offers_cmyk_rgb_lab_and_hsb_sliders`, `a_slider_edit_changes_only_the_selected_custom_color`, `the_sliders_keep_the_numbers_they_set`, `with_a_rule_a_slider_edit_rebuilds_the_theme_from_the_edited_color` and `cmyk_and_lab_slider_edits_keep_their_models` in `crates/ui-egui/src/panels/color_themes.rs`. - **Sample Color from Screen:** an eyedropper button in the Color Picker and `ui.sampleScreenColor` (which can be given a key in Keyboard Shortcuts) pick a color anywhere on the screen with the system's sampler: `NSColorSampler` on macOS, the XDG desktop portal's [PickColor](https://flatpak.github.io/xdg-desktop-portal/docs/doc-org.freedesktop.portal.Screenshot.html) on Linux, a still copy of every monitor under a crosshair on Windows, and the EyeDropper API in browsers that have it. The color becomes the fill or the stroke as one undo step, or the Color Picker's color, converted from display sRGB into the working RGB space. On Linux, a session without a portal that has PickColor, a portal that does not return from the call within 25 seconds (VectorCraft's own limit) or leaves the bus before it answers, and a portal that ends the request another way each show a status message and end the wait. On Windows, the copy is read as sRGB, so the colors of HDR and wide-gamut displays are not converted; Escape, a click of another mouse button or switching to another window cancels (VectorCraft's own rules). The BSDs and other browsers have no sampler yet; the button is gray there. - **Color Guide color groups:** with variation cells selected, the Color Guide's Save Color Group to Swatches button saves those cells as one swatch group, and with none selected it saves the harmony colors, as the [help page](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf) describes saving several selected variations together (printed page 135). The group takes the cells in grid order (row by row, left to right, each cell once), is named after the harmony rule and is one undo step; these are VectorCraft's own rules. A selection lasts until the base, the Color Guide Options, the variation mode, the harmony rule, the library limit or the colors the grid shows (for example after a new swatch while the guide is limited to the document's swatches) change. - **Color Guide colors dragged to Swatches:** a variation cell dragged from the Color Guide onto the Swatches panel's list becomes a swatch of that color, as the [help page](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf) describes for saving variations as individual swatches (printed page 135). In VectorCraft a harmony strip color drags the same way, a drag carries only the grabbed color (the selected cells stay selected and the selection is not saved), it carries the color the cell shows (snapped to the Limit to Library colors), keeps the color's model and does not paint the selected art; the swatch follows the panel's rules for a dropped color (`swatch.new`, one undo step, a color that is already a swatch is added again under another name, a drop on a color group joins it). These are VectorCraft's own rules. Tests: `a_dragged_guide_color_carries_its_color_and_applies_nothing` and `a_guide_color_dragged_onto_the_swatches_panel_becomes_a_swatch` in `crates/ui-egui/src/panels/color_guide.rs`. From de064977165adc0a71583e00e8d5408bd9a49e7b Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 17 Nov 2026 17:08:30 -0800 Subject: [PATCH 166/176] Commands: each built-in command's parameter keys are parsed once per process MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Session::execute asked about a command's params description several times per command (the key check, whether `id` stands for `ids`, whether it takes `ids`), and each question parsed the description again, with a command lookup for each word after the first of each `…` entry. The engine now reads every built-in description, and the ones its `…` entries name, once into a table keyed by the description's address and length, and answers accepted_keys, takes_key, id_stands_for_ids and check_keys from it. A plug-in command's description, and a built-in description whose `…` entries name a plug-in command, are still parsed where they are used, since plug-ins change while the app runs. The keys, answers and error messages are the same; tests::params_cache compares them for every built-in command against a fresh parse. In a release build on a one-object document, object.move with ids and dx takes 48 us of thread CPU time per command instead of 61 us, and select.set with ids 2.3 us instead of 3.2 us (medians of 7 alternating runs of 20,000 commands in one process, while other builds were running; tests::params_cache::bench_params_keys_once). The time is saved per command, in scripts, batches and MCP or plug-in call loops, and does not grow with the size of the document. --- crates/engine/src/cmd/params.rs | 139 ++++++++++++++++++-- crates/engine/src/tests.rs | 1 + crates/engine/src/tests/params_cache.rs | 168 ++++++++++++++++++++++++ docs/target-app-parity.md | 1 + 4 files changed, 300 insertions(+), 9 deletions(-) create mode 100644 crates/engine/src/tests/params_cache.rs diff --git a/crates/engine/src/cmd/params.rs b/crates/engine/src/cmd/params.rs index 8dc29b9704..58a3ecf99b 100644 --- a/crates/engine/src/cmd/params.rs +++ b/crates/engine/src/cmd/params.rs @@ -36,6 +36,9 @@ //! `channel` that the effect doesn't have are refused by `effect.apply` and `effect.setParams` //! themselves ([`check_effect_color`], [`check_effect_channel`]). +use std::collections::HashMap; +use std::sync::OnceLock; + use serde_json::Value; use vectorcraft_apischema::shown_key; @@ -43,7 +46,7 @@ use super::{bad, command_specs, find_command}; use crate::Result; /// What a params description says about the keys of the params object. -#[derive(Debug, Default, PartialEq)] +#[derive(Clone, Debug, Default, PartialEq)] pub struct ParamKeys<'a> { /// The keys it names. pub keys: Vec<&'a str>, @@ -107,6 +110,8 @@ pub(crate) fn is_key(s: &str) -> bool { /// The keys a params description names, or what in it doesn't read as one. pub fn doc_keys(doc: &str) -> std::result::Result<ParamKeys<'_>, String> { + #[cfg(test)] + PARSES.with(|n| n.set(n.get() + 1)); let mut out = ParamKeys::default(); let (mut body, mut rest) = object_body(doc)?; let mut entries = split_top(body, ','); @@ -155,7 +160,12 @@ fn named_commands(more: &str) -> impl Iterator<Item = &'static super::CommandSpe /// `None`: any key (a `…` entry naming no command, or a description that doesn't parse, which /// the tests rule out). fn accepted(doc: &'static str, depth: usize) -> Option<Vec<&'static str>> { - let parsed = doc_keys(doc).ok()?; + resolve(doc, depth, &mut |doc| doc_keys(doc).ok()) +} + +/// [`accepted`], with `parse` reading each description it reaches. +fn resolve(doc: &'static str, depth: usize, parse: &mut dyn FnMut(&'static str) -> Option<ParamKeys<'static>>) -> Option<Vec<&'static str>> { + let parsed = parse(doc)?; let mut keys = parsed.keys; for more in parsed.more { let mut named = named_commands(more).peekable(); @@ -168,22 +178,120 @@ fn accepted(doc: &'static str, depth: usize) -> Option<Vec<&'static str>> { if UNCHECKED.contains(&spec.id) { return None; } - keys.extend(accepted(spec.params, depth + 1)?); + keys.extend(resolve(spec.params, depth + 1, parse)?); } } Some(keys) } +/// What the params description of a built-in command says about its keys, read once per process +/// ([`known`]). +#[derive(Debug)] +struct Known { + /// The keys it names itself; none when it doesn't parse. + own: Vec<&'static str>, + /// [`accepted`] of it. + accepted: Option<Vec<&'static str>>, + /// [`id_stands_for_ids`] of it. + id_stands_for_ids: bool, +} + +impl Known { + /// [`takes_key`] of the description. + fn takes(&self, key: &str) -> bool { + self.own.contains(&key) || self.accepted.as_ref().is_some_and(|keys| keys.contains(&key)) + } +} + +/// The place and length of `doc`'s text: a description with the same words elsewhere (a plug-in's) +/// has another place. +fn text_key(doc: &str) -> (usize, usize) { + (doc.as_ptr().addr(), doc.len()) +} + +/// [`Known`] of each description in `docs`, each one and each one its `…` entries name parsed once. +/// A description is left out when one it reaches has a `…` entry naming a plug-in command, whose +/// keys change as plug-ins are installed and removed. +fn read_descriptions(docs: impl IntoIterator<Item = &'static str>) -> HashMap<(usize, usize), Known> { + let names_plugin = + |more: &str| more.split_whitespace().any(|w| w.trim_matches(|c: char| !c.is_ascii_alphanumeric()).starts_with(vectorcraft_plugins::PREFIX)); + let mut parsed: HashMap<(usize, usize), (Option<ParamKeys<'static>>, bool)> = HashMap::new(); + let mut table = HashMap::new(); + for doc in docs { + if table.contains_key(&text_key(doc)) { + continue; + } + let mut live = false; + let mut parse = |doc: &'static str| { + let (keys, plugin) = parsed.entry(text_key(doc)).or_insert_with(|| { + let keys = doc_keys(doc).ok(); + let plugin = keys.as_ref().is_some_and(|k| k.more.iter().any(|m| names_plugin(m))); + (keys, plugin) + }); + live |= *plugin; + keys.clone() + }; + let own = parse(doc).map(|p| p.keys).unwrap_or_default(); + let accepted = resolve(doc, 0, &mut parse); + if live { + continue; + } + let mut known = Known { own, accepted, id_stands_for_ids: false }; + known.id_stands_for_ids = known.takes("ids") && known.takes("id") && no_required_id_beside_ids(doc); + table.insert(text_key(doc), known); + } + table +} + +/// [`Known`] of `doc` when it is the params description of a built-in command. +fn known(doc: &str) -> Option<&'static Known> { + #[cfg(test)] + if UNCACHED.get() { + return None; + } + static TABLE: OnceLock<HashMap<(usize, usize), Known>> = OnceLock::new(); + TABLE.get_or_init(|| read_descriptions(command_specs().iter().map(|c| c.params))).get(&text_key(doc)) +} + +#[cfg(test)] +thread_local! { + /// The times [`doc_keys`] parsed a description on this thread. + pub(crate) static PARSES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) }; + /// Whether [`known`] is skipped on this thread ([`uncached`]). + static UNCACHED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) }; +} + +/// Whether [`read_descriptions`] keeps what `doc` says. +#[cfg(test)] +pub(crate) fn read_once(doc: &'static str) -> bool { + read_descriptions([doc]).contains_key(&text_key(doc)) +} + +/// `f`'s result with every description parsed again where it is used, as without [`known`]. +#[cfg(test)] +pub(crate) fn uncached<T>(f: impl FnOnce() -> T) -> T { + let before = UNCACHED.replace(true); + let out = f(); + UNCACHED.set(before); + out +} + /// Every key the description `doc` takes, those of the commands its `…` entries name included, or /// `None` when that isn't known: it doesn't parse, a `…` entry names no command, or one names a /// command in [`UNCHECKED`]. pub(crate) fn accepted_keys(doc: &'static str) -> Option<Vec<&'static str>> { - accepted(doc, 0) + match known(doc) { + Some(known) => known.accepted.clone(), + None => accepted(doc, 0), + } } /// Does the description `doc` name `key` as a parameter (its own keys, and those of the commands /// its `…` entries name)? pub fn takes_key(doc: &'static str, key: &str) -> bool { + if let Some(known) = known(doc) { + return known.takes(key); + } doc_keys(doc).is_ok_and(|parsed| parsed.keys.contains(&key)) || accepted(doc, 0).is_some_and(|keys| keys.contains(&key)) } @@ -191,12 +299,17 @@ pub fn takes_key(doc: &'static str, key: &str) -> bool { /// (instead of id)}`, `{id} or {ids: […]}`): it names both keys, and no params object of it names /// `ids` beside a required `id`, which is something else (`plugin.run {id, ids?}`: the plug-in's)? pub(crate) fn id_stands_for_ids(doc: &'static str) -> bool { + if let Some(known) = known(doc) { + return known.id_stands_for_ids; + } + takes_key(doc, "ids") && takes_key(doc, "id") && no_required_id_beside_ids(doc) +} + +/// No params object of `doc` names `ids` beside a required `id`. +fn no_required_id_beside_ids(doc: &str) -> bool { fn head(alternative: &str) -> &str { alternative.split([':', '=', '(']).next().unwrap_or_default().trim() } - if !takes_key(doc, "ids") || !takes_key(doc, "id") { - return false; - } let mut rest = doc; while let Ok((body, after)) = object_body(rest) { let entries = split_top(body, ','); @@ -249,9 +362,17 @@ pub fn check_keys(id: &str, doc: &'static str, params: &Value) -> Result<()> { if given.is_empty() { return Ok(()); } - let Some(keys) = accepted(doc, 0) else { return Ok(()) }; + let live; + let keys = match known(doc) { + Some(known) => known.accepted.as_deref(), + None => { + live = accepted(doc, 0); + live.as_deref() + } + }; + let Some(keys) = keys else { return Ok(()) }; match given.keys().find(|k| !keys.contains(&k.as_str())) { - Some(key) => Err(unknown(id, key, &keys)), + Some(key) => Err(unknown(id, key, keys)), None => Ok(()), } } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index e6c622963a..b4c03027bd 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -122,6 +122,7 @@ mod paintproxy; mod panelcmds; mod paragraphs; mod params; +mod params_cache; mod path_menu_enabled; mod pathfinder_clip; mod pathops; diff --git a/crates/engine/src/tests/params_cache.rs b/crates/engine/src/tests/params_cache.rs new file mode 100644 index 0000000000..3fc2d629e7 --- /dev/null +++ b/crates/engine/src/tests/params_cache.rs @@ -0,0 +1,168 @@ +//! The params description of each built-in command is parsed once per process; the answers read +//! from it are those of parsing it where they are used. + +use std::hint::black_box; + +use serde_json::{Value, json}; + +use crate::cmd::params::{PARSES, accepted_keys, check_keys, doc_keys, id_stands_for_ids, read_once, takes_key, uncached}; +use crate::{Session, command_specs}; + +/// Every answer the key functions give about `doc` for command `id`, as text. +fn answers(id: &str, doc: &'static str) -> Vec<String> { + let own = doc_keys(doc).map(|p| p.keys).unwrap_or_default(); + let accepted = accepted_keys(doc); + let mut out = vec![format!("{accepted:?}"), format!("{}", id_stands_for_ids(doc))]; + let near = own.first().map(|k| format!("{k}q")); + for key in own.iter().copied().chain(["ids", "id", "zzz"]).chain(near.as_deref()) { + out.push(format!("{key}: {}", takes_key(doc, key))); + } + let all: serde_json::Map<String, Value> = accepted.iter().flatten().map(|k| (k.to_string(), Value::Null)).collect(); + let mut cases = vec![json!({}), json!({"zzz": 1}), Value::Object(all)]; + cases.extend(near.map(|k| json!({ k: 1 }))); + for params in cases { + out.push(format!("{params}: {:?}", check_keys(id, doc, ¶ms))); + } + out +} + +#[test] +fn every_command_gets_the_answers_of_its_parsed_description() { + for c in command_specs() { + assert_eq!(answers(c.id, c.params), uncached(|| answers(c.id, c.params)), "{}", c.id); + } +} + +#[test] +fn a_built_in_description_is_not_parsed_again() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 200, "created": null})).unwrap(); + let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 40})).unwrap()["id"].as_u64().unwrap(); + let run = |s: &mut Session| { + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + s.execute("object.move", &json!({"ids": [id], "dx": 1})).unwrap(); + s.execute("object.move", &json!({"ids": [id], "dx": -1})).unwrap(); + for c in command_specs() { + black_box((accepted_keys(c.params), takes_key(c.params, "ids"), takes_key(c.params, "id"), id_stands_for_ids(c.params))); + black_box(check_keys(c.id, c.params, &json!({"zzz": 1})).is_err()); + } + }; + run(&mut s); + PARSES.set(0); + run(&mut s); + assert_eq!(PARSES.get(), 0, "descriptions parsed again"); + // Without the table each command parses its description where it is used. + uncached(|| run(&mut s)); + assert!(PARSES.get() > command_specs().len()); +} + +/// A description that isn't a built-in command's, even with the same words (a plug-in's), is parsed +/// where it is used, and so is one that names a plug-in command, whose keys change as plug-ins are +/// installed and removed. +#[test] +fn other_descriptions_are_parsed_where_they_are_used() { + let spec = command_specs().iter().find(|c| id_stands_for_ids(c.params)).unwrap(); + let copy: &'static str = String::from(spec.params).leak(); + assert_eq!(answers(spec.id, copy), answers(spec.id, spec.params)); + PARSES.set(0); + assert!(takes_key(copy, "ids") && id_stands_for_ids(copy)); + assert!(PARSES.get() > 0); + assert!(read_once("{a, …settings as file.new}")); + assert!(!read_once("{a, …settings as plugin.some.command}")); + assert!(!read_once("{a, …the options of `plugin.some.command`}")); +} + +/// This thread's CPU time in ns where Linux reports it, else the time since `start`. +fn now(start: std::time::Instant) -> (u128, bool) { + let cpu = std::fs::read_to_string("/proc/thread-self/schedstat").ok().and_then(|s| s.split_whitespace().next()?.parse().ok()); + match cpu { + Some(ns) => (ns, true), + None => (start.elapsed().as_nanos(), false), + } +} + +fn median(mut v: Vec<u128>) -> u128 { + v.sort_unstable(); + v[v.len() / 2] +} + +/// `cargo test --release -p vectorcraft-engine --lib params_cache -- --ignored --nocapture` prints +/// the time of the key questions over every built-in description and of `Session::execute` on a +/// one-object document, with descriptions parsed where they are used (`parse`) and read once +/// (`once`), alternating in one process: the median of 7 runs, in this thread's CPU time on Linux. +#[test] +#[ignore = "benchmark"] +fn bench_params_keys_once() { + let start = std::time::Instant::now(); + let specs = command_specs(); + let questions = || { + for c in specs { + black_box((accepted_keys(c.params), takes_key(c.params, "ids"), takes_key(c.params, "id"))); + black_box((takes_key(c.params, "ids"), takes_key(c.params, "id"), id_stands_for_ids(c.params))); + } + }; + let time = |f: &dyn Fn()| { + let t = now(start); + f(); + (now(start).0 - t.0, t.1) + }; + questions(); + uncached(questions); + let (mut parse, mut once, mut cpu) = (Vec::new(), Vec::new(), true); + for _ in 0..7 { + let (p, c1) = time(&|| uncached(|| (0..200).for_each(|_| questions()))); + let (o, c2) = time(&|| (0..200).for_each(|_| questions())); + parse.push(p); + once.push(o); + cpu &= c1 && c2; + } + let per = |ns: u128| ns / (200 * specs.len() as u128); + println!("clock: {}", if cpu { "thread CPU time" } else { "wall time" }); + println!("key questions, ns per description: parse {} once {}", per(median(parse)), per(median(once))); + for (cmd, params) in [("select.set", "ids"), ("object.move", "move")] { + let doc = || { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 200, "height": 200, "created": null})).unwrap(); + let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 40})).unwrap()["id"].as_u64().unwrap(); + let p = if params == "ids" { json!({"ids": [id]}) } else { json!({"ids": [id], "dx": 1}) }; + (s, p) + }; + let run = |s: &mut Session, p: &Value| { + for _ in 0..20_000 { + black_box(s.execute(cmd, p).unwrap()); + } + }; + let ((mut a, pa), (mut b, pb)) = (doc(), doc()); + assert_eq!(uncached(|| a.execute(cmd, &pa).unwrap()), b.execute(cmd, &pb).unwrap(), "{cmd}: both ways give the same result"); + let timed = |s: &mut Session, p: &Value, cached: bool| { + let t = now(start).0; + if cached { + run(s, p) + } else { + uncached(|| run(s, p)) + } + now(start).0 - t + }; + let (mut parse, mut once) = (Vec::new(), Vec::new()); + for i in 0..7 { + let (mut s1, p1) = doc(); + let (mut s2, p2) = doc(); + if i % 2 == 0 { + parse.push(timed(&mut s1, &p1, false)); + once.push(timed(&mut s2, &p2, true)); + } else { + once.push(timed(&mut s2, &p2, true)); + parse.push(timed(&mut s1, &p1, false)); + } + // Each document has a `uid` of its own. + let state = |s: &Session| { + let mut d = crate::inspect::document(s); + d.as_object_mut().unwrap().remove("uid"); + d + }; + assert_eq!(state(&s1), state(&s2), "{cmd}: same document"); + } + let ms = |ns: u128| ns as f64 / 1e6; + println!("{cmd} x 20,000: parse {:.1} ms once {:.1} ms", ms(median(parse)), ms(median(once))); + } +} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index ef83de54ad..547c5fddb8 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -944,6 +944,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Plug-in, recovery and script report replies under `--automation-read-root`: `plugin.list`, `plugin.info` and `plugin.safeMode` name the plug-in folder, failed files, plug-in sources and disabled plug-ins' files outside the read roots by file name or `null`, `file.recovery.*` leave out a document's original file and the recovery folder outside them, and `ui.inspect`'s `scriptReport` names files a run wrote outside them by file name. `crates/engine/src/tests/plugins.rs` (`plugin_list_leaves_out_paths_outside_the_read_root`), `crates/engine/src/tests/recovery.rs` (`recovery_replies_leave_out_paths_outside_the_read_root`), `crates/ui-egui/src/tests/automation.rs` (`ui_inspect_script_report_leaves_out_files_outside_the_read_root`). - Scripts: `alert`, `confirm` and `prompt` open dialogs during a run, each with a Stop button that ends the run and puts every document back. In the app the run waits at the call for the person's answer; a run over MCP or the command line takes its answers in order from `script.run`'s `answers`, and the report lists each dialog with its answer. `crates/engine/src/tests/script_dialogs.rs`, `crates/ui-egui/src/tests/script_dialogs.rs`. - Parameter keys: the engine refuses a key that a command's params description doesn't name before the command runs, in every build and for every caller, including the app's own calls, the commands a command runs and the steps of `command.batch` and `action.batch`. An action recorded by an older version still plays from the Actions panel and the Batch dialog (`Session::replay`). `crates/engine/tests/it/param_keys.rs`. + - Parameter key lookups: the engine reads the params description of each built-in command, with the descriptions its `…` entries name, once per process, and answers the key check and the `ids` and `id` questions of each later command from that reading. A plug-in command's description, and a description whose `…` entries name a plug-in command, are still read each time. The accepted keys, the answers and the error messages are the same. In a release build on a one-object document, `object.move` with `ids` and `dx` takes 48 µs of thread CPU time per command instead of 61 µs, and `select.set` with `ids` 2.3 µs instead of 3.2 µs (medians of 7 alternating runs of 20,000 commands in one process, measured while other builds were running; `tests::params_cache::bench_params_keys_once`). The time is saved per command, in scripts, batches and MCP or plug-in call loops, and does not grow with the size of the document. `crates/engine/src/tests/params_cache.rs` compares every built-in command's answers with those of a fresh parse. - Effect parameter types: `effect.apply`, `appearance.addEffect` and `effect.setParams` refuse an effect parameter of another type than the effect reads, for keys only the params text names too (the earlier 3D `perspective`, `lightAzimuth` and `lightElevation`, Scribble's `variation`, Outline Stroke's `width`, Gaussian Blur's `linear`), a Crop Marks `style` other than `roman` or `japanese`, and an installed plug-in effect's parameter of another type than its manifest gives it, in a `command.batch` step too, with the document and undo history unchanged; a replayed action still plays. `effect.setParams` checks the parameters against a Warp's new style, and refuses a `visible` that is not true or false, in a replayed action too. `crates/engine/src/tests/params.rs` (`an_effect_parameter_without_a_default_is_held_to_its_type`, `effect_commands_refuse_an_undefaulted_parameter_of_the_wrong_type`), `crates/engine/src/tests/plugins.rs` (`live_effect_plugins_reshape_editable_art_and_expand`), `crates/engine/src/cmd/effectcmd/tests.rs` (`set_params_refuses_a_visible_that_is_not_true_or_false`, `set_params_checks_the_effect_it_leaves`). - MCP server with 33 tools (drawing, text, effects, Pathfinder, transforms, graphs, text wrap, export, screenshots, undo/redo, UI inspect/screenshot aliases, any command), attached to the running app or headless. Headless and remote `command_list` include desktop `UI_COMMANDS` (`ui: true`); a UI-only id still needs `--connect` to run. Eight prompts (poster, icon-set, recolor, trace-and-style, export-set, check-spelling, variables-bind, path-tools). Effect ids are not command ids. Prefer a CLI built from the checkout when a release binary lags (#6460). `vectorcraft://commands/reference` serves the API reference. 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 window captures from an app that does not send the image back go through a file in a new folder inside the system's temporary folder, which only the user can open on Unix, instead of a fixed name in the shared folder; the folder is removed after the read, also when the capture or the read fails (`tests::conventions::an_old_app_captures_the_window_in_a_new_private_folder`). From a5cc189172bd6d6dad34a11457f4a2e0b6f709c7 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 17 Nov 2026 17:18:46 -0800 Subject: [PATCH 167/176] Shapes: a Circle tool drag ends where it is let go A release away from the last drag point now moves the circle's points to the release position before the circle is drawn, for a drag from the first press, from a second press and from a press on the first point. A release within 2 screen points of the press is still a click and keeps the point of the press. --- crates/tools/src/circle.rs | 13 +++++++++++++ crates/tools/src/circle/tests.rs | 26 ++++++++++++++++++++++++++ 2 files changed, 39 insertions(+) diff --git a/crates/tools/src/circle.rs b/crates/tools/src/circle.rs index 76e5a2df36..9e467b35d6 100644 --- a/crates/tools/src/circle.rs +++ b/crates/tools/src/circle.rs @@ -136,6 +136,14 @@ impl CircleTool { let (c, v) = command(points); vec![Action::Exec(c, v)] } + + /// Is the press a drag at `ev`: dragged already, or `ev` is [`DRAG_PX`] or more from the press? + fn drags(&self, cx: &ToolContext, ev: &PointerEvent) -> bool { + match self.press { + Some(Press::First { from, dragged, .. } | Press::Second { from, dragged, .. }) => dragged || ev.pos.distance(from) >= cx.tol(DRAG_PX), + None => false, + } + } } impl Tool for CircleTool { @@ -147,6 +155,11 @@ impl Tool for CircleTool { if !ev.pos.is_finite() { return vec![]; } + // A drag ends where it is let go: the release moves the points as a drag to it would. A + // click, or a release within DRAG_PX of the press, keeps the points of the press. + if ev.kind == PointerKind::Up && self.drags(cx, ev) { + self.pointer(cx, &PointerEvent { kind: PointerKind::Drag, ..*ev }); + } match ev.kind { PointerKind::Move => { let leave = self.leave(cx, ev.mods); diff --git a/crates/tools/src/circle/tests.rs b/crates/tools/src/circle/tests.rs index a6caafbc1d..e262d242ef 100644 --- a/crates/tools/src/circle/tests.rs +++ b/crates/tools/src/circle/tests.rs @@ -94,6 +94,32 @@ fn a_click_and_a_drag_draw_the_circle_through_three_points() { assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, (300.0, 360.0), Mods::default())), circle(&[(300.0, 300.0), (380.0, 300.0), (300.0, 360.0)])); } +/// A drag ends where it is let go, also when the release is away from the last drag: from a first +/// press, from a second press, and from a press on the first point. A release within 2 screen +/// points of a second press is still a click and keeps the point of the press. +#[test] +fn a_drag_ends_where_it_is_let_go() { + let (d, _) = doc_with_rect(); + let (s, p) = (Selection::default(), paint()); + let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) }; + let (down, drag, up) = (PointerKind::Down, PointerKind::Drag, PointerKind::Up); + let mut t = CircleTool::default(); + t.pointer(&cx, &ev(down, (300.0, 300.0), Mods::default())); + t.pointer(&cx, &ev(drag, (380.0, 300.0), Mods::default())); + assert_eq!(t.pointer(&cx, &ev(up, (400.0, 300.0), Mods::default())), circle(&[(300.0, 300.0), (400.0, 300.0)])); + click(&mut t, &cx, (300.0, 300.0)); + t.pointer(&cx, &ev(down, (380.0, 300.0), Mods::default())); + t.pointer(&cx, &ev(drag, (300.0, 340.0), Mods::default())); + assert_eq!(t.pointer(&cx, &ev(up, (300.0, 360.0), Mods::default())), circle(&[(300.0, 300.0), (380.0, 300.0), (300.0, 360.0)])); + click(&mut t, &cx, (300.0, 300.0)); + t.pointer(&cx, &ev(down, (300.0, 300.0), Mods::default())); + t.pointer(&cx, &ev(drag, (300.0, 380.0), Mods::default())); + assert_eq!(t.pointer(&cx, &ev(up, (300.0, 400.0), Mods::default())), circle(&[(300.0, 300.0), (300.0, 400.0)])); + click(&mut t, &cx, (300.0, 300.0)); + t.pointer(&cx, &ev(down, (380.0, 360.0), Mods::default())); + assert_eq!(t.pointer(&cx, &ev(up, (381.0, 360.0), Mods::default())), circle(&[(300.0, 300.0), (380.0, 360.0)])); +} + /// Three points on one line show no circle, and the release draws nothing and starts afresh. A /// circle past the canvas is not shown either. #[test] From 55b8fa8b6acb9330f69842449016fd5b4f02ac49 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 17 Nov 2026 17:31:06 -0800 Subject: [PATCH 168/176] Width Point Edit: the dialog and stroke.widthPoint.set share one pairing rule The dialog and stroke.widthPoint.set each tested whether two width points are the halves of one discontinuous point. The test is now one engine function, width_point_pair: a point and the next one are the two halves when they are the only points within 1e-6 of the first one's place. The dialog still picks which point to test, and the command still returns its error when the indices are not a pair. --- crates/engine/src/cmd/distortcmds.rs | 14 +++++++++++--- crates/engine/src/lib.rs | 2 +- crates/ui-egui/src/dialogs/width_point.rs | 16 ++++------------ 3 files changed, 16 insertions(+), 16 deletions(-) diff --git a/crates/engine/src/cmd/distortcmds.rs b/crates/engine/src/cmd/distortcmds.rs index c1ca7ac644..f5d38c0bba 100644 --- a/crates/engine/src/cmd/distortcmds.rs +++ b/crates/engine/src/cmd/distortcmds.rs @@ -214,6 +214,15 @@ fn uniform() -> WidthProfile { /// Width points closer than this (in t) are at the same place: a discontinuous point. const SAME_T: f64 = 1e-6; +/// The outgoing half of the discontinuous width point whose incoming half is point `a`: point `a` +/// and the next one are the two halves when they are the only points within 1e-6 (in t) of `a`'s +/// place. None when `a` is out of range or not such an incoming half. +pub fn width_point_pair(points: &[(f64, f64, f64)], a: usize) -> Option<usize> { + let t = points.get(a)?.0; + let at: Vec<usize> = (0..points.len()).filter(|i| (points[*i].0 - t).abs() <= SAME_T).collect(); + (at == [a, a + 1]).then_some(a + 1) +} + /// The stroke of `id` that width point commands edit (a compound path's for its members). fn stroke_mut(d: &mut Document, id: NodeId) -> Result<&mut vectorcraft_doc::StrokeLayer> { let id = stroke_owner(d, id); @@ -316,11 +325,10 @@ fn set_pair( single: Option<bool>, ) -> Result<usize> { const C: &str = "stroke.widthPoint.set"; - let at = points.get(i).map_or(f64::NAN, |q| q.0); - let halves: Vec<usize> = (0..points.len()).filter(|k| (points[*k].0 - at).abs() <= SAME_T).collect(); - if halves != [i, j] { + if width_point_pair(points, i) != Some(j) { return Err(bad(C, "`index` and `outIndex` must be the two halves of one discontinuous width point")); } + let at = points[i].0; let (old_in, old_out) = (points[i], points[j]); if (old_in.0 - inc.0).abs() > SAME_T { return Err(bad(C, "a discontinuous width point keeps its place")); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 4f7532108d..5381a549de 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -28,7 +28,7 @@ use vectorcraft_tools::{PaintDefaults, Tool}; pub use cmd::clipboard::{Clipboard, SourceLayer}; pub use cmd::create::constrain_click; -pub use cmd::distortcmds::perspective_click; +pub use cmd::distortcmds::{perspective_click, width_point_pair}; pub use cmd::graph::{GraphTypeSubject, calculated_axes as graph_calculated_axes, graph_type_subject}; pub use cmd::params::{check_keys, check_params}; pub use cmd::pathops::auto_simplify_level; diff --git a/crates/ui-egui/src/dialogs/width_point.rs b/crates/ui-egui/src/dialogs/width_point.rs index 0c4c41c356..b0881b9082 100644 --- a/crates/ui-egui/src/dialogs/width_point.rs +++ b/crates/ui-egui/src/dialogs/width_point.rs @@ -21,6 +21,7 @@ use egui::vec2; use serde_json::{Value, json}; use vectorcraft_doc::Unit; use vectorcraft_engine::doc::NodeId; +use vectorcraft_engine::width_point_pair; use super::swatch_options::{grid, label}; use super::{DialogSpec, run_and_close}; @@ -30,10 +31,6 @@ use crate::{VectorcraftApp, widgets}; /// The dialog kind of Width Point Edit. pub const KIND: &str = "widthPoint"; -/// Width points closer than this (in t) are the two halves of one discontinuous point, as the -/// engine and the Width tool count them. -const SAME_T: f64 = 1e-6; - pub(super) const SPEC: DialogSpec = DialogSpec { heading: |_| tl!("Width Point Edit").into(), body, confirm, discard: Some("Delete"), min_width: 300.0, ..DialogSpec::FORM }; @@ -45,17 +42,12 @@ fn point(app: &VectorcraftApp, id: u64, index: usize) -> Option<(f64, f64, f64)> } /// The incoming and outgoing halves of the discontinuous point that width point `index` of `id` -/// belongs to, or none when it is a continuous point. As `stroke.widthPoint.set` pairs them, a -/// point `a` and the next one are the two halves when they are the only points within -/// [`SAME_T`] of `a`'s place, so either half finds the same pair. +/// belongs to, or none when it is a continuous point. The halves are paired by +/// [`width_point_pair`], as `stroke.widthPoint.set` pairs them, so either half finds the same pair. fn halves(app: &VectorcraftApp, id: u64, index: usize) -> Option<(usize, usize)> { let points = &app.session.active()?.doc.node(NodeId(id))?.appearance.stroke()?.profile.as_ref()?.points; points.get(index)?; - let pair = |a: usize| { - let t = points.get(a)?.0; - let at: Vec<usize> = (0..points.len()).filter(|i| (points[*i].0 - t).abs() <= SAME_T).collect(); - (at == [a, a + 1]).then_some((a, a + 1)) - }; + let pair = |a: usize| width_point_pair(points, a).map(|b| (a, b)); pair(index).or_else(|| index.checked_sub(1).and_then(pair)) } From 385b4c5e82ec5400e36714631addc4bbf1219ce8 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 17 Nov 2026 17:45:15 -0800 Subject: [PATCH 169/176] Cut: direct-selection Cut removes whole and emptied paths in one pass per parent Cut with direct-selected anchors or segments removed each object selected whole, and each path it left with no segment, with its own remove. Every removal shifted the siblings after it, so later lookups walked the document's tree again. With 2,000 roots removed whole, the old loop walked the tree 10,005 times. These removals now go through the same batch that already places the surviving pieces, which rebuilds the children of each layer or group once, and compound paths left with no members are removed after it. A compound path left with one member stays a compound path. The document, the selection, the clipboard and the undo step are the same as before. With 2,000 of 10,000 squares on one layer selected whole and two anchors of another picked, Cut walks the tree 8 times instead of 10,005 and takes a median of 11 ms of CPU time instead of 573 ms (release build on Linux, seven alternating runs in one process). --- crates/engine/src/cmd/edit.rs | 33 ++- crates/engine/src/cmd/edit/tests.rs | 343 ++++++++++++++++++++++++++++ docs/target-app-parity.md | 1 + 3 files changed, 360 insertions(+), 17 deletions(-) create mode 100644 crates/engine/src/cmd/edit/tests.rs diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index fbf5deb568..466f689596 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -1076,8 +1076,10 @@ fn cut(s: &mut Session, p: &Value) -> Result<Value> { /// Select every surviving piece while retaining intentional compound-path structure. /// `roots` contains the copied targets: whole-object roots are removed in full, while partial paths /// lose only the copied geometry. An exhausted partial path is removed, along with its compound -/// parent if now empty; layers remain. Returns JSON `null` on success, replacing direct-selection -/// references with surviving object IDs. +/// parent if now empty; a compound left with one member stays a compound path, as after Clear; +/// layers remain. Removed and replaced roots go through one [`super::pathops::Beside`], which +/// rebuilds each parent's children once when the roots are separate. Returns JSON `null` on +/// success, replacing direct-selection references with surviving object IDs. fn cut_direct_selection(s: &mut Session, roots: &[NodeId]) -> Result<Value> { let st = s.doc()?; let sel = st.selection.clone(); @@ -1085,13 +1087,18 @@ fn cut_direct_selection(s: &mut Session, roots: &[NodeId]) -> Result<Value> { // The selected ruler guides were copied too (#3226): they go in the same undo step. let gone = selection.guides.clone(); d.retain_guides(selection, |g| !g.id.is_some_and(|id| gone.contains(&id))); + // The compound paths that hold a root; one left with no members goes too. + let compounds: BTreeSet<NodeId> = roots + .iter() + .filter_map(|id| d.parent_of(*id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. })))) + .collect(); let mut survivors = vec![]; let mut pieces = super::pathops::Beside::replacing(d, roots); for id in roots { let Some(node) = d.node(*id) else { continue }; let has_direct = sel.anchors.contains_key(id) || sel.segments.contains_key(id); if !has_direct || node.path_data().is_none() { - remove_leaving_no_empty_compound(d, *id)?; + pieces.put(d, *id, vec![])?; continue; } let original = super::path::deletion_source(d, *id)?; @@ -1114,12 +1121,14 @@ fn cut_direct_selection(s: &mut Session, roots: &[NodeId]) -> Result<Value> { } subpaths.retain(|sp| sp.anchors.len() >= 2); if subpaths.is_empty() { - remove_leaving_no_empty_compound(d, *id)?; + pieces.put(d, *id, vec![])?; } else { survivors.extend(super::path::replace_deleted_pieces(d, &mut pieces, original, subpaths)?); } } pieces.finish(d)?; + let emptied: Vec<NodeId> = compounds.into_iter().filter(|p| d.node(*p).is_some_and(|n| n.children().is_some_and(|c| c.is_empty()))).collect(); + super::pathops::remove_each(d, &emptied)?; selection.set(survivors); selection.anchors.clear(); selection.segments.clear(); @@ -1128,19 +1137,6 @@ fn cut_direct_selection(s: &mut Session, roots: &[NodeId]) -> Result<Value> { ok() } -/// Remove object `id`, and the compound path that held it when it was the compound's last member. -/// A compound left with one member stays a compound path, as after Clear. -fn remove_leaving_no_empty_compound(d: &mut Document, id: NodeId) -> Result<()> { - let parent = d.parent_of(id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. }))); - d.remove(id)?; - if let Some(p) = parent - && d.node(p).is_some_and(|n| n.children().is_some_and(|c| c.is_empty())) - { - d.remove(p)?; - } - Ok(()) -} - fn clear(s: &mut Session, p: &Value) -> Result<Value> { let guides = switch_or(p, "guides", false, "edit.clear")?; let explicit = if p.get("ids").is_some() { Some(checked_ids_param(s, p, "ids", "edit.clear")?) } else { None }; @@ -1751,3 +1747,6 @@ pub(crate) fn copy_above(d: &mut Document, roots: &[NodeId], mut change: impl Fn pub(crate) fn arc_nodes(v: Vec<Node>) -> Vec<Arc<Node>> { v.into_iter().map(Arc::new).collect() } + +#[cfg(test)] +mod tests; diff --git a/crates/engine/src/cmd/edit/tests.rs b/crates/engine/src/cmd/edit/tests.rs new file mode 100644 index 0000000000..8146bec6c2 --- /dev/null +++ b/crates/engine/src/cmd/edit/tests.rs @@ -0,0 +1,343 @@ +//! Cut with direct-selected anchors removes the objects selected whole and the paths it empties +//! through one [`Beside`](super::super::pathops::Beside), and leaves the document, the selection, +//! the clipboard and the undo history exactly as removing each of them on its own does. + +use std::collections::BTreeSet; +use std::time::{Duration, Instant}; + +use serde_json::{Value, json}; +use vectorcraft_doc::{Document, NodeId, NodeKind, tree_walks}; + +use super::*; +use crate::tests_large_edits::{session, square}; + +/// Cut's removal with every root selected whole or emptied taken out by its own +/// [`Document::remove`], and its compound path removed right after when that left it empty. The +/// tests compare [`cut_direct_selection`] with it. +fn cut_one_at_a_time(s: &mut Session, roots: &[NodeId]) -> Result<Value> { + let st = s.doc()?; + let sel = st.selection.clone(); + s.edit("Cut", |d, selection| { + let gone = selection.guides.clone(); + d.retain_guides(selection, |g| !g.id.is_some_and(|id| gone.contains(&id))); + let mut survivors = vec![]; + let mut pieces = super::super::pathops::Beside::replacing(d, roots); + for id in roots { + let Some(node) = d.node(*id) else { continue }; + let has_direct = sel.anchors.contains_key(id) || sel.segments.contains_key(id); + if !has_direct || node.path_data().is_none() { + remove_one(d, *id)?; + continue; + } + let original = super::super::path::deletion_source(d, *id)?; + let seg_refs = sel.segments.get(id); + let anchor_refs = sel.anchors.get(id); + let mut subpaths = Vec::new(); + let owned = std::mem::take(&mut super::super::path::path_mut(d, *id)?.subpaths); + for (si, sp) in owned.into_iter().enumerate() { + let cuts = super::super::clipboard::subpath_selected_segments(&sp, si, seg_refs, anchor_refs); + if cuts.is_empty() { + subpaths.push(sp); + } else if seg_refs.is_some_and(|segments| !segments.is_empty()) { + subpaths.extend(super::super::path::without_segments(sp, &cuts)); + } else { + let gone: BTreeSet<usize> = anchor_refs.into_iter().flat_map(|refs| super::super::path::subpath_refs(refs, si)).collect(); + subpaths.extend(super::super::path::without_anchors(sp, &gone)); + } + } + subpaths.retain(|sp| sp.anchors.len() >= 2); + if subpaths.is_empty() { + remove_one(d, *id)?; + } else { + survivors.extend(super::super::path::replace_deleted_pieces(d, &mut pieces, original, subpaths)?); + } + } + pieces.finish(d)?; + selection.set(survivors); + selection.anchors.clear(); + selection.segments.clear(); + Ok(()) + })?; + ok() +} + +/// Removes object `id`, and the compound path that held it when it was the compound's last member. +fn remove_one(d: &mut Document, id: NodeId) -> Result<()> { + let parent = d.parent_of(id).filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. }))); + d.remove(id)?; + if let Some(p) = parent + && d.node(p).is_some_and(|n| n.children().is_some_and(|c| c.is_empty())) + { + d.remove(p)?; + } + Ok(()) +} + +/// Cut as `edit.cut` runs it for a direct selection, with [`cut_one_at_a_time`] in place of +/// [`cut_direct_selection`]. +fn reference_cut(s: &mut Session) { + let (direct, roots) = copy_cut_targets(s).unwrap(); + assert!(direct, "the selection is a direct selection"); + copy(s, &json!({})).unwrap(); + cut_one_at_a_time(s, &roots).unwrap(); +} + +fn run(s: &mut Session, cmd: &str, p: Value) -> Value { + s.execute(cmd, &p).unwrap_or_else(|e| panic!("{cmd}: {e}")) +} + +/// Selects `whole` as objects, then anchors `anchors` of each path in `partial`. +fn select_direct(s: &mut Session, whole: &[NodeId], partial: &[(NodeId, Value)]) { + run(s, "select.set", json!({"ids": whole.iter().map(|id| id.0).collect::<Vec<_>>()})); + for (id, anchors) in partial { + run(s, "select.anchors", json!({"id": id.0, "anchors": anchors, "mode": "add"})); + } +} + +/// The ids of every node of the document, depth first, with the depth of each. +fn tree(d: &Document) -> Vec<(usize, NodeId)> { + fn walk(n: &vectorcraft_doc::Node, depth: usize, out: &mut Vec<(usize, NodeId)>) { + out.push((depth, n.id)); + for c in n.children().into_iter().flatten() { + walk(c, depth + 1, out); + } + } + let mut out = vec![]; + for l in &d.layers { + walk(l, 0, &mut out); + } + out +} + +/// Whether `a` and `b` hold the same document, selection, clipboard and number of undo and redo +/// steps. +fn assert_same(a: &Session, b: &Session, when: &str) { + let (x, y) = (a.doc().unwrap(), b.doc().unwrap()); + assert_eq!(tree(&x.doc), tree(&y.doc), "{when}: the tree"); + assert!(*x.doc == *y.doc, "{when}: the document"); + assert_eq!(x.selection, y.selection, "{when}: the selection"); + // Each session's document has its own uid; the clipboard names the one it came from. + assert_eq!(a.clipboard.source_doc.is_some(), b.clipboard.source_doc.is_some(), "{when}: the clipboard's source"); + let unsourced = |c: &Clipboard| Clipboard { source_doc: None, ..c.clone() }; + assert!(unsourced(&a.clipboard) == unsourced(&b.clipboard), "{when}: the clipboard"); + assert_eq!(x.history.undo.len(), y.history.undo.len(), "{when}: the undo steps"); + assert_eq!(x.history.redo.len(), y.history.redo.len(), "{when}: the redo steps"); +} + +/// Runs `edit.cut` on one session that `make` builds and [`reference_cut`] on another, and checks +/// that both hold the same after the Cut, after Undo and after Redo. Returns the first session after +/// the Cut. +fn same_as_one_at_a_time(make: impl Fn() -> Session) -> Session { + let (mut a, mut b) = (make(), make()); + let before = a.doc().unwrap().doc.clone(); + assert_same(&a, &b, "before"); + run(&mut a, "edit.cut", json!({})); + reference_cut(&mut b); + assert_same(&a, &b, "Cut"); + let after = a.doc().unwrap().doc.clone(); + run(&mut a, "edit.undo", json!({})); + run(&mut b, "edit.undo", json!({})); + assert_same(&a, &b, "Undo"); + assert!(*a.doc().unwrap().doc == *before, "Undo gives back the document"); + run(&mut a, "edit.redo", json!({})); + run(&mut b, "edit.redo", json!({})); + assert_same(&a, &b, "Redo"); + assert!(*a.doc().unwrap().doc == *after, "Redo gives back the Cut"); + run(&mut a, "edit.undo", json!({})); + run(&mut a, "edit.redo", json!({})); + a +} + +/// A new document; [`rect`] adds squares to it. +fn new_doc() -> Session { + let mut s = Session::new(); + run(&mut s, "file.new", json!({"width": 800, "height": 600})); + s +} + +/// Adds a 10 pt square to the current layer, 20 pt right of the last one. +fn rect(s: &mut Session) -> NodeId { + let x = 20.0 * s.doc().unwrap().doc.node_count() as f64; + NodeId(run(s, "shape.rectangle", json!({"x": x, "y": 10, "width": 10, "height": 10}))["id"].as_u64().unwrap()) +} + +/// Makes a compound path of `ids` and returns it with its members in order. +fn compound(s: &mut Session, ids: &[NodeId]) -> (NodeId, Vec<NodeId>) { + run(s, "select.set", json!({"ids": ids.iter().map(|id| id.0).collect::<Vec<_>>()})); + let c = NodeId(run(s, "object.compoundPath.make", json!({}))["id"].as_u64().unwrap()); + let members = s.doc().unwrap().doc.node(c).unwrap().children().unwrap().iter().map(|m| m.id).collect(); + (c, members) +} + +/// Anchors 0 to 2 of a square: Cut leaves it no segment, so it is removed. +fn three_anchors() -> Value { + json!([[0, 0], [0, 1], [0, 2]]) +} + +/// Anchors 0 and 1 of a square: Cut keeps its other three sides. +fn two_anchors() -> Value { + json!([[0, 0], [0, 1]]) +} + +/// The compound path whose members are cut one whole and one emptied goes with them; the other +/// compound path keeps its one member left, as a compound path. +#[test] +fn cut_removes_a_compound_whose_members_all_go_and_keeps_one_with_one_member_left() { + let make = || { + let mut s = new_doc(); + let first = [(); 2].map(|()| rect(&mut s)); + let (gone, gone_members) = compound(&mut s, &first); + let second = [(); 3].map(|()| rect(&mut s)); + let (kept, kept_members) = compound(&mut s, &second); + let other = rect(&mut s); + select_direct( + &mut s, + &[gone_members[0], kept_members[0]], + &[(gone_members[1], three_anchors()), (kept_members[1], three_anchors()), (other, two_anchors())], + ); + (s, gone, kept, kept_members[2], other) + }; + let s = same_as_one_at_a_time(|| make().0); + let (_, gone, kept, left, other) = make(); + let d = &s.doc().unwrap().doc; + assert!(d.node(gone).is_none(), "the compound path whose members all went is removed"); + let kept = d.node(kept).expect("the compound path with a member left stays"); + assert!(matches!(kept.kind, NodeKind::Compound { .. })); + assert_eq!(kept.children().unwrap().iter().map(|m| m.id).collect::<Vec<_>>(), [left]); + assert_eq!(s.doc().unwrap().selection.objects, [other], "the cut square's other sides stay selected"); +} + +/// Objects inside two groups and on the layer, removed whole, emptied or cut apart between kept +/// siblings, keep the order and ids that removing them one at a time leaves. +#[test] +fn cut_inside_groups_keeps_the_order_and_ids_of_removing_one_at_a_time() { + let make = || { + let mut s = new_doc(); + let a = [(); 4].map(|()| rect(&mut s)); + run(&mut s, "select.set", json!({"ids": a.iter().map(|id| id.0).collect::<Vec<_>>()})); + run(&mut s, "object.group", json!({})); + let b = [(); 4].map(|()| rect(&mut s)); + run(&mut s, "select.set", json!({"ids": b.iter().map(|id| id.0).collect::<Vec<_>>()})); + run(&mut s, "object.group", json!({})); + let c = [(); 4].map(|()| rect(&mut s)); + select_direct( + &mut s, + &[a[0], a[2], b[3], c[1]], + &[(a[1], two_anchors()), (b[0], three_anchors()), (b[2], two_anchors()), (c[3], three_anchors())], + ); + s + }; + let s = same_as_one_at_a_time(make); + assert_eq!(s.doc().unwrap().selection.objects.len(), 2, "the two squares cut apart stay selected"); +} + +/// Selected ruler guides go with the objects, in the Cut's undo step. +#[test] +fn cut_removes_the_selected_guides_with_the_objects() { + let make = || { + let mut s = new_doc(); + let [a, b, c] = [(); 3].map(|()| rect(&mut s)); + run(&mut s, "guide.add", json!({"vertical": true, "pos": 30})); + run(&mut s, "guide.add", json!({"vertical": false, "pos": 40})); + select_direct(&mut s, &[a, c], &[(b, two_anchors())]); + run(&mut s, "guide.select", json!({"indexes": [1], "toggle": true})); + s + }; + let s = same_as_one_at_a_time(make); + assert_eq!(s.doc().unwrap().doc.ruler_guides().len(), 1, "the selected guide is removed"); + assert_eq!(s.clipboard.guides.len(), 1, "the selected guide is on the clipboard"); +} + +/// Roots that are not separate (one inside another) are removed one at a time, as before. +#[test] +fn cut_of_roots_inside_another_root_matches_removing_one_at_a_time() { + let make = || { + let mut s = new_doc(); + let a = [(); 3].map(|()| rect(&mut s)); + run(&mut s, "select.set", json!({"ids": a.iter().map(|id| id.0).collect::<Vec<_>>()})); + let group = NodeId(run(&mut s, "object.group", json!({}))["id"].as_u64().unwrap()); + let b = rect(&mut s); + select_direct(&mut s, &[group, b], &[(a[1], two_anchors())]); + (s, vec![a[1], group, b]) + }; + let (mut x, roots) = make(); + let (mut y, _) = make(); + copy(&mut x, &json!({})).unwrap(); + copy(&mut y, &json!({})).unwrap(); + cut_direct_selection(&mut x, &roots).unwrap(); + cut_one_at_a_time(&mut y, &roots).unwrap(); + assert_same(&x, &y, "Cut"); +} + +/// One layer of 10,000 squares with every fifth of the first 10,000 selected whole (2,000) and +/// anchors 0 and 1 of the square after them picked. +fn many() -> Session { + let mut s = session(10_001, square); + let ids = crate::tests_large_edits::layer(&s, 0); + let whole: Vec<NodeId> = ids.iter().take(10_000).step_by(5).copied().collect(); + select_direct(&mut s, &whole, &[(ids[10_000], two_anchors())]); + s +} + +/// The tree walks [`tree_walks`] counts while `f` runs on `s`. +fn walks(s: &mut Session, f: impl FnOnce(&mut Session)) -> u64 { + let before = tree_walks(); + f(s); + tree_walks() - before +} + +/// Cut of 2,000 objects selected whole among 10,000, with a direct selection, walks the document's +/// tree a few times, where removing them one at a time walks it several times for each object. +#[test] +fn direct_selection_cut_of_2000_of_10000_objects_takes_few_tree_walks() { + let s = same_as_one_at_a_time(many); + assert_eq!(crate::tests_large_edits::layer(&s, 0).len(), 8_001); + let (mut a, mut b) = (many(), many()); + let batched = walks(&mut a, |s| { + run(s, "edit.cut", json!({})); + }); + let one_at_a_time = walks(&mut b, reference_cut); + println!("tree walks: Cut {batched}, one at a time {one_at_a_time}"); + assert!(batched <= 64, "Cut walked the document's tree {batched} times"); + assert!(one_at_a_time >= 4 * batched.max(1), "one at a time walked it {one_at_a_time} times, Cut {batched}"); +} + +/// This thread's CPU time, where the system reports it (`/proc/thread-self/schedstat` on Linux). +fn cpu_time() -> Option<Duration> { + let stat = std::fs::read_to_string("/proc/thread-self/schedstat").ok()?; + stat.split_whitespace().next()?.parse().ok().map(Duration::from_nanos) +} + +/// The middle of `v`. +fn median(mut v: Vec<Duration>) -> Duration { + v.sort_unstable(); + v[v.len() / 2] +} + +/// Times Cut of [`many`] and [`reference_cut`] seven times each, in turn, and prints every run's +/// CPU and wall-clock time with the medians. Run it with +/// `cargo test --release -p vectorcraft-engine --lib -- --ignored --nocapture direct_selection_cut_timing`. +#[test] +#[ignore = "timing; prints the numbers"] +fn direct_selection_cut_timing() { + let mut runs: [(Vec<Duration>, Vec<Duration>); 2] = Default::default(); + for round in 0..7 { + for (k, (cpu, wall)) in runs.iter_mut().enumerate() { + let mut s = many(); + let (c0, w0) = (cpu_time(), Instant::now()); + if k == 0 { + reference_cut(&mut s); + } else { + run(&mut s, "edit.cut", json!({})); + } + let w = w0.elapsed(); + let c = c0.zip(cpu_time()).map(|(a, b)| b.saturating_sub(a)).unwrap_or(w); + println!("round {round} {}: cpu {c:?}, wall {w:?}", ["one at a time", "Cut"][k]); + cpu.push(c); + wall.push(w); + } + } + for (k, (cpu, wall)) in runs.into_iter().enumerate() { + println!("median {}: cpu {:?}, wall {:?}", ["one at a time", "Cut"][k], median(cpu), median(wall)); + } +} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index ef83de54ad..0861a6e8b1 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -2200,6 +2200,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur The canvas keeps the selected objects' outlines, anchors and handles from one frame to the next as one mesh. It builds an object's marks again when the object, its layer color or its selected anchors change. A pan moves the kept outlines and handles and places the anchor squares again. Each subpath and handle gets its triangles the first time it is in view. A frame with a new zoom or rotation draws the marks one shape at a time and keeps nothing, and the next frame at that view builds them. The pixels are the same, apart from two small differences: a kept outline's corner of exactly 90 degrees in a rotated view can keep its miter or cut corner after a pan, and kept vertices can move by rounding errors. On Windows at 1440 × 900, in a release build, with 2,000 selected circles of 50 anchors each in 10 fill colors, an idle frame takes 12.8 ms instead of 59.9 ms with the Selection tool and 29.8 ms instead of 192.1 ms with Direct Selection (medians of five runs). A frame during a zoom takes about what it did: 86.7 ms instead of 80.0 ms with the Selection tool. Delete, Cut, Group, Ungroup, Make and Release Compound Path, Make Clipping Mask, Send to Current Layer, Duplicate, Copy in the Move, Rotate, Scale, Reflect and Shear dialogs, Transform Each with Copy and each move of an Alt-drag take time in proportion to the size of the document (#1429). Cut, and Clear with `ids`, take the removed objects out of the selection in one pass over the selected objects. With 50,000 objects selected and all of them cut, that step takes 5.07 to 5.91 ms instead of 544 to 630 ms, with 20,000 it takes 1.75 to 1.87 ms instead of 91.7 to 97.2 ms, and with 2,000 it takes 0.120 to 0.148 ms instead of 0.940 to 0.955 ms (release build, 7 wall-clock runs of each, measured while other builds were running). + Cut with direct-selected anchors or segments removes the objects selected whole and the paths it leaves with no segment in one pass over each layer or group that holds them, and then removes the compound paths left with no members, instead of removing each one on its own. The document, the selection, the clipboard and the undo step are the same as before. With 2,000 of 10,000 squares on one layer selected whole and two anchors of another picked, Cut walked the document's tree 10,005 times and now walks it 8 times, and takes a median of 11 ms of CPU time instead of 573 ms (release build on Linux, seven alternating runs of each in one process, `cargo test --release -p vectorcraft-engine --lib -- --ignored --nocapture direct_selection_cut_timing`). Tests: `cmd::edit::tests` in `crates/engine/src/cmd/edit/tests.rs`. In the web build the status bar's render and UI times are measured with the browser's `performance.now()`, and the Layers panel stops rendering row thumbnails in a frame once they have taken 8 ms. On the desktop, the Layers panel renders a row's thumbnail on its thumbnail thread when the row's paths, and the paths of its opacity masks that are not disabled, hold more than 2,000 anchors in all. It already did this for the first thumbnail of a row of more than 200 objects. Until its first thumbnail is ready, the row shows boxes at the bounds of up to 41 of its paths, each in its path's solid fill or stroke color or in gray, when its own paths, without its opacity masks, hold at most 2,000 anchors in all, and an empty white box otherwise. With one path of 200,000 anchors, the first frame after the panel opens takes 2.4 ms instead of 393 ms (release build, median of three runs). The same 2,000-anchor limit counts each glyph of type as 4 anchors, each point of a gradient mesh as 1 and every 100 pixels of an image as 1, and a symbol instance or a placed document counts the objects and anchors of the art it shows. A placed document whose file has not been read yet, or a symbol nested more than 8 deep (one that holds an instance of itself, for example), gets its first thumbnail on the thumbnail thread, and so does a row whose art takes more than 20,000 steps to count (each object, subpath, text run and symbol looked at is one step). The first frame after the panel opens takes 2.4 ms instead of 19.8 ms with 5,000 glyphs of point type, 1.8 ms instead of 343 ms with one instance of a symbol of a 200,000-anchor path, 2.0 ms instead of 11.0 ms with a 100 × 100 mesh, and 2.1 ms instead of 274 ms with a placed document of a 200,000-anchor path (release build, median of three runs). From 89b0c5b72b3c47f7d167a443dd77d854826de731 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 17 Nov 2026 18:01:57 -0800 Subject: [PATCH 170/176] Width Point: stroke.widthPoint.set refuses outgoing widths without outIndex A call with outLeft or outRight but no outIndex set the incoming point alone and reported success, so the outgoing widths were dropped. It is now refused as a missing outIndex, and the document and history stay as they are. --- crates/engine/src/cmd/distortcmds.rs | 4 +++- crates/engine/src/tests/widthpoints.rs | 2 ++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/cmd/distortcmds.rs b/crates/engine/src/cmd/distortcmds.rs index f5d38c0bba..dc36e24380 100644 --- a/crates/engine/src/cmd/distortcmds.rs +++ b/crates/engine/src/cmd/distortcmds.rs @@ -367,8 +367,10 @@ fn width_point_set(s: &mut Session, p: &Value) -> Result<Value> { Some(_) => return Err(bad(C, "`single` must be `incoming` or `outgoing`")), }; // The outgoing half of a discontinuous point: its index and side widths (points). + // `single`, `outLeft` or `outRight` without `outIndex` is refused as a missing `outIndex`. + let out_widths = ["outLeft", "outRight"].iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null())); let out = match p.get("outIndex") { - None | Some(Value::Null) if single.is_none() => None, + None | Some(Value::Null) if single.is_none() && !out_widths => None, _ => { let j = usize::try_from(u64_req(p, "outIndex", C)?).map_err(|_| bad(C, "no such width point"))?; let (l, r) = (f64_req(p, "outLeft", C)?, f64_req(p, "outRight", C)?); diff --git a/crates/engine/src/tests/widthpoints.rs b/crates/engine/src/tests/widthpoints.rs index a76e1a2227..bed235421e 100644 --- a/crates/engine/src/tests/widthpoints.rs +++ b/crates/engine/src/tests/widthpoints.rs @@ -275,6 +275,8 @@ fn paired_set_refuses_what_is_not_one_discontinuous_point() { pair(json!({"outLeft": 1.0e6})), pair(json!({"single": "both"})), pair(json!({"single": true})), + pair(json!({"outIndex": null})), + pair(json!({"outIndex": null, "outLeft": null})), json!({"id": id.0, "index": 2, "t": 0.5, "left": 5, "right": 5, "single": "incoming"}), ] { assert!(s.execute("stroke.widthPoint.set", &p).is_err(), "accepted {p}"); From bbfa29789be888677769c3509d46cd2ab62cdc24 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 17 Nov 2026 18:02:24 -0800 Subject: [PATCH 171/176] Rerun CI From 149b9dc93c773f1e86e60a0cec98cc9a8a8d3c7c Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 17 Nov 2026 18:10:09 -0800 Subject: [PATCH 172/176] Docs: the PDF format entry appears once docs/target-app-parity.md listed the SVG/SVGZ and PDF format entry twice; the shorter copy is removed and the entry that also names the .ai and EPS image sources stays. --- docs/target-app-parity.md | 1 - 1 file changed, 1 deletion(-) diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index 41c1508015..d3ec03b658 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1927,7 +1927,6 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Save as Template writes a PDF-compatible `.ait` as well as a `.vctemplate`, which stays the default: the save panel and the web build's Save as Template dialog list both, and New from Template opens the `.ait` as an untitled document with its layers and art (`file.saveAsTemplate {format: "ait"}`, or a path ending in `.ait`). Save as Template always writes a file named with its template type's extension: `file.saveAsTemplate` saves a path ending in another format's extension (`card.png`) as `card.vctemplate` (or `card.ait`), the desktop save panel does the same with a Save As format's extension typed in it (`card.pdf` is saved as `card.vctemplate`), and `file.saveAs` and `document.save` refuse `ait` with an error that names `file.saveAsTemplate`. A `.ait` is PDF-compatible only: `aiVersion: "7"` is an error for it, and the web build's dialog shows no Version row for it. Exports refuse a `.ait` with an error that names `file.saveAsTemplate`, and `vectorcraft-cli convert in.pdf out.ait` and `run --export out.ait` write the template as `file.saveAsTemplate` does. - - SVG/SVGZ in and out with SVG Options, Preserve Editing, symbols, filters, rich text and physical units (SVG type under a transform or `viewBox` scale opens at the size it draws at, the scale moved into its size, leading, baseline shift and strokes, a stretch, skew or rotation kept as its transform: #396; a top-level group with a clip path, such as a clipped Inkscape layer, opens as a layer with a clipping mask, its name kept: #420; hidden objects written hidden on Save and `convert`, and `data-*` attributes kept as the objects' own data: #522; top-level groups open as layers named from `data-name`, else the id, also when one more group (a transform on all the art, a `<switch>`) wraps them, hidden ones hidden, and a file whose art sits loose under a root `<svg>` with an id (or `data-name`), as one-layer exports write it, opens with its one layer named from it; nested groups stay groups, except the sublayers VectorCraft writes, marked `data-vc-layer`, and Inkscape sublayers, which open as sublayers in their layer's colour: #372); PDF and PDF-compatible `.ai` in and out (layers, with hidden ones kept hidden with their art and nested ones as sublayers, on pages of up to 64 million operators, art whose layer can't be told going to a hidden, non-printing layer rather than showing or printing: #419; strokes kept live, a fill and a stroke of one outline as one object; a type object's stroke written as each glyph's outline stroked back on the type, so it stays one editable object; lines wrapped in a frame (each wrapped line ending in a space, one left edge, leading and font) back as one area type object, left aligned or justified with its paragraph spacing, where laying it out breaks the lines where the file does; glyphs set apart by gaps wider than a space (a barcode's digit groups) keeping their places; layers stacked as the pages mark them even when one first paints on a later page, art ending a layer's marked content or a clip closing in a later layer kept in its own layer, and layers with no art kept empty: #508; art reaching past a plain PDF's page clipped to its crop box, as PDF viewers show it, each such object in a clip group of its own (a PDF-compatible `.ai` opens whole: #675); a `.ai` on its trim boxes with the bleed boxes round them as the document's bleed, as Crop To › Trim opens a PDF (#1266); masks, editable text with type set along a curve coming back as type on a path, each artboard's art on its own page only, an `.ai`'s white page under its layers left out rather than coming in as art, spot colours, presets, security, marks and bleed, ICC output intents, raster effects, subset fonts, PDF/X, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3). CMYK images keep their ink amounts from PDF import (and from placed CMYK TIFFs) to PDF export: a CMYK JPEG passes through with its compressed samples unchanged (its `ICC_PROFILE` segments are removed when `output.profiles` is `none` (except in PDF/A, and in PDF/X-3 and PDF/X-4 files that do not write CMYK colors as DeviceCMYK) and in PDF/X-3 and PDF/X-4 when they are the CMYK output intent's profile and CMYK colors are DeviceCMYK), others stay CMYK (DeviceCMYK, or ICC-based CMYK in PDF/X-3/X-4 when not in the output intent's profile) unless the Output settings convert them; the canvas shows them through the working CMYK profile (#320). Overprint is kept from PDF import (opened, the PDF part of an `.ai`, placed) to PDF export: the graphics state's `/OP` and `/op` become the overprint of fills, strokes and type, so a spot colour over a process colour still overprints; a page whose overprint can't be read for certain knocks out with a note, as does `/OPM 0` being read as nonzero overprint (#1388; hand-written fixtures, `pdf/src/tests/import_overprint.rs`). A masked CMYK image (`/SMask`, `/Mask` or a colour key) keeps its inks too, its alpha coming in as a greyscale opacity mask. - SVG/SVGZ in and out with SVG Options, Preserve Editing, symbols, filters, rich text and physical units (SVG type under a transform or `viewBox` scale opens at the size it draws at, the scale moved into its size, leading, baseline shift and strokes, a stretch, skew or rotation kept as its transform: #396; a top-level group with a clip path, such as a clipped Inkscape layer, opens as a layer with a clipping mask, its name kept: #420; hidden objects written hidden on Save and `convert`, and `data-*` attributes kept as the objects' own data: #522; top-level groups open as layers named from `data-name`, else the id, also when one more group (a transform on all the art, a `<switch>`) wraps them, hidden ones hidden, and a file whose art sits loose under a root `<svg>` with an id (or `data-name`), as one-layer exports write it, opens with its one layer named from it; nested groups stay groups, except the sublayers VectorCraft writes, marked `data-vc-layer`, and Inkscape sublayers, which open as sublayers in their layer's colour: #372); PDF and PDF-compatible `.ai` in and out (layers, with hidden ones kept hidden with their art and nested ones as sublayers, on pages of up to 64 million operators, art whose layer can't be told going to a hidden, non-printing layer rather than showing or printing: #419; strokes kept live, a fill and a stroke of one outline as one object; a type object's stroke written as each glyph's outline stroked back on the type, so it stays one editable object; lines wrapped in a frame (each wrapped line ending in a space, one left edge, leading and font) back as one area type object, left aligned or justified with its paragraph spacing, where laying it out breaks the lines where the file does; glyphs set apart by gaps wider than a space (a barcode's digit groups) keeping their places; layers stacked as the pages mark them even when one first paints on a later page, art ending a layer's marked content or a clip closing in a later layer kept in its own layer, and layers with no art kept empty: #508; art reaching past a plain PDF's page clipped to its crop box, as PDF viewers show it, each such object in a clip group of its own (a PDF-compatible `.ai` opens whole: #675); a `.ai` on its trim boxes with the bleed boxes round them as the document's bleed, as Crop To › Trim opens a PDF (#1266); masks, editable text with type set along a curve coming back as type on a path, each artboard's art on its own page only, an `.ai`'s white page under its layers left out rather than coming in as art, spot colours, presets, security, marks and bleed, ICC output intents, raster effects, subset fonts, PDF/X, PDF layers, overprint, page thumbnails, fast web view, PDF 1.3). CMYK images keep their ink amounts from PDF import (and from placed CMYK TIFFs and the images in an `.ai` or EPS file's editing data, an alpha channel coming in as a grayscale opacity mask) to PDF export: a CMYK JPEG passes through with its compressed samples unchanged (its `ICC_PROFILE` segments are removed when `output.profiles` is `none` (except in PDF/A, and in PDF/X-3 and PDF/X-4 files that do not write CMYK colors as DeviceCMYK) and in PDF/X-3 and PDF/X-4 when they are the CMYK output intent's profile and CMYK colors are DeviceCMYK), others stay CMYK (DeviceCMYK, or ICC-based CMYK in PDF/X-3/X-4 when not in the output intent's profile) unless the Output settings convert them; the canvas shows them through the working CMYK profile (#320). Overprint is kept from PDF import (opened, the PDF part of an `.ai`, placed) to PDF export: the graphics state's `/OP` and `/op` become the overprint of fills, strokes and type, so a spot colour over a process colour still overprints; a page whose overprint can't be read for certain knocks out with a note, as does `/OPM 0` being read as nonzero overprint (#1388; hand-written fixtures, `pdf/src/tests/import_overprint.rs`). A masked CMYK image (`/SMask`, `/Mask` or a colour key) keeps its inks too, its alpha coming in as a greyscale opacity mask. In imported PDF type, a space glyph the file draws between two words also keeps the next word where the file has it when the gap beside the space is wide, as VectorCraft's own export draws a tracked space: the space gets tracking of its own, and the wrapped lines of a justified paragraph still come back as one area type object when the word gaps on each line are alike (part of #2384). Letter-spaced PDF type, whether set with character spacing (`Tc`) or glyph by glyph, keeps its word spaces and gains none between its letters: the spacing a line's letters share is taken off each gap before a gap reads as a space. That holds on a line that also shows where its words break, with spaces the file draws or gaps wider than the rest; evenly spaced glyphs alone, which could be words of one letter, keep every gap as a space, as do glyphs set more than half an em apart, such as figures in columns. From c66272a9e3b11fd32f56c152df09eeee7109e36f Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 17 Nov 2026 18:05:56 -0800 Subject: [PATCH 173/176] Layers: in Draw Behind a new layer goes directly below the current layer layer.new without `top` or `below` now reads the drawing mode: in Draw Behind the new layer goes directly below the current layer, at its level (a sibling below a current sublayer), as the help page describes (https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=234). The Layers panel button, the panel menu, Ctrl/Cmd+L and the Layer Options dialog all go through layer.new. `top` and `below` keep their meaning in every mode, Draw Normal and Draw Inside keep a new layer above the current one, and New Sublayer is not affected. --- crates/engine/src/cmd/layer.rs | 9 ++++-- crates/engine/src/tests/layers.rs | 48 +++++++++++++++++++++++++++++++ docs/mcp.md | 5 ++-- docs/target-app-parity.md | 2 +- 4 files changed, 58 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 237f0f9d49..7b459adfdc 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -29,7 +29,7 @@ pub fn specs() -> Vec<CommandSpec> { "New Layer…", ["Window", "Layers"], Some("Cmd+L"), - "{name?, top?: bool, below?: bool, color?, template?, locked?, visible?, printable?, preview?, dimImages?} a layer directly above the current layer, at its level (a sublayer beside a current sublayer); `top`: above all layers (Ctrl/Cmd-click the button); `below`: directly below the current layer, at its level (Ctrl/Cmd+Alt-click the button), not with `top`. Options as layer.setProps; refused while an opacity mask is edited (the Layers panel lists only the mask) → {id}", + "{name?, top?: bool, below?: bool, color?, template?, locked?, visible?, printable?, preview?, dimImages?} a layer directly above the current layer, at its level (a sublayer beside a current sublayer), or directly below it in Draw Behind; `top`: above all layers (Ctrl/Cmd-click the button); `below`: directly below the current layer, at its level (Ctrl/Cmd+Alt-click the button), not with `top`. Options as layer.setProps; refused while an opacity mask is edited (the Layers panel lists only the mask) → {id}", super::maskedit::outside_mask_editing, new_layer ), @@ -526,12 +526,15 @@ fn add_layer(s: &mut Session, p: &Value, cmd: &str, label: &str, place: impl FnO fn new_layer(s: &mut Session, p: &Value) -> Result<Value> { const C: &str = "layer.new"; let below = switch_or(p, "below", false, C)?; - if below && bool_or(p, "top", false) { + let top = bool_or(p, "top", false); + if below && top { return Err(bad(C, "`top` and `below` can't both be true")); } + // In Draw Behind a layer given neither `top` nor `below` goes below the current layer. + let below = below || (!top && s.draw_mode == crate::DrawMode::Behind); let st = s.doc()?; // Above the current layer, at its level; below it with `below`; on top of everything with `top`. - let cur = st.current_layer().filter(|_| !bool_or(p, "top", false)); + let cur = st.current_layer().filter(|_| !top); add_layer(s, p, C, "New Layer", |d| match cur.and_then(|c| d.position(c)) { Some((parent, i, _)) => Ok((parent, if below { i } else { i + 1 })), None => Ok((None, if below { 0 } else { usize::MAX })), diff --git a/crates/engine/src/tests/layers.rs b/crates/engine/src/tests/layers.rs index f6b35716f6..da7d573da2 100644 --- a/crates/engine/src/tests/layers.rs +++ b/crates/engine/src/tests/layers.rs @@ -481,6 +481,54 @@ fn new_layers_go_below_the_current_one_and_sublayers_under_the_contents() { assert_eq!(children(&s, layer), vec![front, under, back]); } +/// In Draw Behind a new layer goes directly below the current layer, at its level, in one undo +/// step; `top` and `below` keep their meaning, Draw Inside and Draw Normal keep it above, and new +/// sublayers are not affected. +#[test] +fn new_layers_go_below_the_current_one_in_draw_behind() { + let mut s = session(); + let (layer, sub, a, g, _, c) = tree(&mut s); + run(&mut s, "view.drawMode", json!({"mode": "behind"})); + run(&mut s, "layer.setCurrent", json!({"id": sub.0})); + let before = undos(&s); + let n = id(&run(&mut s, "layer.new", json!({}))); + assert_eq!(children(&s, layer), vec![c, n, sub], "a sublayer directly below the current sublayer"); + assert_eq!(undos(&s), before + 1); + assert_eq!(s.doc().unwrap().highlighted_rows(), vec![n]); + assert_eq!(s.doc().unwrap().current_layer(), Some(n)); + run(&mut s, "edit.undo", json!({})); + assert_eq!(children(&s, layer), vec![c, sub]); + // The Create New Layer button sends `top: false` for a plain click: still below. + run(&mut s, "layer.setCurrent", json!({"id": sub.0})); + let n = id(&run(&mut s, "layer.new", json!({"top": false}))); + assert_eq!(children(&s, layer), vec![c, n, sub]); + run(&mut s, "edit.undo", json!({})); + // At the top level, and with options. + run(&mut s, "layer.setCurrent", json!({"id": layer.0})); + let back = id(&run(&mut s, "layer.new", json!({"name": "Back", "locked": true}))); + let order = |s: &Session| s.doc().unwrap().doc.layers.iter().map(|l| l.id).collect::<Vec<_>>(); + assert_eq!(order(&s), vec![back, layer]); + assert!(node(&s, back).locked); + // `top` and `below` win over the drawing mode. + let top = id(&run(&mut s, "layer.new", json!({"top": true}))); + assert_eq!(order(&s), vec![back, layer, top]); + let below = id(&run(&mut s, "layer.new", json!({"below": true}))); + assert_eq!(order(&s), vec![back, layer, below, top]); + assert!(s.execute("layer.new", &json!({"top": true, "below": true})).is_err()); + // New sublayers still go on top of the parent's contents. + let inner = id(&run(&mut s, "layer.newSublayer", json!({"parent": sub.0}))); + assert_eq!(children(&s, sub), vec![a, g, inner]); + // Draw Inside and Draw Normal put it above. + run(&mut s, "select.set", json!({"ids": [c.0]})); + for mode in ["inside", "normal"] { + run(&mut s, "view.drawMode", json!({"mode": mode})); + assert_eq!(s.draw_mode, if mode == "inside" { DrawMode::Inside } else { DrawMode::Normal }); + run(&mut s, "layer.setCurrent", json!({"id": back.0})); + let n = id(&run(&mut s, "layer.new", json!({}))); + assert_eq!(s.doc().unwrap().doc.layers[1].id, n, "{mode}"); + } +} + #[test] fn rows_move_above_below_and_into_layers_and_groups() { let mut s = session(); diff --git a/docs/mcp.md b/docs/mcp.md index 4c1b661f42..1a3da65de8 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5419,8 +5419,9 @@ and `layerRows`, the rows highlighted in the panel. inside it); a row never goes into itself or a row inside it, and a locked layer or group takes nothing. Dragging the selected-art square is `layer.move` with the selected objects. `node.move {id, parent?, index}` is the low-level form with the same nesting rules; unlike `layer.move`, it also moves a row into a locked layer or group. -- **Buttons**: `layer.new {name?, top?, below?, …options}` (above the current layer at its level; `top` with - Ctrl/Cmd; `below`, directly below the current layer at its level, with Ctrl/Cmd+Alt), +- **Buttons**: `layer.new {name?, top?, below?, …options}` (above the current layer at its level, or directly + below it in Draw Behind; `top` with Ctrl/Cmd; `below`, directly below the current layer at its level, with + Ctrl/Cmd+Alt; `top` and `below` apply in every drawing mode), `layer.newSublayer {parent?, bottom?, name?, …options}` (on top of the parent's contents; `bottom`, under them but above a clipping layer's clipping path, with Ctrl/Cmd+Alt; both refused while an opacity mask is edited), `layer.delete {ids?}` (rows with what they hold; the diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index ef83de54ad..bc2ccc9197 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1241,7 +1241,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - **Compound paths:** Make keeps the backmost object's appearance and each contour; selecting a member in Direct Selection reads and changes the compound's fill rule in Attributes. Direction remains a per-member edit. Rendered holes, unchanged contour geometry, no-op history and Undo/Redo are covered by `engine/tests/it/compound_attributes.rs` (#1197). Behaviour reference: [public compound-path documentation](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/create-compound-paths.html). Make Compound Path on a group (such as outlined type) keeps the paint of its backmost path instead of drawing nothing, and compound paths joined into one keep their holes (#1537). - **Saved selections:** Select ▸ Save Selection… asks for a name and keeps the selection in the document (saved with the file, undoable, up to 25); each one is listed at the bottom of the Select menu and a click selects its objects again; Edit Selection… lists them to rename or delete, applied together on OK. A file's saved selections are capped and checked against its objects when it opens. Select ▸ Update Selection replaces the objects of the saved selection last recalled with the selected objects, in one undo step that marks the document changed (`select.update`). After Edit Selection… renames that saved selection, Update Selection replaces it under the new name; after Edit Selection… deletes it, Update Selection is disabled until another saved selection is recalled or the delete is undone. Undo and Redo do not change which saved selection is recalled. - - **Drawing modes:** in Draw Inside, a double-click with a selection tool outside the object being drawn into sets the drawing mode to Draw Normal, as Shift+D does. Pastes follow the drawing mode ([drawing modes](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/drawing-modes-overview.html)) (#3705): in Draw Inside, Paste, Paste in Place and Paste on All Artboards put the copies inside the object drawn into, in one undo step, Paste Remembers Layers aside; in Draw Behind, Paste in Place and Paste on All Artboards put them just below the selection; Paste in Front and Paste in Back ignore the mode. Shift+D cycles Draw Normal → Draw Behind → Draw Inside → Draw Normal, skipping Draw Inside unless one path, compound path or type is selected. With the object drawn into isolated (a double-click on it with the Selection tool), art drawn or pasted inside it takes isolation mode into its clip group, so it can be clicked and isn't dimmed, as art added in isolation mode belongs with what is isolated ([isolation mode](https://helpx.adobe.com/illustrator/desktop/manage-objects/select-objects/isolate-objects.html)) (#3705); undo or redo that removes the isolated object ends isolation mode. While Draw Inside lasts, a dotted open rectangle marks the corners of the object drawn into (#4319). + - **Drawing modes:** in Draw Inside, a double-click with a selection tool outside the object being drawn into sets the drawing mode to Draw Normal, as Shift+D does. Pastes follow the drawing mode ([drawing modes](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/drawing-modes-overview.html)) (#3705): in Draw Inside, Paste, Paste in Place and Paste on All Artboards put the copies inside the object drawn into, in one undo step, Paste Remembers Layers aside; in Draw Behind, Paste in Place and Paste on All Artboards put them just below the selection; Paste in Front and Paste in Back ignore the mode. Shift+D cycles Draw Normal → Draw Behind → Draw Inside → Draw Normal, skipping Draw Inside unless one path, compound path or type is selected. With the object drawn into isolated (a double-click on it with the Selection tool), art drawn or pasted inside it takes isolation mode into its clip group, so it can be clicked and isn't dimmed, as art added in isolation mode belongs with what is isolated ([isolation mode](https://helpx.adobe.com/illustrator/desktop/manage-objects/select-objects/isolate-objects.html)) (#3705); undo or redo that removes the isolated object ends isolation mode. While Draw Inside lasts, a dotted open rectangle marks the corners of the object drawn into (#4319). In Draw Behind, New Layer (the Layers panel's button, its menu, Ctrl/Cmd+L and the Layer Options dialog) puts the new layer directly below the current layer, at its level, as [the help page](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=234) describes and [drawing modes](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/learn-drawing-basics/drawing-modes-overview.html) lists; Ctrl/Cmd-click still puts it on top and Ctrl/Cmd+Alt-click below, and New Sublayer is not affected (VectorCraft's own rule). - **Drawing:** Pen, Curvature, anchor tools, Pencil, Paintbrush, Blob Brush, Smooth, Path Eraser, Join. Direction handles dragged with Direct Selection or the Anchor Point tool snap to smart guides, and Shift keeps them at 45° steps from their anchor. The Pen continues any open path from the end clicked, and while drawing, a click on an end of another open path joins the two into one (#776). The Curvature tool edits any selected path, whatever drew it, keeping its shape except where edited (#798): a click on a point makes it current and a drag moves it, re-curving only its two segments; double-click, or Alt-click on any point but an end of an open path, toggles it smooth or corner and Delete removes it; a click on a segment adds a point without changing the shape; with an end of an open path current, clicks go on from it and its other end closes it (`path.curvatureEdit`). An Alt-click on an end of a selected open path makes that end current without changing it, so the next click goes on from it, as [the help page](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/draw-shapes-with-the-curvature-tool.html) describes for continuing a path; an Alt-click that starts a new path places a corner point, as later Alt-clicks do. Every point a drawing tool places snaps to Smart Guides through one snapper (#506): the Pen's and Curvature tool's anchors, the Pencil's ends, the shape tools' start and dragged corner or radius (Rectangle, Rounded Rectangle, Ellipse, Polygon, Star, Line Segment, Arc, Spiral, the grids), the Type tool's click and frame, a new artboard's corners. A filled Pencil path keeps a stroke of None (#1804, part of #1679). While a Pencil or Paintbrush stroke is drawn back to within Close Paths When Ends Are Within of its start, the cursor shows the closing ring and a release there closes the path, as [Draw straight lines with the Pencil tool](https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/draw-shapes/draw-straight-lines-with-the-pencil-tool.html) describes for the Pencil. The [ and ] keys reach the Blob Brush, the Eraser and the Symbolism tools in the app (#1734, part of #1661). Blob Brush and Eraser Tool Options' Size is Fixed or Pressure with a Variation (#4590, #3961): with Pressure a pen stroke is Size − Variation wide where it presses lightest and Size + Variation where it presses hardest, and a mouse stroke keeps the Size. `path.blob` and `path.eraseRegion` refuse a Size outside 0.1 to 1000 pt and a Variation outside 0 to 1000 pt, also with Size set to Fixed, and the drawing commands that read pen values refuse a pressure outside 0 to 1, a tilt outside −90° to 90°, a rotation outside 0° to 360° and a point array of more than six numbers, with an error naming the key; the document, the selection and the undo history stay as they were. The pressure and tilt ranges are those of [Pointer Events](https://www.w3.org/TR/pointerevents3/); the Size, Variation and rotation ranges are VectorCraft's own values (`tests::draw2::pen_values_outside_their_ranges_are_refused`). From ced9eefa1fc0e3082866936bbc2a3166d8a66a30 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 17 Nov 2026 18:21:31 -0800 Subject: [PATCH 174/176] Color: test that built-in CMYK profiles separate saturated inks back The colorimetric table of each built-in CMYK profile is checked on solid and two-color overprint inks: CMYK to the connection space and back through the profile's own tables lands within a Delta E 2000 of 3 of the original inks. --- crates/color/src/cms/tests_icc.rs | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/crates/color/src/cms/tests_icc.rs b/crates/color/src/cms/tests_icc.rs index e49e67082a..2c1d96638b 100644 --- a/crates/color/src/cms/tests_icc.rs +++ b/crates/color/src/cms/tests_icc.rs @@ -59,6 +59,25 @@ fn cmyk_profiles_convert_like_the_cms() { } } +#[test] +fn cmyk_profiles_separate_saturated_inks_back_without_clipping_to_srgb() { + // CMYK → PCS → CMYK through the profile's own colorimetric tables, by way of linear ProPhoto + // RGB, which holds every color these profiles print, so no display gamut clips the inks. + // Inks that print outside sRGB come back to inks that print the same color. + for name in BUILTIN_CMYK { + let p = IccProfile::from_bytes(None, &icc_bytes(name).unwrap()).unwrap(); + let cms = Cms::new(&ColorSettings { cmyk: name.into(), bpc: false, ..Default::default() }).unwrap(); + for inks in + [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [1.0, 1.0, 0.0, 0.0], [0.0, 1.0, 1.0, 0.0], [1.0, 0.0, 1.0, 0.0]] + { + let back = p.to_same_model_of(&p, &inks, Intent::RelativeColorimetric, false).unwrap(); + let de = delta_e2000(cms.cmyk_to_lab(inks), cms.cmyk_to_lab([back[0], back[1], back[2], back[3]])); + // Within the ΔE of 3 that the gamut tag counts as reproduced. + assert!(de <= 3.0, "{name} {inks:?} -> {back:?} (ΔE {de})"); + } + } +} + #[test] fn cmyk_profiles_carry_their_paper_as_the_media_white() { let generic = generic::swop_like(); From 67ee9657ac9f3c1dcdcc5d87cfa342393dc6e952 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Tue, 17 Nov 2026 18:24:55 -0800 Subject: [PATCH 175/176] Rerun CI From a55a511d5cae14ca9ce86f446e240f9701aea9d0 Mon Sep 17 00:00:00 2001 From: dotCooCoo <RobertLeeLW@gmail.com> Date: Mon, 16 Nov 2026 10:35:53 -0800 Subject: [PATCH 176/176] Tests: drop the confined single-file PDF test of several assets `assets.export` now refuses `pdfs: "single"` with assets, layers and `selection: "each"` before any file is checked or written (70fdab8445 on main), so the test's request no longer reaches the link check and fails with that refusal. A single-file PDF is now written only for artboards, whose items all hold the same document. (cherry picked from commit 80cf2172f1c258e685d7e3b3162c00f805cba705) --- crates/engine/src/tests/links.rs | 28 ---------------------------- 1 file changed, 28 deletions(-) diff --git a/crates/engine/src/tests/links.rs b/crates/engine/src/tests/links.rs index 87dd7453f6..313d573206 100644 --- a/crates/engine/src/tests/links.rs +++ b/crates/engine/src/tests/links.rs @@ -2542,34 +2542,6 @@ fn confined_screens_rows_check_the_artboard_each_file_holds() { } } -/// A confined caller's single-file PDF with Preserve Editing of several assets carries the first -/// asset's document alone, so only that document is checked: an image linked outside the read roots in a later asset does -/// not refuse it, and one in the first asset does. -#[test] -fn confined_single_file_pdf_checks_the_document_it_carries() { - use crate::file_access::{AutomationRoots, confine}; - - let away = Folder::new("single-pdf-away"); - let home = Folder::new("single-pdf-home"); - let photo = away.file("photo.png"); - write(&photo, &png(60, 30, RED)); - let mut s = session(); - let r = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 20})).unwrap(); - let rect: vectorcraft_doc::NodeId = serde_json::from_value(r["id"].clone()).unwrap(); - let placed = place(&mut s, &photo); - let mut assets = vec![]; - for id in [rect, placed] { - assets.push(s.execute("assets.add", &json!({"ids": [id.0]})).unwrap()["assets"][0].as_u64().unwrap()); - } - let roots = AutomationRoots::new(&[home.0.as_path()], &[home.0.as_path()]).unwrap(); - let p = |ids: &[u64], folder: &str| json!({"assets": ids, "folder": home.file(folder), "pdfs": "single", "formats": [{"format": "pdf", "preserveEditing": true}]}); - let r = confine(roots.as_ref(), || s.execute("assets.export", &p(&assets, "first-plain"))).unwrap_or_else(|e| panic!("{e}")); - assert_eq!(r["files"].as_array().map(Vec::len), Some(1), "{r}"); - let reversed = [assets[1], assets[0]]; - let e = confine(roots.as_ref(), || s.execute("assets.export", &p(&reversed, "first-linked"))).expect_err("first asset links outside").to_string(); - assert!(e.contains("a linked image file is outside the read roots"), "{e}"); -} - /// A confined caller's native outputs (a native file or template, an EPS or `.ai` file, a PDF with /// Preserve Editing, a package's document) carry the document without the Export for Screens /// folder when it is outside the read roots, with the other export settings and the art; the open