From 543034987eb6d2e31f73a6b373234c40e9802263 Mon Sep 17 00:00:00 2001 From: jmverges Date: Wed, 11 Nov 2026 19:33:22 +0000 Subject: [PATCH 01/38] Envelopes: type's strokes paint at their own weight along the bent outlines (#6644) With Envelope Options > Distort Appearance on, VectorCraft turned the strokes of type in an envelope into filled outlines and bent them with the art, so a stroke got thinner where the grid squeezes the type and thicker where it stretches it. The drawn art of users' .ai files keeps those strokes as stroked paths at the type's own weights, and the ring they paint is as wide wherever the grid squeezes or stretches the type. An envelope of stroked type in such a grid therefore didn't draw as its drawn art and kept it instead of opening live. Type's strokes (its characters' and those on its own appearance) now paint along the bent glyph outlines at their own weight, with Distort Appearance on or off, also in an envelope inside an envelope: - doc: `map_node` maps the groups that hold type's glyph outlines with `Hooks::type_appearance` in place of `Hooks::appearance`, for type in the envelope's contents and for type that a live object in them (an inner envelope) outlined (`Warper::type_outlines`). Such a group's opacity mask is mapped with the ordinary hooks, so it bends as other art does. Groups marked as type's outlines in the contents themselves (art an earlier Expand made) stay plain art. - effects: `bake_type_appearance`, `bake_appearance` with strokes kept as strokes: geometry effects on type's fills and strokes still bake in and bend. - doc: `max_outset` counts type's character strokes as type's own visual bounds do (`char_stroke_outset`). It left them out, though they already painted past an envelope's grid where the glyphs reach its edge; this also grows the visual bounds of blends and repeats of stroked type and the reach of symbol art holding it. Paths' strokes, geometry effects, opacity masks, linear gradients and pattern fills bend as before. The canvas, hit testing, effect bounds, Expand, every export and the .ai save take the evaluation from the same hooks. Expand of an envelope of stroked type gives the bent outlines with the strokes on them. This changes how VectorCraft's own envelopes of stroked type draw. Tests: envelope_distort::type_strokes_paint_at_their_own_weight_in_a_squeezed_envelope, a_stroke_on_types_appearance_paints_at_its_own_weight_in_a_squeezed_envelope, type_strokes_paint_at_their_own_weight_in_an_envelope_inside_an_envelope, a_paths_stroke_still_bends_in_a_squeezed_envelope, an_opacity_mask_on_type_bends_as_other_art, the_visual_bounds_of_an_envelope_hold_its_types_strokes, the_visual_bounds_of_a_repeat_of_stroked_type_grow_by_half_the_stroke, expanding_an_envelope_of_stroked_type_keeps_the_stroke_at_its_weight, bake::tests::type_pieces_bake_their_geometry_effects_and_keep_their_strokes and tests_native::an_envelope_of_stroked_type_whose_drawn_art_strokes_the_bent_outlines_at_the_weight_opens_live. Co-Authored-By: Claude Opus 5.5 --- crates/doc/src/live/envelope.rs | 5 +- crates/doc/src/live/expand.rs | 35 +++- crates/effects/src/bake.rs | 29 ++- crates/effects/src/bake/tests.rs | 21 ++ crates/effects/src/lib.rs | 2 +- crates/effects/src/live.rs | 10 +- crates/engine/src/tests/envelope_distort.rs | 207 ++++++++++++++++++++ crates/eps/src/import/tests_native.rs | 100 +++++++++- docs/file-format-parity.md | 3 +- docs/mcp.md | 10 +- docs/target-app-parity.md | 6 +- docs/type-parity.md | 3 +- 12 files changed, 406 insertions(+), 25 deletions(-) diff --git a/crates/doc/src/live/envelope.rs b/crates/doc/src/live/envelope.rs index 8f9b197048..8abe961841 100644 --- a/crates/doc/src/live/envelope.rs +++ b/crates/doc/src/live/envelope.rs @@ -78,7 +78,9 @@ pub struct EnvelopeOptions { /// Rasters: Preserve Shape Using. pub preserve_shape: PreserveShape, /// Distort Appearance: strokes and live effects are applied before the distortion, so they - /// bend with the art (off: they apply to the distorted paths). + /// bend with the art (off: they apply to the distorted paths). Type's strokes are the exception: + /// they paint along its distorted glyph outlines at their own weight either way, as `.ai` files + /// draw them (#6644). pub distort_appearance: bool, /// Distort Linear Gradients (with Distort Appearance): placed gradients bend with the art. pub distort_linear_gradients: bool, @@ -638,6 +640,7 @@ pub(super) fn expand_envelope( hooks, options, depth: 0, + type_outlines: false, }; content.iter().map(|c| map_node(c, &w)).collect() } diff --git a/crates/doc/src/live/expand.rs b/crates/doc/src/live/expand.rs index 1cc8ba0863..8675dcc011 100644 --- a/crates/doc/src/live/expand.rs +++ b/crates/doc/src/live/expand.rs @@ -21,6 +21,11 @@ pub struct Hooks<'a> { /// Distort Appearance: a path's strokes and geometry effects baked into filled art (`None` /// when it has none to bake). pub appearance: Outliner<'a>, + /// Distort Appearance for the pieces of type's glyph outlines: their geometry effects baked + /// as [`Hooks::appearance`] bakes them, their strokes left as strokes, which then paint along + /// the bent outlines at their own weight (#6644). `None` when a piece has nothing to bake, and + /// without this hook nothing in type's outlines is baked. + pub type_appearance: Outliner<'a>, /// Distort Pattern Fills: the tiles a pattern fill lays (see [`PatternTiles`]). pub pattern: Option>, /// The document whose symbols' art counts toward the instance budget of a Repeat of their @@ -61,6 +66,12 @@ pub(super) struct Warper<'a> { pub(super) options: EnvelopeOptions, /// How many hooks the art being mapped came through. pub(super) depth: u32, + /// Are groups marked as type's glyph outlines ([`crate::NodeExtras::type_outlines`]) in the art + /// being mapped type that live evaluation outlined: the type of the envelope's contents, or of + /// a live object in them, such as an envelope inside the envelope? Their strokes then paint + /// along the bent outlines at their own weight (#6644). Groups so marked in the contents as + /// they are, art an earlier Expand made of type, are plain art. + pub(super) type_outlines: bool, } impl Warper<'_> { @@ -117,6 +128,13 @@ pub(super) fn map_node(n: &Node, w: &Warper) -> Node { *live = None; } NodeKind::Layer { children, .. } | NodeKind::Group { children, .. } | NodeKind::Compound { children, .. } => { + // Type's glyph outlines: with Distort Appearance too, their strokes paint along the + // bent outlines at their own weight, as `.ai` files draw them (#6644). Their pieces are + // baked by `type_appearance`, which keeps strokes as strokes; their geometry effects, + // gradients and pattern fills follow the options as a path's do. The group's opacity + // mask, mapped above, bends as other art does. + let typed = Warper { hooks: Hooks { appearance: w.hooks.type_appearance, ..w.hooks }, ..*w }; + let w = if w.type_outlines && n.extras().type_outlines { &typed } else { w }; for c in children.iter_mut() { *c = Arc::new(map_node(c, w)); } @@ -124,14 +142,17 @@ pub(super) fn map_node(n: &Node, w: &Warper) -> Node { NodeKind::Mesh(m) => m.map(w.f), NodeKind::Blend { .. } | NodeKind::Envelope { .. } | NodeKind::Repeat(_) | NodeKind::Intertwine { .. } => { if let Some(d) = &deeper { - return map_node(&expanded_group_hooks(n, w.hooks), d); + // The type's outlines in its art are type (an envelope inside the envelope, #6644). + return map_node(&expanded_group_hooks(n, w.hooks), &Warper { type_outlines: true, ..*d }); } } NodeKind::Text(_) | NodeKind::SymbolInstance { .. } => { if let Some(d) = &deeper && let Some(o) = w.hooks.outline.and_then(|h| h(n)) { - return map_node(&carry_look(n, o), d); + // Type's outlines are type (#6644, the group arm above). + let d = Warper { type_outlines: d.type_outlines || matches!(n.kind, NodeKind::Text(_)), ..*d }; + return map_node(&carry_look(n, o), &d); } } NodeKind::Image(im) => { @@ -439,8 +460,11 @@ pub fn subtree_has_live(n: &Node) -> bool { any } -/// Largest stroke outset in a subtree (for visual bounds of envelopes). With `symbols`, the -/// outsets in the art of the symbols its instances show count too +/// Largest stroke outset in a subtree (for visual bounds of envelopes, blends and repeats, and the +/// reach of symbol art), type's character strokes included as type's own visual bounds measure them +/// ([`crate::TextObject::char_stroke_outset`]): in an envelope they paint at their own weight +/// around the bent glyphs, past its grid where the glyphs reach its edge (#6644). With +/// `symbols`, the outsets in the art of the symbols its instances show count too /// ([`crate::symbols::ArtBox::reach`]), grown by [`crate::SymbolBoxes::brush_pad`]. In boxes made /// by [`crate::SymbolBoxes::without_art_strokes`], the outsets in the art do not count, and the pad /// does. @@ -449,6 +473,9 @@ pub(crate) fn max_outset(nodes: &[Arc], symbols: Option<&crate::SymbolBoxe for n in nodes { n.walk(&mut |c| { o = o.max(c.appearance.outset()); + if let NodeKind::Text(t) = &c.kind { + o = o.max(t.char_stroke_outset()); + } if let (Some(s), NodeKind::SymbolInstance { symbol, .. }) = (symbols, &c.kind) && let Some(art) = s.art(symbol) { diff --git a/crates/effects/src/bake.rs b/crates/effects/src/bake.rs index 5d27ac60af..795fc69bdf 100644 --- a/crates/effects/src/bake.rs +++ b/crates/effects/src/bake.rs @@ -552,6 +552,21 @@ pub fn expand_art(d: &mut Document, n: &mut Node, stroke_art: StrokeArt) { /// painting their pieces name are looked up in `doc`. `None` when it has neither a stroke to /// outline nor a geometry effect, so bending first changes nothing. pub fn bake_appearance(doc: Option<&Document>, n: &Node) -> Option { + bake_appearance_as(doc, n, true) +} + +/// [`bake_appearance`] for the glyph outlines of type in an envelope with Distort Appearance: +/// geometry effects are applied as it applies them, and fills, gradients and patterns are left as +/// it leaves them, but every stroke stays a stroke on its piece instead of becoming its filled +/// outline. The envelope then bends the piece's path, and the stroke paints along the bent outline +/// at its own weight, as `.ai` files draw the strokes of type in an envelope (#6644). `None` when +/// it has no geometry effect, so bending first changes nothing. +pub fn bake_type_appearance(doc: Option<&Document>, n: &Node) -> Option { + bake_appearance_as(doc, n, false) +} + +/// [`bake_appearance`], or with `outline_strokes` false [`bake_type_appearance`]. +fn bake_appearance_as(doc: Option<&Document>, n: &Node, outline_strokes: bool) -> Option { if let Some(m) = crate::revolve_art_in(doc, n).or_else(|| crate::solid_art_in(doc, n)) { return Some(m); } @@ -564,10 +579,10 @@ pub fn bake_appearance(doc: Option<&Document>, n: &Node) -> Option { if crate::has_transform_art(n) && let Some(mut m) = reshape(doc, n, None) { - bake_appearance_pieces(doc, &mut m); + bake_appearance_pieces(doc, &mut m, outline_strokes); return Some(m); } - let outlined = |i: &AppearanceItem| paints(i) && matches!(i, AppearanceItem::Stroke(s) if s.brush.is_none()); + let outlined = |i: &AppearanceItem| outline_strokes && paints(i) && matches!(i, AppearanceItem::Stroke(s) if s.brush.is_none()); let geometric = has_geometry(&n.appearance.effects) || n.appearance.items.iter().any(|i| has_geometry(item_effects(i))); if !geometric && !n.appearance.items.iter().any(outlined) { return None; @@ -585,7 +600,7 @@ pub fn bake_appearance(doc: Option<&Document>, n: &Node) -> Option { let (ig, mut it) = apply_item(item, carried, &g, &ctx); clear_item_effects(&mut it); pieces.push(match &it { - AppearanceItem::Stroke(st) if st.brush.is_none() => { + AppearanceItem::Stroke(st) if outline_strokes && st.brush.is_none() => { let outline = crate::stroke::outline_region(&ig, rule, st); match st.path_gradient() { // A gradient along or across the stroke: its gradient meshes clipped to the outline. @@ -618,16 +633,16 @@ pub fn bake_appearance(doc: Option<&Document>, n: &Node) -> Option { Some(m) } -/// [`bake_appearance`] every path and compound path in `n` that it changes, in place. -fn bake_appearance_pieces(doc: Option<&Document>, n: &mut Node) { +/// [`bake_appearance_as`] every path and compound path in `n` that it changes, in place. +fn bake_appearance_pieces(doc: Option<&Document>, n: &mut Node, outline_strokes: bool) { if matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) { - if let Some(m) = bake_appearance(doc, n) { + if let Some(m) = bake_appearance_as(doc, n, outline_strokes) { *n = m; } return; } for c in n.children_mut().into_iter().flatten() { - bake_appearance_pieces(doc, Arc::make_mut(c)); + bake_appearance_pieces(doc, Arc::make_mut(c), outline_strokes); } } diff --git a/crates/effects/src/bake/tests.rs b/crates/effects/src/bake/tests.rs index 4751b137c9..2bcc026340 100644 --- a/crates/effects/src/bake/tests.rs +++ b/crates/effects/src/bake/tests.rs @@ -575,6 +575,27 @@ fn a_baked_stroke_with_a_gradient_along_it_becomes_meshes_clipped_to_its_outline assert_eq!(ch[1].opacity, 0.5); } +/// Distort Appearance on the pieces of type's glyph outlines (#6644): a stroke's geometry effect +/// still bakes into its piece, but the stroke stays a stroke at its own weight; a piece with no +/// geometry effect is left as it is, its stroke on it (Distort Appearance on a path outlines it). +#[test] +fn type_pieces_bake_their_geometry_effects_and_keep_their_strokes() { + let mut n = Node::path(NodeId(50), shapes::rectangle(Rect::new(0.0, 0.0, 100.0, 100.0)), Appearance::default_art()); + assert!(bake_type_appearance(None, &n).is_none(), "nothing to bake"); + assert!(bake_appearance(None, &n).is_some(), "a path's stroke is outlined"); + if let AppearanceItem::Stroke(s) = &mut n.appearance.items[1] { + s.width = 4.0; + s.effects.push(fx("path.offsetPath", json!({"offset": 5.0}))); + } + let m = bake_type_appearance(None, &n).unwrap(); + let ch = m.children().unwrap(); + assert_eq!(ch.len(), 2); + let Some(AppearanceItem::Stroke(st)) = ch[1].appearance.items.first() else { panic!("still a stroke: {:?}", ch[1].appearance) }; + assert!(st.width == 4.0 && st.effects.is_empty(), "{st:?}"); + assert!((ch[1].geometric_bounds().unwrap().width() - 110.0).abs() < 0.5, "the stroke's offset is baked into its path"); + assert!((ch[0].geometric_bounds().unwrap().width() - 100.0).abs() < 1e-6, "the fill keeps the square"); +} + /// A 100 pt square at the origin painted by `fill` and `stroke` (`width` pt), with the Transform /// effect `params`. fn transformed(fill: Paint, stroke: Paint, width: f64, params: serde_json::Value) -> Node { diff --git a/crates/effects/src/lib.rs b/crates/effects/src/lib.rs index ae8b7d9e90..67b4b464fd 100644 --- a/crates/effects/src/lib.rs +++ b/crates/effects/src/lib.rs @@ -68,7 +68,7 @@ pub use adjust::{ ADJUSTMENTS, CHANNELS, ColorMap, ImageHook, adjust, adjust_in_document, color_map, curve_at, curve_points, has_adjustment, is_adjustment, is_channel, }; -pub use bake::{StrokeArt, bake_appearance, bake_document, expand_art, expand_leaf, fresh_ids, needs_bake}; +pub use bake::{StrokeArt, bake_appearance, bake_document, bake_type_appearance, expand_art, expand_leaf, fresh_ids, needs_bake}; pub use clip::clip_outline; pub use group::{ OutlineHook, PATHFINDER_EFFECTS, compound_shape_area, compound_shape_art, evaluate_container, has_container_appearance, has_pathfinder, diff --git a/crates/effects/src/live.rs b/crates/effects/src/live.rs index 03b335f010..2c02f886c0 100644 --- a/crates/effects/src/live.rs +++ b/crates/effects/src/live.rs @@ -2,8 +2,9 @@ //! every exporter, with what the pure evaluation in [`vectorcraft_doc::live`] can't do itself //! ([`Hooks`]): type inside an envelope distorts as its glyph outlines, run by run //! ([`outline_text`]); symbol instances as their symbol's art; with Distort Appearance strokes and -//! geometry effects bend with the art ([`bake_appearance`]); with Distort Pattern Fills the pattern -//! tiles do. +//! geometry effects bend with the art ([`bake_appearance`]), except type's strokes, which paint +//! along its bent outlines at their own weight ([`bake_type_appearance`], #6644); with Distort +//! Pattern Fills the pattern tiles do. use std::sync::Arc; @@ -11,7 +12,7 @@ use vectorcraft_doc::live::{self, Hooks, Outliner}; use vectorcraft_doc::{Document, Node, NodeKind}; use vectorcraft_geom::{Affine, Rect}; -use crate::{bake_appearance, outline_text}; +use crate::{bake_appearance, bake_type_appearance, outline_text}; /// The text outliner live evaluation uses: type as its glyph outlines, one path per run in the /// run's paint ([`outline_text`]). @@ -44,7 +45,8 @@ fn with_hooks(doc: Option<&Document>, f: impl FnOnce(Hooks) -> R) -> R { let outline = |n: &Node| outline_object(doc, n); let tiles = |name: &str, xf: Affine, region: Rect| Some(doc?.pattern(name)?.instances_in(xf, region)); let appearance = |n: &Node| bake_appearance(doc, n); - f(Hooks { outline: Some(&outline), appearance: Some(&appearance), pattern: Some(&tiles), symbols: doc }) + let type_appearance = |n: &Node| bake_type_appearance(doc, n); + f(Hooks { outline: Some(&outline), appearance: Some(&appearance), type_appearance: Some(&type_appearance), pattern: Some(&tiles), symbols: doc }) } /// One level of evaluation of live object `n` ([`live::expand_live_hooks`]). diff --git a/crates/engine/src/tests/envelope_distort.rs b/crates/engine/src/tests/envelope_distort.rs index b42b1da027..8a1e46c68a 100644 --- a/crates/engine/src/tests/envelope_distort.rs +++ b/crates/engine/src/tests/envelope_distort.rs @@ -405,3 +405,210 @@ fn new_envelopes_distort_appearance_and_old_ones_keep_their_look() { let e = arch(&mut s, 50.0, json!({})); assert!(matches!(node(&s, e).kind, NodeKind::Envelope { options, .. } if options == EnvelopeOptions::NEW)); } + +/// What strokes the object in [`squeezed`]. +#[derive(Clone, Copy)] +enum Stroked { + /// Nothing. + No, + /// The characters of type, or a path's own stroke. + Own, + /// A stroke on type's own appearance (Appearance panel), the characters unstroked. + Appearance, +} + +/// The weight of the strokes in [`squeezed`]. +const SQUEEZED_WEIGHT: f64 = 8.0; + +/// `make`'s object, stroked by `stroked` with a red stroke [`SQUEEZED_WEIGHT`] wide, in a one-patch +/// mesh envelope with Distort Appearance on whose right column is moved in to squeeze the object to +/// half its width (a horizontal squeeze, the same everywhere): the session, the envelope and the +/// height of the envelope's middle. +fn squeezed(make: fn(&mut Session) -> NodeId, stroked: Stroked) -> (Session, NodeId, f64) { + use vectorcraft_doc::live::EnvelopeKind; + let mut s = session(); + let a = make(&mut s); + sel(&mut s, &[a]); + match stroked { + Stroked::No => {} + Stroked::Own => { + s.execute("paint.setStroke", &json!({"ids": [a.0], "color": "#ff0000"})).unwrap(); + s.execute("stroke.set", &json!({"ids": [a.0], "weight": SQUEEZED_WEIGHT})).unwrap(); + } + Stroked::Appearance => { + s.edit("appearance stroke", |d, _| { + let n = d.node_mut(a).unwrap(); + let mut appearance = (*n.appearance).clone(); + appearance + .items + .push(AppearanceItem::Stroke(vectorcraft_doc::StrokeLayer::new(Paint::solid(Color::rgb(1.0, 0.0, 0.0)), SQUEEZED_WEIGHT))); + n.appearance = appearance.into(); + Ok(()) + }) + .unwrap(); + } + } + let e = id_of(&s.execute("object.envelope.makeWithMesh", &json!({"rows": 1, "cols": 1})).unwrap()); + let NodeKind::Envelope { options, .. } = &node(&s, e).kind else { panic!("an envelope") }; + assert!(options.distort_appearance, "new envelopes distort appearance"); + let mut middle = 0.0; + s.edit("squeeze", |d, _| { + let NodeKind::Envelope { kind, .. } = &mut d.node_mut(e).unwrap().kind else { panic!("an envelope") }; + let EnvelopeKind::Mesh { points, handles, .. } = &mut **kind else { panic!("a mesh") }; + let (left, right) = (points[0].x, points[1].x); + points[1].x = left + (right - left) / 2.0; + points[3].x = points[1].x; + handles.clear(); + middle = (points[0].y + points[2].y) / 2.0; + Ok(()) + }) + .unwrap(); + (s, e, middle) +} + +/// Where the ink of the page of `s` starts and ends across height `y`, as the canvas draws it. +fn ink_across(s: &Session, y: f64) -> (f64, f64) { + let scale = 8.0; + let region = Rect::new(0.0, y - 0.5, 800.0, y + 0.5); + let r = vectorcraft_render::Renderer::new().render_region(&s.doc().unwrap().doc, region, scale, true); + let row = (r.height / 2) as usize; + let inked: Vec = (0..r.width as usize).filter(|i| r.pixels[(row * r.width as usize + i) * 4..][..3].iter().any(|c| *c < 128)).collect(); + let (first, last) = (inked.first().unwrap(), inked.last().unwrap()); + (*first as f64 / scale, (last + 1) as f64 / scale) +} + +/// How wide the ink is across the middle of `make`'s object in [`squeezed`]. +fn squeezed_ink(make: fn(&mut Session) -> NodeId, stroked: Stroked) -> f64 { + let (s, _, middle) = squeezed(make, stroked); + let (first, last) = ink_across(&s, middle); + last - first +} + +/// A capital I set 300 points tall at (100, 400), filled black. +fn tall_i(s: &mut Session) -> NodeId { + id_of(&s.execute("text.create", &json!({"x": 100, "y": 400, "text": "I", "size": 300})).unwrap()) +} + +/// With Distort Appearance on, the characters' stroke of type in an envelope paints along the bent +/// glyph outlines at its own weight, as `.ai` files draw it (#6644): squeezed to half its width, the +/// stem of an I still has half the weight of stroke on each side, not a quarter. +#[test] +fn type_strokes_paint_at_their_own_weight_in_a_squeezed_envelope() { + let (plain, stroked) = (squeezed_ink(tall_i, Stroked::No), squeezed_ink(tall_i, Stroked::Own)); + let past = stroked - plain; + assert!((past - SQUEEZED_WEIGHT).abs() < 0.5, "the stroke reaches {past} pt past the squeezed stem, both sides together ({plain} → {stroked})"); +} + +/// A stroke on type's own appearance paints at its own weight too (#6644). +#[test] +fn a_stroke_on_types_appearance_paints_at_its_own_weight_in_a_squeezed_envelope() { + let (plain, stroked) = (squeezed_ink(tall_i, Stroked::No), squeezed_ink(tall_i, Stroked::Appearance)); + let past = stroked - plain; + assert!((past - SQUEEZED_WEIGHT).abs() < 0.5, "the stroke reaches {past} pt past the squeezed stem, both sides together ({plain} → {stroked})"); +} + +/// A path's stroke still bends with the art: squeezed to half its width, it reaches half as far past +/// the path's left and right sides. +#[test] +fn a_paths_stroke_still_bends_in_a_squeezed_envelope() { + let (plain, stroked) = (squeezed_ink(rect, Stroked::No), squeezed_ink(rect, Stroked::Own)); + let past = stroked - plain; + assert!( + (past - SQUEEZED_WEIGHT / 2.0).abs() < 0.5, + "the stroke reaches {past} pt past the squeezed rectangle, both sides together ({plain} → {stroked})" + ); +} + +/// The type's stroke paints past the envelope's grid, where the glyphs reach its edge: the +/// envelope's visual bounds hold it (#6644). +#[test] +fn the_visual_bounds_of_an_envelope_hold_its_types_strokes() { + let (s, e, middle) = squeezed(tall_i, Stroked::Own); + let n = node(&s, e); + let (visual, grid) = (n.visual_bounds().unwrap(), n.geometric_bounds().unwrap()); + let (first, last) = ink_across(&s, middle); + assert!(first < grid.x0 - 1.0, "the stroke paints past the grid: {first} vs {grid:?}"); + // The ink is measured to whole pixels (an eighth of a point); miter spikes don't count, as in + // type's own visual bounds. + let pixel = 0.125; + assert!(visual.x0 <= first + pixel && visual.x1 >= last - pixel, "{visual:?} holds the ink from {first} to {last}"); + assert!(first - visual.x0 < 1.0 && visual.x1 - last < 1.0, "{visual:?} reaches no further than the ink from {first} to {last}"); +} + +/// A repeat of stroked type reaches past its copies by as far as the characters' strokes paint +/// past their glyphs: half the weight of a centred stroke, as type's own visual bounds (#6644). +#[test] +fn the_visual_bounds_of_a_repeat_of_stroked_type_grow_by_half_the_stroke() { + let mut s = session(); + let t = id_of(&s.execute("text.create", &json!({"x": 100, "y": 200, "text": "I", "size": 100})).unwrap()); + s.execute("paint.setStroke", &json!({"ids": [t.0], "color": "#ff0000"})).unwrap(); + s.execute("stroke.set", &json!({"ids": [t.0], "weight": SQUEEZED_WEIGHT})).unwrap(); + let r = id_of(&s.execute("object.repeat.grid", &json!({"ids": [t.0], "rows": 2, "cols": 2})).unwrap()); + let n = node(&s, r); + let (visual, geometric) = (n.visual_bounds().unwrap(), n.geometric_bounds().unwrap()); + let grown = [geometric.x0 - visual.x0, geometric.y0 - visual.y0, visual.x1 - geometric.x1, visual.y1 - geometric.y1]; + assert!(grown.iter().all(|g| (g - SQUEEZED_WEIGHT / 2.0).abs() < 1e-6), "{grown:?}"); +} + +/// An I stroked by `stroked` in a one-patch mesh envelope that leaves it as it is: the envelope. +fn enveloped_i(s: &mut Session, stroked: bool) -> NodeId { + let t = tall_i(s); + if stroked { + s.execute("paint.setStroke", &json!({"ids": [t.0], "color": "#ff0000"})).unwrap(); + s.execute("stroke.set", &json!({"ids": [t.0], "weight": SQUEEZED_WEIGHT})).unwrap(); + } + sel(s, &[t]); + id_of(&s.execute("object.envelope.makeWithMesh", &json!({"rows": 1, "cols": 1})).unwrap()) +} + +/// Type's stroke in an envelope inside an envelope also paints at its own weight: the outer +/// envelope squeezes the inner one's type to half its width, and the stem still has half the weight +/// of stroke on each side (#6644). +#[test] +fn type_strokes_paint_at_their_own_weight_in_an_envelope_inside_an_envelope() { + let (plain, stroked) = (squeezed_ink(|s| enveloped_i(s, false), Stroked::No), squeezed_ink(|s| enveloped_i(s, true), Stroked::No)); + let past = stroked - plain; + assert!((past - SQUEEZED_WEIGHT).abs() < 0.5, "the stroke reaches {past} pt past the squeezed stem, both sides together ({plain} → {stroked})"); +} + +/// An opacity mask on type bends as other art does (#6644): with Distort Appearance its stroke +/// becomes its bent outline, as on a path, while the type's own stroke stays a stroke. +#[test] +fn an_opacity_mask_on_type_bends_as_other_art() { + let mut s = session(); + let t = tall_i(&mut s); + s.execute("paint.setStroke", &json!({"ids": [t.0], "color": "#ff0000"})).unwrap(); + s.execute("stroke.set", &json!({"ids": [t.0], "weight": SQUEEZED_WEIGHT})).unwrap(); + let m = id_of(&s.execute("shape.rectangle", &json!({"x": 90, "y": 150, "width": 120, "height": 300})).unwrap()); + s.execute("paint.setStroke", &json!({"ids": [m.0], "color": "#ffffff"})).unwrap(); + s.execute("stroke.set", &json!({"ids": [m.0], "weight": SQUEEZED_WEIGHT})).unwrap(); + sel(&mut s, &[t, m]); + s.execute("transparency.makeOpacityMask", &json!({})).unwrap(); + assert!(node(&s, t).extras().mask.is_some(), "the type has the mask"); + sel(&mut s, &[t]); + let e = arch(&mut s, 60.0, json!({"distortAppearance": true})); + let (mut masks, mut kept) = (vec![], 0); + for n in &evaluated(&s, e) { + n.walk(&mut |c| { + kept += c.appearance.painted_strokes().count(); + masks.extend(c.extras().mask.as_ref().map(|m| m.art.clone())); + }); + } + assert_eq!(masks.len(), 1, "the mask goes with the type"); + let mut in_mask = 0; + masks[0].walk(&mut |c| in_mask += c.appearance.painted_strokes().count()); + assert_eq!(in_mask, 0, "the mask's stroke became its bent outline"); + assert_eq!(kept, 1, "the type's stroke stays a stroke"); +} + +/// Expand turns an envelope of stroked type into its bent glyph outlines with the stroke on them, +/// at its own weight, as it draws (#6644). +#[test] +fn expanding_an_envelope_of_stroked_type_keeps_the_stroke_at_its_weight() { + let (mut s, e, _) = squeezed(tall_i, Stroked::Own); + sel(&mut s, &[e]); + s.execute("object.envelope.expand", &json!({})).unwrap(); + let mut weights = vec![]; + node(&s, e).walk(&mut |c| weights.extend(c.appearance.painted_strokes().map(|st| st.width))); + assert_eq!(weights, [SQUEEZED_WEIGHT]); +} diff --git a/crates/eps/src/import/tests_native.rs b/crates/eps/src/import/tests_native.rs index 45a7a92c8c..8f64280367 100644 --- a/crates/eps/src/import/tests_native.rs +++ b/crates/eps/src/import/tests_native.rs @@ -5796,7 +5796,8 @@ fn a_warp_of_type_opens_as_a_mesh_on_its_saved_grid_and_keeps_its_shape_when_its /// A warp of stroked type with Distort Appearance whose drawn art maps the type's bounds with its /// strokes onto the grid the file saves (not its glyphs' bounds alone) opens live as a mesh envelope -/// mapping from that box (#3179). +/// mapping from that box (#3179). The drawn art strokes the bent outlines at the stroke's own weight, +/// as files draw it (#6644). #[test] fn a_warp_of_stroked_type_maps_from_its_bounds_with_strokes_where_its_drawn_art_does() { use vectorcraft_doc::live::{envelope_content_boxes, envelope_stroke_margin}; @@ -5816,7 +5817,7 @@ fn a_warp_of_stroked_type_maps_from_its_bounds_with_strokes_where_its_drawn_art_ vectorcraft_doc::NodeId(1_000_000), NodeKind::Envelope { content, kind: Box::new(rising_kind()), fidelity: 50.0, editing: false, options, frame: Box::default() }, ); - let (drawn, page) = drawn_envelope(&shaped); + let (drawn, page) = drawn_stroked_envelope(&shaped); let art = native_with_text(&layer("Art", true, &format!("{}\n{}", square(10, 10), type_envelope_on(&arc_keys(0.3), &rising_grid(), &drawn, ""))), &doc); let r = import(&eps(&format!("{}\n{page}", page_square(10, 10)), &art)).unwrap(); @@ -5833,6 +5834,101 @@ fn a_warp_of_stroked_type_maps_from_its_bounds_with_strokes_where_its_drawn_art_ assert_eq!(margin, Some(options.bounds_margin)); } +/// The drawn art of `envelope` (on the page axes), an envelope of type stroked by its characters, +/// as the drawn art of `.ai` files strokes type in an envelope: the bent glyph outlines the envelope +/// draws of its type unstroked, each filled in its type's color, then each stroked with the type's +/// stroke (its weight, color, join and miter limit) whatever the grid does to it, and the page's +/// PostScript for them (#6644). +fn drawn_stroked_envelope(envelope: &Node) -> (String, String) { + let NodeKind::Envelope { content, .. } = &envelope.kind else { panic!("an envelope") }; + let Some(NodeKind::Text(t)) = content.first().map(|c| &c.kind) else { panic!("type") }; + let stroke = t.runs[0].style.stroke_layer(); + let mut unstroked = envelope.clone(); + if let NodeKind::Envelope { content, .. } = &mut unstroked.kind { + for c in content.iter_mut() { + if let NodeKind::Text(t) = &mut std::sync::Arc::make_mut(c).kind { + t.runs.iter_mut().for_each(|r| r.style.stroke = vectorcraft_color::Paint::None); + } + } + } + let (fills, fill_page) = drawn_envelope(&unstroked); + let [r, g, b] = stroke.paint.color().map_or([0.0; 3], |c| c.to_rgb()); + let join = match stroke.join { + vectorcraft_doc::LineJoin::Miter => 0, + vectorcraft_doc::LineJoin::Round => 1, + vectorcraft_doc::LineJoin::Bevel => 2, + }; + let (w, limit) = (stroke.width, stroke.miter_limit); + let mut art = format!("{fills}0 0 0 0 {r} {g} {b} XA\n{w} w\n{join} j\n{limit} M\n"); + let mut page = format!("{fill_page}{r} {g} {b} setrgbcolor {w} setlinewidth {join} setlinejoin {limit} setmiterlimit\n"); + let pt = |p: kurbo::Point| { + let (x, y) = to_art(p); + format!("{x} {y}") + }; + vectorcraft_effects::expand_live_deep(None, &unstroked).walk(&mut |n| { + let NodeKind::Path { path, .. } = &n.kind else { return }; + for el in path.to_bezpath().elements() { + match *el { + kurbo::PathEl::MoveTo(p) => { + art += &format!("{} m\n", pt(p)); + page += &format!("newpath {} moveto ", pt(p)); + } + kurbo::PathEl::LineTo(p) => { + art += &format!("{} L\n", pt(p)); + page += &format!("{} lineto ", pt(p)); + } + kurbo::PathEl::CurveTo(a, c, p) => { + art += &format!("{} {} {} C\n", pt(a), pt(c), pt(p)); + page += &format!("{} {} {} curveto ", pt(a), pt(c), pt(p)); + } + kurbo::PathEl::QuadTo(..) => {} + kurbo::PathEl::ClosePath => { + art += "s\n"; + page += "closepath stroke\n"; + } + } + } + }); + (art, page) +} + +/// An envelope of type with a character stroke, Distort Appearance on, whose drawn art strokes the +/// bent glyph outlines at the stroke's own weight (as `.ai` files draw the strokes of type in an +/// envelope, however much the grid squeezes or stretches it) opens live: VectorCraft draws the +/// stroke that way too (#6644). +#[test] +fn an_envelope_of_stroked_type_whose_drawn_art_strokes_the_bent_outlines_at_the_weight_opens_live() { + let Some(family) = installed_family() else { return }; + // "FLUX" stroked 1.5 points wide in black with round joins. + let stroked = "/53 << /99 /CAITextPaint /0 << /0 2 /1 [ 1.0 0.0 1.0 0.0 0.0 ] >> >> /54 << /99 /CAITextPaint /0 << /0 2 /1 [ 1.0 0.0 0.0 0.0 1.0 ] >> >> /57 true /62 1 /63 1.5"; + let doc = type_envelope_text(&family, None).replace("/53 << /99 /CAITextPaint /0 << /0 2 /1 [ 1.0 0.0 1.0 0.0 0.0 ] >> >>", stroked); + let mut text = made_envelope_type(&doc); + text.visible = true; + assert!( + matches!(&text.kind, NodeKind::Text(t) if t.runs[0].style.stroke_width == 1.5 && t.runs[0].style.stroke_join == vectorcraft_doc::LineJoin::Round), + "{text:?}" + ); + let shaped = Node::new( + vectorcraft_doc::NodeId(1_000_000), + NodeKind::Envelope { + content: vec![std::sync::Arc::new(text)], + kind: Box::new(rising_kind()), + fidelity: 50.0, + editing: false, + options: vectorcraft_doc::live::EnvelopeOptions::NEW, + frame: Box::default(), + }, + ); + let (drawn, page) = drawn_stroked_envelope(&shaped); + let art = + native_with_text(&layer("Art", true, &format!("{}\n{}", square(10, 10), type_envelope_on(&arc_keys(0.3), &rising_grid(), &drawn, ""))), &doc); + let r = import(&eps(&format!("{}\n{page}", page_square(10, 10)), &art)).unwrap(); + assert_eq!(names(&r.document), ["Art"], "{:?}", r.warnings); + let (envelopes, loose) = envelopes_and_type(&r.document); + assert_eq!(envelopes, [vec!["FLUX".to_string()]], "{:?}", r.warnings); + assert!(loose.is_empty(), "{loose:?}"); +} + /// A warp of type whose editing data saves no grid it can be shaped by keeps its drawn art and its /// type, hidden, with the note, when its own warp draws apart from that art (#3179). #[test] diff --git a/docs/file-format-parity.md b/docs/file-format-parity.md index d42e770df0..79785b2b00 100644 --- a/docs/file-format-parity.md +++ b/docs/file-format-parity.md @@ -1,6 +1,6 @@ # File format parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-11 · **Change:** minor (`.ai` and EPS import: centred and right-aligned lines of tracked type are aligned without the tracking after their last character, as the file's page aligns them, #6610; `.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; `.ai` save and open: layer colour presets Yellow, Magenta and Cyan keep their colour, as the `Lb` colour index now follows the file's numbering, #6502; `.ai` save: stroked type keeps its stroke's cap, join and miter limit in the text document, #6472; `.ai` and EPS import, PDF import: tracking and manual kerning in horizontally scaled type take the Horizontal Scale, as the file's page spaces such type; `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke, #3179; `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid, #3179; `.ai` and EPS import: stroked type keeps its stroke's cap, join and miter limit from the text document, #6472; `.ai` save: type in a variable font's named instance names its design-space setting, #6388; `.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; `.ai` and EPS import: a note for type in an envelope, #3179; `.ai` and EPS import: the live envelope and warped type check sees white art; PDF import: DeviceN images of one ink or of process plates keep their inks, #6348; `.ai` import: images in a spot ink's Separation space keep their ink, #6350; PDF import: Separation images keep their ink, #6314; PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; PDF import: image masks open colorized by the color they are painted in, #6313; EPS and `.ai` editing data: a ligature the page names by a private-use glyph matches its text object; EPS import: CIDFonts only named, over a Unicode CMap, set as live type; EPS import: CMap mappings to base-font codes and glyph names; EPS import: CID-keyed fonts in FontSets (CFF) draw their glyphs; EPS import: `kshow` procedures kern live type; EPS import: embedded Type 1 fonts' glyphs and widths; EPS import: CID-keyed fonts draw their glyphs; EPS import: Type 42 fonts' characters and widths from the font they carry, show operators' spacing kept as tracking; EPS import: an image decoder's own buffers stop counting against the memory budget once it is decoded; EPS import: sampled functions interpolate between their samples; `.ai` and EPS type from the text document keeps its tab stops; it keeps auto leading and hyphenation options, and may show more of the file's last lines in an area frame; `.ai` and EPS import: Art brushes in the older form of their objects come into the Brushes panel; EPS import: gradients drawn as abutting strips come in as one gradient, without seams; EPS import: composite fonts draw their Type 42 glyphs; SVG import: filter and mask regions clip, #5876, #5875; SVG import: Gaussian blurs keep `color-interpolation-filters`, #5877; PDF and `.ai` export: objects' URLs as links, #5785; SVG import: `color-interpolation="linearRGB"` gradients, #5878; `.ai` import: paths with a Calligraphic brush open brushed, #372) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-11 · **Change:** minor (`.ai` and EPS import, and what every export and `.ai` save draw: type's strokes in an envelope paint at their own weight along its bent outlines, Distort Appearance on or off, #6644; `.ai` and EPS import: centred and right-aligned lines of tracked type are aligned without the tracking after their last character, as the file's page aligns them, #6610; `.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; `.ai` save and open: layer colour presets Yellow, Magenta and Cyan keep their colour, as the `Lb` colour index now follows the file's numbering, #6502; `.ai` save: stroked type keeps its stroke's cap, join and miter limit in the text document, #6472; `.ai` and EPS import, PDF import: tracking and manual kerning in horizontally scaled type take the Horizontal Scale, as the file's page spaces such type; `.ai` and EPS import: stroked type in an envelope maps from its glyphs grown by half its stroke, #3179; `.ai` and EPS import: warps of type open as mesh envelopes on their saved grid, #3179; `.ai` and EPS import: stroked type keeps its stroke's cap, join and miter limit from the text document, #6472; `.ai` save: type in a variable font's named instance names its design-space setting, #6388; `.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; `.ai` and EPS import: a note for type in an envelope, #3179; `.ai` and EPS import: the live envelope and warped type check sees white art; PDF import: DeviceN images of one ink or of process plates keep their inks, #6348; `.ai` import: images in a spot ink's Separation space keep their ink, #6350; PDF import: Separation images keep their ink, #6314; PDF editable import preserves authored ActualText once, including empty/nested spans and authored ordering (#6165); cross-line/style layout remains approximate; scores and estimates unchanged; PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; PDF import: image masks open colorized by the color they are painted in, #6313; EPS and `.ai` editing data: a ligature the page names by a private-use glyph matches its text object; EPS import: CIDFonts only named, over a Unicode CMap, set as live type; EPS import: CMap mappings to base-font codes and glyph names; EPS import: CID-keyed fonts in FontSets (CFF) draw their glyphs; EPS import: `kshow` procedures kern live type; EPS import: embedded Type 1 fonts' glyphs and widths; EPS import: CID-keyed fonts draw their glyphs; EPS import: Type 42 fonts' characters and widths from the font they carry, show operators' spacing kept as tracking; EPS import: an image decoder's own buffers stop counting against the memory budget once it is decoded; EPS import: sampled functions interpolate between their samples; `.ai` and EPS type from the text document keeps its tab stops; it keeps auto leading and hyphenation options, and may show more of the file's last lines in an area frame; `.ai` and EPS import: Art brushes in the older form of their objects come into the Brushes panel; EPS import: gradients drawn as abutting strips come in as one gradient, without seams; EPS import: composite fonts draw their Type 42 glyphs; SVG import: filter and mask regions clip, #5876, #5875; SVG import: Gaussian blurs keep `color-interpolation-filters`, #5877; PDF and `.ai` export: objects' URLs as links, #5785; SVG import: `color-interpolation="linearRGB"` gradients, #5878; `.ai` import: paths with a Calligraphic brush open brushed, #372) · **Target:** Adobe Illustrator 2026 (30.x) Every format Illustrator opens, places, saves or exports, against VectorCraft's format table (`FORMATS`, `OPEN_EXTS`, `PLACE_EXTS` in `crates/engine/src/cmd/fileio/formats.rs`). Illustrator's list comes from its public @@ -339,6 +339,7 @@ Stop opacity on translated artboards remains outside this regression coverage. | Date | Change | Summary | |---|---|---| +| 2026-11-11 | minor | `.ai` and EPS import, and what the canvas, every export and `.ai` save draw: type's strokes in an envelope (its characters' and those on its own appearance) paint along the bent glyph outlines at their own weight, Distort Appearance on or off, as the drawn art of users' `.ai` files strokes them (used locally, never committed: there the drawn art keeps those strokes as stroked paths at the type's own weights, and its ring is as wide wherever the grid squeezes or stretches the type). With Distort Appearance, VectorCraft bent them with the art, as their filled outlines, so an envelope of stroked type in a squeezed or stretched grid didn't draw as its drawn art and kept it. The same holds in an envelope inside an envelope. Paths' strokes, geometry effects, opacity masks, linear gradients and pattern fills bend as before. On 224 of our own files: envelopes of type that open live go from 135 in 37 files to 154 in 45, and no file loses one; no file changes whether it opens from its layers or its PDF part; renders at 40 ppi change in 31 files, by at most 2.3% of their pixels, 19 closer to the file's own page and 12 further, 11 of those where an envelope of type now opens live in place of its drawn art (the page's own art) and one by 4 pixels. Tests `envelope_distort::type_strokes_paint_at_their_own_weight_in_a_squeezed_envelope`, `a_stroke_on_types_appearance_paints_at_its_own_weight_in_a_squeezed_envelope`, `a_paths_stroke_still_bends_in_a_squeezed_envelope`, `tests_native::an_envelope_of_stroked_type_whose_drawn_art_strokes_the_bent_outlines_at_the_weight_opens_live` (#6644) | | 2026-11-11 | minor | `.ai` and EPS import, and what SVG export, PDF export and `.ai` save draw: centred and right-aligned lines of tracked type are aligned without the tracking after their last character, as a `.ai`'s own page aligns them (see type-parity.md, same date). In 224 users' files (used locally, never committed), 63 render differently: 54 closer to the page, 7 further, 1 alike and 1 that couldn't be compared; among them the median share of pixels that differ from the page went from 4.4% to 1.0%. Of the 7: one now opens from its layers instead of its PDF part (they differ from the page by less than the import's 5% limit now; type note 3.8%); one has a centred line whose spacing inside it differs from the page's, which now centres on the page's line while half of it no longer lies on the page's glyphs (type note 1.4% to 2.4%); five moved by less than 0.05 of a percentage point, in type the page draws in other glyphs. The type note shows a smaller share in 6 files; 2 more envelopes of type open live (129 to 131, none fewer in any file). SVG import: `text-anchor` aligns a line's advance, which ends after its last character's letter spacing, so a centred or right-aligned letter-spaced line moves back by half or all of it and stays where a reader draws it; SVG export, which anchors lines so, reads back unchanged (test `import_text::anchored_letter_spaced_lines_stay_where_a_reader_draws_them`). Affinity import: centred or right-aligned tracked artistic text moves by half or all of its last character's tracking, as layout now aligns it (unverified against Affinity, whose files we don't have), and differently aligned paragraphs line up by the widths layout aligns them by (`affinity_features::artistic_text_aligns_its_lines_within_the_longest`). Scores and estimates unchanged. (#6610) | | 2026-11-11 | minor | `.ai` and EPS import: while an envelope's contents are edited, the editing data keeps its mesh (a mesh's, a top object's or a warp's grid) in its dictionary, and in some files that mesh lies away from the drawn art by a move, the contents with the drawn art, as if the mesh hadn't followed the envelope when it moved: the envelope drew its contents elsewhere and kept its drawn art. A mesh or top object saved in Edit Contents (or a warp of type tried on its saved grid) whose mesh draws the contents as large as the drawn art, within half a point over width and height together, but further from it than that, is now tried again, after every other way and with one more of the import's checks, with its mesh moved by as far as the drawn art's box lies from the box of what it draws; it opens live there where it then draws as the drawn art. In users' files, used locally and never committed, only envelopes saved in Edit Contents draw elsewhere than their drawn art, and nothing in their dictionaries says by how much they moved. Tests `ai::tests::an_envelope_in_edit_contents_whose_mesh_stayed_behind_opens_live_on_its_drawn_art`, `tests_native::a_warp_of_type_in_edit_contents_whose_grid_stayed_behind_opens_on_its_drawn_art` (#6570) | | 2026-11-11 | minor | `.ai` save (PDF-compatible editing copy and legacy) and `.ai`/EPS open: a layer's `Lb` colour index follows the file's numbering, where Magenta, Cyan and Yellow are 4, 5 and 6 and `LAYER_COLORS` has Yellow, Magenta and Cyan; Yellow, Magenta and Cyan layers no longer come out as Magenta, Cyan and Yellow, and the other 24 presets are unchanged (#6502, from the index and RGB pairs in users' files). `LAYER_COLORS` keeps its order, so `.vectorcraft` files and the Layers panel don't change. Scores and estimates unchanged. | diff --git a/docs/mcp.md b/docs/mcp.md index 5826c5c8c4..75f5dfe80c 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -7922,8 +7922,14 @@ laid-out box, and so does type inside any other object, such as a blend, a repea VectorCraft's own rule, and envelopes of type in saved files redraw by it. Everything inside bends with the envelope: images as a raster mesh warp (cut into pieces by Fidelity, each a clipped image under its own affine map; SVG shares the pixels between the pieces), symbol instances as their symbol's art, -and with Distort Appearance strokes (as their filled outlines) and geometry effects; with it, Distort Linear Gradients -bends linear gradients and Distort Pattern Fills the pattern tiles. A transformed envelope keeps its warp in its own +and with Distort Appearance the strokes of paths (as their filled outlines) and geometry effects; with it, Distort +Linear Gradients bends linear gradients and Distort Pattern Fills the pattern tiles. Type's strokes (its characters' +and those on its own appearance) don't bend, with Distort Appearance or without: they paint along the bent glyph +outlines at their own weight, as `.ai` files draw type in an envelope, so a squeezed or stretched envelope keeps them +as wide as they are, also in an envelope inside an envelope (#6644). Their geometry effects and an opacity mask on +the type still bend, and Expand gives the bent outlines with the strokes on them, which Object › Expand or Outline +Stroke outlines later. Before #6644, VectorCraft bent type's strokes too, so envelopes of stroked type made earlier +now draw their strokes at their own weight. A transformed envelope keeps its warp in its own frame (`kind.frame` in `document.inspect`; rotating a warp envelope turns the warp with it), and move and scale keep it square to the page. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index b4c949f742..a5d874c65e 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-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) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-11 · **Change:** minor (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) > > Vector Halftone preview update (2026-11-10): temporary dot selection marks are hidden, and the bounding box stays available (#6369). > @@ -1233,6 +1233,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Window › Blend exposes easing Type, Ramp and independent color Shift through `object.blend.options`. Smooth Color counts the steps of each pair of keys from their color change, or from the distance between their visible bounding-box edges when their colors match or they hold gradients or patterns ([Blend Options](https://web.archive.org/web/20241217212108/https://helpx.adobe.com/illustrator/using/blending-objects.html)); the step counts, their caps and the colors compared are VectorCraft's own. Envelope Options › Anti-Alias off draws an envelope's distorted images without smoothing, and Preserve Shape Using › Transparency gives each piece of a distorted image an opacity mask in its shape instead of a clipping mask ([Envelope panel options](http://web.archive.org/web/20260513013456/https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/envelope-panel-options.html)). + With Envelope Options › Distort Appearance on, type's strokes (its characters' and those on its own appearance) paint along the bent glyph outlines at their own weight instead of bending with the art, as the drawn art of users' `.ai` files strokes type in an envelope. This is VectorCraft's own rule from those files: the public page names applied effects and graphic styles, not strokes. This holds in an envelope inside an envelope too. Paths' strokes, geometry effects (type's included), opacity masks (on type too), linear gradients and pattern fills bend as before; Expand gives type's bent outlines with their strokes on them. The visual bounds of envelopes, blends and repeats, and the reach of symbol art, count type's character strokes as type's own visual bounds do (half the weight of a centred stroke); they left them out, though those strokes already painted past an envelope's grid. Envelopes of stroked type made in VectorCraft before this draw their strokes at their own weight now (#6644; `crates/engine/src/tests/envelope_distort.rs`, `crates/effects/src/bake/tests.rs`). The four polynomial distributions are original approximations of the public description, not measured numeric parity. See [Blend panel overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/apply-transparency-and-blending/blend-panel-overview.html). A blend in a `.ai` or EPS opened from its editing data keeps a Specified Distance spacing with its distance ([Blend Options](https://helpx.adobe.com/illustrator/desktop/manage-colors/apply-transparency-and-blending/blend-options-overview.html)) where VectorCraft lays out as many steps between each pair of keys as the file draws, in the same places and colors. A Smooth Color blend opens live only where VectorCraft's own Smooth Color step count equals the drawn steps, and VectorCraft often counts a different number. A blend that VectorCraft doesn't lay out as drawn keeps its drawn steps with a note (`import::ai::tests::a_blend_keeps_its_spacing`, `a_blend_of_three_keys_keeps_its_distance_between_each_pair`, `a_blend_whose_spacing_doesnt_lay_out_its_steps_keeps_them`). @@ -1438,7 +1439,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur A `.ai`, or a PDF saved with Illustrator's editing data, whose editing data can't be decompressed opens from its PDF part with a warning that its layers weren't read and why, and an export or Save As to its own path asks first (`acknowledgeLoss`), as for a file whose layers the reader can't read (`crates/eps/src/import/tests_native.rs`, `crates/engine/src/cmd/fileio/tests_aiimport.rs`). A `.ai` or EPS opened from its editing data with one object on a shown layer that the reader can't read (an unknown operator inside a group, a pattern fill whose pattern it doesn't have, a symbol instance, a placed file without a usable preview) keeps its layers and groups: in that object's place, its layer gets a group of the page's objects inside the object's box, named after it, with a warning that lists what came in as the page's art and an export or Save As to its own path asking first (`acknowledgeLoss`). The file still opens from its page or PDF part when no box can be found, when live art or another unread object shares the page art inside it, when the object spans two artboards or lies on an artboard that has no page, when no page art lies inside its box, when that page art is inside a page group with a clip, mask, transparency or appearance, when the object holds a frame of threaded type, when the page art uses a pattern, image or swatch that the page lacks or that differs from the editing data's, or when the page art doesn't carry the object's transparency (#4806; `crates/eps/src/import/tests_native.rs`, `crates/engine/src/cmd/fileio/tests_aiimport.rs`). A `.ai` or EPS opened from its editing data with one object on a shown layer that the reader can't read (an unknown operator inside a group, a pattern fill whose pattern it doesn't have, a symbol instance, a placed file without a usable preview) keeps its layers and groups: in that object's place, its layer gets a group of the page's objects inside the object's box, named after it, with a warning that lists what came in as the page's art and an export or Save As to its own path asking first (`acknowledgeLoss`). The file still opens from its page or PDF part when no box can be found, when live art or another unread object shares the page art inside it, when the object spans two artboards, or when the page art doesn't carry the object's transparency (#4806; `crates/eps/src/import/tests_native.rs`, `crates/engine/src/cmd/fileio/tests_aiimport.rs`). - In a `.ai` opened from its editing data, an envelope made with a warp, a mesh or a top object opens as a live envelope of its contents, with its warp style, bend and distortions, its mesh points and handles or its top object's outline, its Envelope Options, its Fidelity and whether its contents are being edited. When Distort Appearance is on and the size the file saves for the contents matches their bounds with strokes, the contents map from that stroked box, until an edit in Edit Contents changes how far the strokes reach; VectorCraft's new envelopes map from the geometric box, as do contents with no width or no height, such as a single straight line. An envelope that can't be read, or that VectorCraft draws differently from the file's drawn art, keeps that drawn art, with a note. An envelope of type opens live, its type laid out from the text document as its contents, where VectorCraft's own envelope of that type draws as the drawn art the file saves (compared as for the other envelopes, seen on white and on black, so white type counts, and only where the layers with it are compared with the page and draw as it, the envelope weighed as the art it draws); elsewhere, and where the type's font isn't available, a text or visibility variable binds the type, or the envelope is in a symbol's or a pattern's art, it keeps its drawn art, with its type hidden and a note that says the type isn't editable (#3179; `crates/eps/src/import/ai/tests.rs`, `crates/eps/src/import/tests_native.rs`). A warp of type whose own warp, VectorCraft's, doesn't draw as its drawn art is tried again as a mesh envelope on the grid the file saves for it: its type stays editable and keeps the file's shape, but the warp's settings (style, bend) are lost, as the document has no place for them on a mesh. Type with strokes in an envelope with Distort Appearance on is also tried mapped from its glyphs grown by as far as its strokes paint along a side (half the weight of a centred stroke), without what miter joins add at corners, where the size the file saves for it doesn't already give that box; the drawn-art check decides which one opens. An envelope's grid reads its way round from all its rows and columns, so a mesh bent far round reads the way it runs. While an envelope's contents are edited, its mesh is kept in its dictionary, and in some files that mesh lies away from the drawn art by a move, the contents with the drawn art (as if the mesh hadn't followed the envelope when it moved): a mesh or top object saved in Edit Contents whose mesh draws the contents as large as the drawn art but elsewhere is tried again, after every other way, with its mesh moved onto that art, and opens there where it then draws as it. + In a `.ai` opened from its editing data, an envelope made with a warp, a mesh or a top object opens as a live envelope of its contents, with its warp style, bend and distortions, its mesh points and handles or its top object's outline, its Envelope Options, its Fidelity and whether its contents are being edited. When Distort Appearance is on and the size the file saves for the contents matches their bounds with strokes, the contents map from that stroked box, until an edit in Edit Contents changes how far the strokes reach; VectorCraft's new envelopes map from the geometric box, as do contents with no width or no height, such as a single straight line. An envelope that can't be read, or that VectorCraft draws differently from the file's drawn art, keeps that drawn art, with a note. An envelope of type opens live, its type laid out from the text document as its contents, where VectorCraft's own envelope of that type draws as the drawn art the file saves (compared as for the other envelopes, seen on white and on black, so white type counts, and only where the layers with it are compared with the page and draw as it, the envelope weighed as the art it draws); elsewhere, and where the type's font isn't available, a text or visibility variable binds the type, or the envelope is in a symbol's or a pattern's art, it keeps its drawn art, with its type hidden and a note that says the type isn't editable (#3179; `crates/eps/src/import/ai/tests.rs`, `crates/eps/src/import/tests_native.rs`). A warp of type whose own warp, VectorCraft's, doesn't draw as its drawn art is tried again as a mesh envelope on the grid the file saves for it: its type stays editable and keeps the file's shape, but the warp's settings (style, bend) are lost, as the document has no place for them on a mesh. Type with strokes in an envelope with Distort Appearance on is also tried mapped from its glyphs grown by as far as its strokes paint along a side (half the weight of a centred stroke), without what miter joins add at corners, where the size the file saves for it doesn't already give that box; the drawn-art check decides which one opens. An envelope's grid reads its way round from all its rows and columns, so a mesh bent far round reads the way it runs. While an envelope's contents are edited, its mesh is kept in its dictionary, and in some files that mesh lies away from the drawn art by a move, the contents with the drawn art (as if the mesh hadn't followed the envelope when it moved): a mesh or top object saved in Edit Contents whose mesh draws the contents as large as the drawn art but elsewhere is tried again, after every other way, with its mesh moved onto that art, and opens there where it then draws as it. The drawn art of these files strokes type in an envelope along its bent outlines at the stroke's own weight, Distort Appearance on or off, and VectorCraft draws it so (#6644): an envelope of stroked type whose grid squeezes or stretches it opens live where it draws as that art. 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`, off by default) writes such pages in points without a `UserUnit` at every PDF version. @@ -1981,6 +1982,7 @@ Edit › Copy and Cut put the selected ruler guides on the clipboard, with the s | Date | Change | Summary | |---|---|---| +| 2026-11-11 | minor | Envelopes: with Distort Appearance, type's strokes (characters' and appearance) paint along the bent glyph outlines at their own weight, as users' `.ai` files draw them; paths' strokes, geometry effects, gradients and patterns bend as before; also in an envelope inside an envelope; opacity masks bend as other art; Expand keeps type's strokes as strokes; the visual bounds of envelopes, blends and repeats and the reach of symbol art count type's character strokes as type's own bounds do. Changes how VectorCraft's own envelopes of stroked type draw. Advanced art evidence and `.ai` import evidence updated (#6644); 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. | diff --git a/docs/type-parity.md b/docs/type-parity.md index 702ecd5048..7d7af40c51 100644 --- a/docs/type-parity.md +++ b/docs/type-parity.md @@ -1,6 +1,6 @@ # Type parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-11 · **Change:** minor (a centred or right-aligned line of tracked type is aligned without the tracking after its last character, as the page of users' `.ai` files aligns it, #6610; previously minor: tracking and manual kerning in horizontally scaled type are thousandths of the em as the Horizontal Scale draws it, as the page of users' `.ai` files spaces such type; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: Direct Selection shows and drags the direction handles of type on a path's path, #3565; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; paint-only Arabic harakat keep joining with GDEF-mark ownership and Insert Kashidas base-letter paint; scores and estimates unchanged; custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: right-aligned area type sets the text after a line's last tab against the right edge; a soft return in justified type no longer keeps its line from being justified; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen) · **Target:** Adobe Illustrator 2026 (30.x) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-11-11 · **Change:** minor (type's strokes in an envelope paint along its bent glyph outlines at their own weight, Distort Appearance on or off, as users' `.ai` files draw them, #6644; previously minor: a centred or right-aligned line of tracked type is aligned without the tracking after its last character, as the page of users' `.ai` files aligns it, #6610; previously minor: tracking and manual kerning in horizontally scaled type are thousandths of the em as the Horizontal Scale draws it, as the page of users' `.ai` files spaces such type; previously minor: Edit › Edit Custom Dictionary…: its dialog adds, deletes and changes the custom dictionary's words, #4936; previously minor: Direct Selection shows and drags the direction handles of type on a path's path, #3565; previously minor: right-click on type: Spelling › Auto Spell Check, with its check mark, #4936; previously minor: right-click on a word Auto Spell Check underlined: its suggestions, Ignore All and Add to Dictionary, #4936; previously minor: Auto Spell Check: `edit.autoSpellCheck` underlines the unknown words, #4936; previously minor: PDF marked-text export (#6309): compatible glyphs stay on one layout line with per-glyph offsets; scores and estimates unchanged; paint-only Arabic harakat keep joining with GDEF-mark ownership and Insert Kashidas base-letter paint; scores and estimates unchanged; custom dictionary and Ignore All: `text.spelling.addWord`, `removeWord`, `changeWord`, `dictionary` and `ignoreAll`, #4936; previously minor: spell check engine: `text.spelling.check` and `text.spelling.suggest` on craft-proof, #4936; previously minor: right-aligned area type sets the text after a line's last tab against the right edge; a soft return in justified type no longer keeps its line from being justified; Character Styles panel: a double-click on a style's row opens its Character Style Options; the dialog keeps a fixed width and scrolls its sections, so its buttons stay on screen) · **Target:** Adobe Illustrator 2026 (30.x) Type is Illustrator's largest single area by use (weight 13 of 105 across "Type core" and "Type advanced" in [target-app-parity.md](target-app-parity.md)). This checklist lists the features one by one. Status is from the @@ -81,6 +81,7 @@ Character Styles menu New/Redefine and footer New capture the first selected cha | Date | Change | Summary | |---|---|---| +| 2026-11-11 | minor | Type in envelopes: its strokes (its characters' and those on its own appearance) paint along the bent glyph outlines at their own weight, Distort Appearance on or off, as the drawn art of users' `.ai` files strokes them; with Distort Appearance they bent with the art as their filled outlines. The same holds in an envelope inside an envelope. Geometry effects on type's fills and strokes, and an opacity mask on type, still bend; Expand gives the bent outlines with the strokes on them. The visual bounds of envelopes, blends and repeats count type's character strokes as type's own visual bounds do. This changes how VectorCraft's own envelopes of stroked type draw (#6644). Score unchanged (estimated) | | 2026-11-11 | minor | Aligned lines of tracked type: a centred or right-aligned line is as wide as its characters without the tracking after its last one (`LineInfo::trailing`), so a centred line sits half that tracking right of where it did and a right-aligned line's last glyph ends on its anchor or frame edge, the tracking after it reaching past. The page of users' `.ai` files (used locally, never committed) aligns tracked lines so: matched glyph by glyph with the page, 176 centred lines of point type in 51 files sat half their last character's tracking left of it (median 0.500 of it; 143 within 0.05 pt), 58 right-aligned lines in 5 files the whole tracking (median 1.001), and 182 left-aligned lines where the page has them; in a line whose last character is tracked 150 and the others −34, the offset is half the last character's tracking (0.498 of it). All those lines end a paragraph. The last character is the last the line draws before a paragraph's end, a forced line break or the spaces a wrap leaves (they hang past the line). Spaces or a tab typed before a paragraph's end or a forced line break are the line's last characters, and the letter before them keeps its tracking: in the 2 such lines in the files, the page counts the space and the letter's tracking and leaves out only the space's own (VectorCraft still leaves trailing spaces out of the width). Forced line breaks and wrapped lines of tracked type aren't in the files: they take the rule unverified, so that Convert To Point Type and Artwork Cleanup's Break Text, which turn wraps into paragraphs and forced line breaks, keep the lines where they were. A hyphenated line, one whose last character hangs, justified, vertical and right-to-left lines and type on a path keep the tracking, and so do right, centre and decimal tab stops, which still align the text after them with its last character's tracking. Manual kerning on the last character, line breaking and justification are unchanged (none in the files). The tracking stays in the last glyph's advance (the caret after it and a selection of it take it in), and Fit Headline still counts it, as line breaking does. Right-aligned area type sets the text after its last tab the same way. Convert To Area Type makes the frame end where the lines are aligned, with room for that tracking, so tracked type converted either way stays where it is (it moved by the tracking on each round trip). Affinity import aligns artistic text by the same rule, so centred or right-aligned tracked artistic text moves by half or all of its last character's tracking (unverified against Affinity). Centred and right-aligned tracked type lays out differently than before in every document. Tests `tests::an_aligned_line_leaves_its_last_characters_tracking_out_of_its_width`, `tests::which_lines_leave_the_tracking_after_their_last_character_out`, `tests::an_aligned_line_leaves_out_its_last_tracking_as_glyph_scaling_sets_it`, `tests::the_text_after_the_last_tab_of_right_aligned_type_leaves_its_last_tracking_out`, and the engine's `converting_tracked_type_between_point_and_area_keeps_it_in_place` and `break_tracked_area_type_keeps_its_aligned_lines_in_place`. Scores and estimates unchanged. (#6610) | | 2026-11-11 | minor | Tracking and manual kerning in horizontally scaled type: they are thousandths of the em as the Horizontal Scale draws it (`vectorcraft_text::spacing_scale`), so at 50% a tracking of 100 adds 0.05 em after each character, half as much as at 100%. They were added at the full em whatever the scale, so narrow tracked type drifted further right with each letter. Illustrator's own layout in users' `.ai` files (used locally, not committed) spaces such type so, and PDF scales its character spacing by its horizontal scaling alike (ISO 32000-1 §9.4.4). Inline graphics take it after them too; vertical type keeps the full em, its advances down the column not all taking the Horizontal Scale. The automatic kerning the Character panel reads, Touch Type's limits and Artwork Cleanup's Combine Point Text measure in the same em, and Scale Text Attributes now keeps tracked type where a horizontal stretch of its transform drew it. Type that has both a Horizontal Scale other than 100% and tracking or manual kerning lays out differently than before in every document. Tests `tests::tracking_and_manual_kerning_take_the_horizontal_scale`, `tests::typo::optical_pairs_in_horizontally_scaled_type_measure_without_the_scaled_tracking`, `tests::inline::shift_tracking_and_missing_symbols`, `tests::vertical::vertical_tracking_keeps_the_em_at_any_horizontal_scale` and the engine's `horizontally_scaled_pair_reads_as_the_kerning_that_keeps_it`, `scale_text_attributes_keeps_tracked_type_where_it_was` and `combine_puts_horizontally_scaled_pieces_back_where_they_were`. Scores and estimates unchanged. | | 2026-11-10 | minor | Edit Custom Dictionary (#4936): Edit › Edit Custom Dictionary… adds, deletes and changes the custom dictionary's words, applied on Done; the Check Spelling dialog remains. Scores and estimates unchanged. | From 8e8b43f045b9945d0824cbcb1fec6b4bcc7c5dd1 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 11 Nov 2026 16:02:52 -0500 Subject: [PATCH 02/38] ci: use StepSecurity's maintained actions (#6658) Each third-party action that StepSecurity publishes a secure drop-in replacement for now uses that replacement, pinned to a commit with its version as a comment. Versions follow what we used: the newest StepSecurity release in the same major, or the closest major they publish. dtolnay/rust-toolchain refs that named a toolchain (stable, nightly, 1.76) become the replacement's `toolchain` input. --- .github/workflows/affinity-corpus.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/affinity-corpus.yml b/.github/workflows/affinity-corpus.yml index 41ac5a00d7..b3e0178f56 100644 --- a/.github/workflows/affinity-corpus.yml +++ b/.github/workflows/affinity-corpus.yml @@ -30,7 +30,7 @@ jobs: egress-policy: audit - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - name: Install Rust - uses: dtolnay/rust-toolchain@686976e191b89faba57d3206551f0f330d8cb249 # stable + uses: step-security/dtolnay-rust-toolchain@8dd607977d06adf4ed49b190381e74c17a9dd25f # v1.0.0 with: toolchain: "1.95" - name: Fetch pinned and checksum-verified corpus From 566f720868c180c862311fb174cefe91e81e7abd Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Wed, 11 Nov 2026 16:11:34 -0500 Subject: [PATCH 03/38] SVG import: references follow an id's first element, one read per linked file, bounded blank lines (#5409) * fix(svg): first element of an id, shared linked file reads, bounded blank lines * address review: cache failed linked-image reads but give each href its own placeholder and link * address review: charge only blank lines to the line-break budget * address review: a collapsed line break keeps its measured leading in tiny type * address review: blank lines use the same scaled leading tolerance --- crates/svg/src/import/depth.rs | 19 +++++++++++++- crates/svg/src/import/files.rs | 28 +++++++++++++++----- crates/svg/src/import/text.rs | 20 ++++++++++++--- crates/svg/tests/it/import_details.rs | 37 +++++++++++++++++++++++++++ crates/svg/tests/it/import_text.rs | 19 ++++++++++++++ crates/svg/tests/it/roundtrip.rs | 16 ++++++++++++ 6 files changed, 129 insertions(+), 10 deletions(-) diff --git a/crates/svg/src/import/depth.rs b/crates/svg/src/import/depth.rs index 2cdccc9dad..0586deaf6f 100644 --- a/crates/svg/src/import/depth.rs +++ b/crates/svg/src/import/depth.rs @@ -220,7 +220,14 @@ fn prescan_with(svg: &str, most: usize) -> Prescan<'_> { /// `most`. Without recursion. pub(super) fn height(xml: &roxmltree::Document, most: usize) -> Option { let elements = || xml.descendants().filter(|n| n.is_element()); - let ids: HashMap<&str, XNode> = elements().filter_map(|n| Some((n.attribute("id")?, n))).collect(); + // The first element of an id, as usvg resolves references: a later one of the same id would + // hide a deep target behind a shallow one. + let mut ids: HashMap<&str, XNode> = HashMap::new(); + for n in elements() { + if let Some(id) = n.attribute("id") { + ids.entry(id).or_insert(n); + } + } let css = Styles::new(xml); // How deep each element's own tree goes, itself included; 0 while it is being worked out: a // reference back to it then is a loop, which usvg leaves out. @@ -394,6 +401,16 @@ mod tests { assert!(!deep(&svg(&format!("{defs}{art}")))); } + #[test] + fn a_reference_follows_the_first_element_of_its_id() { + // A chain of ``s as deep as the cap, each link's id given again later to an empty group: + // usvg follows the first, so the chain is deep. + let chain: String = (1..MAX_ELEMENT_DEPTH).map(|i| format!("", i - 1)).collect(); + let shallow: String = (1..MAX_ELEMENT_DEPTH).map(|i| format!("")).collect(); + let top = format!("", MAX_ELEMENT_DEPTH - 1); + assert!(deep(&svg(&format!("{chain}{shallow}{top}")))); + } + #[test] fn a_loop_of_references_is_not_deep() { assert!(!deep(&svg(""))); diff --git a/crates/svg/src/import/files.rs b/crates/svg/src/import/files.rs index 9de3bebcdf..1a4c06f0e6 100644 --- a/crates/svg/src/import/files.rs +++ b/crates/svg/src/import/files.rs @@ -49,11 +49,12 @@ pub(in crate::import) struct Files { /// How usvg holds the bytes of a raster of one format (`ImageKind::PNG`…). type RasterKind = fn(Arc>) -> ImageKind; +#[derive(Clone)] enum Source { /// A raster file of the kind usvg reads it as. Raster(RasterKind, Arc>), /// An SVG file's text (unpacked when it is SVGZ), parsed by usvg as an image. - Svg(String), + Svg(Arc), } /// A linked raster image (or the placeholder of a missing one). @@ -133,14 +134,29 @@ impl Files { pub(in crate::import) fn read(svg: &str, xml: &roxmltree::Document, opts: &ImportOptions, edits: &mut Edits, warnings: &mut Vec) -> Self { let mut files = Files::default(); let mut placeholder = None; + // What each file read gave, by the file: hrefs spelled differently (`a.png`, `./a.png`, + // `%61.png`) share one read and one copy of its bytes. + let mut by_file: HashMap> = HashMap::new(); for n in xml.descendants().filter(|n| n.is_element() && n.tag_name().name() == "image") { let Some(h) = href(n).filter(|h| !h.trim_start().starts_with("data:")) else { continue }; if !files.sources.contains_key(h) { let (path, file) = target(h, opts.folder); - let read = file.and_then(|file| opts.read.and_then(|read| read(&file))); - let source = match read { - Some((bytes, link)) => files.source(bytes, link).ok_or("is not an image VectorCraft reads"), - None => Err("not found"), + // A failed read is cached too, but each href gets its own placeholder: its own link + // path (an Arc shared between hrefs would share the first href's link) and warning. + let cached = file.as_ref().and_then(|f| by_file.get(f)).cloned(); + let source = match cached { + Some(source) => source, + None => { + let read = file.clone().and_then(|file| opts.read.and_then(|read| read(&file))); + let source = match read { + Some((bytes, link)) => files.source(bytes, link).ok_or("is not an image VectorCraft reads"), + None => Err("not found"), + }; + if let Some(file) = file { + by_file.insert(file, source.clone()); + } + source + } }; let source = source.or_else(|why| { warnings.push(format!("linked image '{h}' {why}: a placeholder keeps its place until it is relinked")); @@ -164,7 +180,7 @@ impl Files { let Ok(format) = image::guess_format(&bytes) else { // Unpacked once, here, within what the SVGZ images may unpack to. let text = crate::text_within(&bytes, &self.unpacked).ok()?; - return text.contains(" impl Iterator { v.split(|c: char| c.is_whitespace() || c == ',').filter(|t| !t.is_empty()) @@ -1155,6 +1159,12 @@ fn justify_of(anchor: f64) -> Justify { } } +/// How far a line's leading may differ from its spacing and still count as it: 0.01 absolute, but +/// never more than a thousandth of the spacing itself (tiny type has tiny gaps). +fn leading_tolerance(spacing: f64) -> f64 { + 0.01_f64.min(spacing.abs() * 1e-3) +} + /// Point type: line breaks, baseline shifts and kerning from the positioning lists. Returns the /// justification, the x of the first line's left (or anchor) edge and, when no character is /// placed on its own, each line's first character and anchor x. @@ -1175,6 +1185,7 @@ fn lines( // Line starts (first character, anchor x) and absolutely placed characters (index, x). let mut lines = vec![(0, x0)]; let mut targets: Vec<(usize, f64)> = vec![]; + let mut added = 0usize; for i in 1..n { let ny = y[i].unwrap_or(cur) + dy[i]; let lead = cells[i].style.effective_leading(); @@ -1183,7 +1194,9 @@ fn lines( // Whole multiples of the auto leading add blank lines (not without limit: a far-off y // mustn't ask for billions); other spacing is one break. let count = (gap / lead).round().clamp(1.0, MAX_LINE_GAP); - let count = if (gap / count - lead).abs() <= lead * 0.05 { count } else { 1.0 }; + // The first newline just ends the previous line: only the others are blank lines. + let count = if (gap / count - lead).abs() <= lead * 0.05 && added + (count as usize - 1) <= MAX_LINE_BREAKS { count } else { 1.0 }; + added += count as usize - 1; breaks.push(Break { at: i, count: count as usize, leading: gap / count }); lines.push((i, ax + dx[i])); (base, cur) = (ny, ny); @@ -1199,7 +1212,8 @@ fn lines( // A line's characters take its spacing as leading unless it is their auto leading. for (k, b) in breaks.iter().enumerate() { let end = breaks.get(k + 1).map_or(n, |nb| nb.at); - if cells[b.at..end].iter().any(|c| (c.style.effective_leading() - b.leading).abs() > 0.01) { + let tolerance = leading_tolerance(b.leading); + if cells[b.at..end].iter().any(|c| (c.style.effective_leading() - b.leading).abs() > tolerance) { for c in &mut cells[b.at..end] { c.style.leading = Some(b.leading); } @@ -1372,7 +1386,7 @@ fn assemble(cells: &[Cell], breaks: &[Break]) -> (Runs, Vec) { let key = (prev.fill, prev.stroke); push(&mut out, '\n', prev.final_style(), key); let mut blank = prev.final_style(); - if (blank.effective_leading() - b.leading).abs() > 0.01 { + if (blank.effective_leading() - b.leading).abs() > leading_tolerance(b.leading) { blank.leading = Some(b.leading); } for _ in 1..b.count { diff --git a/crates/svg/tests/it/import_details.rs b/crates/svg/tests/it/import_details.rs index 10418f3441..d6983a1ce2 100644 --- a/crates/svg/tests/it/import_details.rs +++ b/crates/svg/tests/it/import_details.rs @@ -88,6 +88,23 @@ fn a_linked_png_resolves_against_the_svg_folder_and_stays_linked() { assert!((b.x0 - 10.0).abs() < 1e-6 && (b.y0 - 20.0).abs() < 1e-6 && (b.width() - 80.0).abs() < 1e-6, "{b:?}"); } +#[test] +fn hrefs_spelling_one_file_differently_read_it_once() { + let dir = folder("spellings"); + std::fs::write(dir.join("img").join("a.png"), png(4, 4)).unwrap(); + let reads = std::sync::atomic::AtomicUsize::new(0); + let counting = |path: &str| { + reads.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + read(path) + }; + let folder = dir.to_string_lossy(); + let body = r#""#; + let (d, w) = import_with(&svg(body), &ImportOptions { folder: Some(&folder), read: Some(&counting) }).unwrap(); + assert!(w.is_empty(), "{w:?}"); + assert_eq!(images(&d).len(), 3); + assert_eq!(reads.into_inner(), 1, "one read for the three spellings"); +} + #[test] fn a_missing_link_warns_and_keeps_a_placeholder_in_its_box() { let dir = folder("missing"); @@ -139,6 +156,26 @@ fn files_with_the_same_pixels_have_keys_of_their_own() { assert_eq!(*d.images[&b.key].bytes, bytes); } +#[test] +fn hrefs_spelling_one_missing_file_differently_each_warn_and_keep_their_own_link() { + let dir = folder("missing_twice"); + let reads = std::sync::atomic::AtomicUsize::new(0); + let counting = |path: &str| { + reads.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + read(path) + }; + let folder = dir.to_string_lossy(); + let body = r#""#; + let (d, w) = import_with(&svg(body), &ImportOptions { folder: Some(&folder), read: Some(&counting) }).unwrap(); + assert_eq!(w.iter().filter(|w| w.contains("gone.png") && w.contains("not found")).count(), 2, "{w:?}"); + assert_eq!(reads.into_inner(), 1, "the failed read is cached"); + let found = images(&d); + assert_eq!(found.len(), 2); + for (_, im) in found { + assert_eq!(Path::new(&im.link.as_ref().unwrap().path), dir.join("img").join("gone.png")); + } +} + #[test] fn svg_images_import_as_vector_art() { let dir = folder("svgimage"); diff --git a/crates/svg/tests/it/import_text.rs b/crates/svg/tests/it/import_text.rs index 35289a0c1d..8b0d0338c6 100644 --- a/crates/svg/tests/it/import_text.rs +++ b/crates/svg/tests/it/import_text.rs @@ -277,6 +277,25 @@ fn anchored_letter_spaced_lines_stay_where_a_reader_draws_them() { assert!(close(s[0], 200.0 - a[0] / 2.0, 1e-6) && close(s[1], 200.0 - a[1], 1e-6), "{s:?} {a:?}"); } +#[test] +fn a_small_line_gap_in_tiny_type_keeps_its_leading() { + // 0.0085 against an auto leading of 0.006 differs by less than 0.01 but is not a whole multiple of it. + let d = open(r#"OneTwo"#); + let t = only_text(&d); + let two = t.runs.iter().find(|r| r.text.contains("Two")).unwrap().style.leading; + assert!(two.is_some_and(|l| close(l, 0.0085, 1e-9)), "{two:?}"); +} + +#[test] +fn blank_lines_in_tiny_type_keep_their_own_spacing() { + // B sits 0.0085 below A (kept as its leading); C is three 0.006 lines below B, so the two blank + // lines between them must be 0.006 apart, not carry B's 0.0085. + let d = open(r#"ABC"#); + let t = only_text(&d); + let blank = t.runs.iter().find(|r| r.text == "\n\n").expect("a run of the two blank lines"); + assert!(blank.style.leading.is_some_and(|l| close(l, 0.006, 1e-9)), "{:?}", blank.style.leading); +} + #[test] fn tspan_lines_dx_and_baseline_shift() { let d = open( diff --git a/crates/svg/tests/it/roundtrip.rs b/crates/svg/tests/it/roundtrip.rs index b13ecf160b..127e47846c 100644 --- a/crates/svg/tests/it/roundtrip.rs +++ b/crates/svg/tests/it/roundtrip.rs @@ -909,6 +909,22 @@ fn import_tspan_far_below_is_bounded() { assert!(breaks <= 10_002, "{breaks} line breaks"); } +#[test] +fn import_many_tspans_far_apart_are_bounded_together() { + // Each tspan 9,999 lines (auto leading 14.4 pt) below the last: each within the limit of one gap, + // two hundred of them were two million line breaks. + let spans: String = (1..=200).map(|i| format!(r#"{i}"#, 20.0 + 14.4 * 9_999.0 * i as f64)).collect(); + let d = import_art(&format!( + r#"a{spans}"# + )); + let a = art(&d); + let NodeKind::Text(t) = &a[0].kind else { panic!() }; + let text = t.plain_text(); + assert!(text.ends_with("200"), "{}", &text[text.len().saturating_sub(20)..]); + let breaks = text.matches('\n').count(); + assert!(breaks <= 10_200, "{breaks} line breaks"); +} + #[test] fn import_tspan_on_the_same_baseline_stays_on_the_line() { // Styled runs positioned on the line's own baseline (as Illustrator writes them, with x and y on From 3edc1640fd1bc89f67db67337651a73a96195cc3 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 13:17:39 -0800 Subject: [PATCH 04/38] Simplify: a flat closed loop keeps its outline when splitting reaches its limit Follows #6651. When the refits of a closed subpath enclose no area, Simplify splits its curves until straight lines between the pieces enclose one. That split stopped at 65,536 pieces in all, and a loop with many anchors then came back as the flat refit, with no outline. - Only curved segments are split; line segments stay one piece each. - When no split within the limits encloses an area, the loop stays as it is. With Convert to Straight Lines, each curved segment becomes the lines between its samples instead. --- crates/pathops/src/edit.rs | 44 +++++++++++++++++++++++++++------- crates/pathops/tests/it/ops.rs | 36 ++++++++++++++++++++++++++++ 2 files changed, 71 insertions(+), 9 deletions(-) diff --git a/crates/pathops/src/edit.rs b/crates/pathops/src/edit.rs index a82503391c..da8e5e4d8f 100644 --- a/crates/pathops/src/edit.rs +++ b/crates/pathops/src/edit.rs @@ -88,7 +88,9 @@ pub fn simplify_with(path: &PathData, opts: &SimplifyOptions) -> PathData { /// whose refit is one segment, or lines that enclose no area, is refitted in two parts, cut at the /// point farthest from its start, or in three when two still give that. When three parts still give /// no area, straight lines follow the subpath within the tolerance, and without straight lines it -/// stays as it is, as does one of a single segment; one that is all in line keeps the refit. +/// stays as it is, as does one of a single segment. When no lines within the limits on pieces enclose +/// an area, it stays as it is, or with straight lines follows the lines between samples of each +/// curved segment; one that is all in line keeps the refit. fn simplify_subpath(sp: &SubPath, opts: &SimplifyOptions) -> Option { let mut segs = subpath_segs(sp); let n = segs.len(); @@ -139,27 +141,51 @@ fn simplify_subpath(sp: &SubPath, opts: &SimplifyOptions) -> Option { } let ctrl: Vec = segs.iter().flat_map(|s| [s.c.p0, s.c.p1, s.c.p2]).collect(); if flat(&result) && !in_line(&ctrl) { - // Each segment split in 2, 4, 8 and so on, up to 1,024 pieces and 65,536 in all, until every - // piece is within the tolerance of the line between its ends and those lines enclose an - // area: with straight lines they are the result, and without them the loop stays as it is. - // A loop whose points are all in line keeps the lines of the refit. + // Each curved segment split in 2, 4, 8 and so on, up to 1,024 pieces and 65,536 pieces in all + // with the line segments, until every piece is within the tolerance of the line between its + // ends and those lines enclose an area: with straight lines they are the result, and without + // them the loop stays as it is. When no split within those limits encloses an area, the loop + // stays as it is, or with straight lines each curved segment becomes the lines between its + // samples, up to `MAX_RUN_RESULT` lines in all. A loop whose points are all in line keeps the + // lines of the refit. let near = |c: &CubicBez| [c.p1, c.p2].iter().all(|&p| Line::new(c.p0, c.p3).nearest(p, 1e-9).distance_sq.sqrt() <= opts.tolerance); + let curved = segs.iter().filter(|s| !s.line).count(); for k in 1..=10u32 { let parts = 1u32 << k; - if segs.len().saturating_mul(parts as usize) > 1 << 16 { + if curved.saturating_mul(parts as usize).saturating_add(n - curved) > 1 << 16 { break; } let at = |i: u32| f64::from(i) / f64::from(parts); - let pieces: Vec = segs.iter().flat_map(|s| (0..parts).map(move |i| s.c.subsegment(at(i)..at(i + 1)))).collect(); + let pieces: Vec = segs + .iter() + .flat_map(|s| { + let count = if s.line { 1 } else { parts }; + (0..count).map(move |i| if s.line { s.c } else { s.c.subsegment(at(i)..at(i + 1)) }) + }) + .collect(); let lines: Vec = pieces.iter().map(|c| Seg::line(c.p0, c.p3)).collect(); if pieces.iter().all(near) && !flat(&lines) { if !opts.straight_lines { return Some(sp.clone()); } - result = lines; - break; + return segs_to_subpath(&lines, true); } } + if !opts.straight_lines { + return Some(sp.clone()); + } + let room = (MAX_RUN_RESULT / curved.max(1)).min(MAX_SEGMENT_SAMPLES); + let mut lines: Vec = Vec::new(); + for s in &segs { + if s.line { + lines.push(Seg::line(s.c.p0, s.c.p3)); + continue; + } + let mut pts = Vec::new(); + sample(&s.c, sample_steps(&s.c, opts.tolerance.max(1e-6)).min(room).max(1), &mut pts, true); + lines.extend(pts.windows(2).map(|p| Seg::line(p[0], p[1]))); + } + return segs_to_subpath(&lines, true); } } let s = segs_to_subpath(&result, sp.closed)?; diff --git a/crates/pathops/tests/it/ops.rs b/crates/pathops/tests/it/ops.rs index 9a6fb57138..81e7f83ce7 100644 --- a/crates/pathops/tests/it/ops.rs +++ b/crates/pathops/tests/it/ops.rs @@ -479,6 +479,42 @@ fn simplify_keeps_a_closed_subpath_that_refits_to_one_curve() { assert!(max_deviation(&long, &s) <= 0.1 + 1e-6, "{s:?}"); } +/// An S curve closed by a straight edge of 20,000 anchors, whose curve shows only when it is split in +/// four, keeps its outline within the tolerance. With corner anchors on the edge, only the curve is +/// split. With smooth anchors whose handles lie along the edge, four pieces of every segment pass the +/// limit on pieces: the loop stays as it is, or with straight lines follows lines between samples. +#[test] +fn simplify_keeps_a_flat_loop_with_many_anchors_on_its_edge() { + let n = 20_000; + let step = 100.0 / f64::from(n); + let curve_anchors = vec![ + Anchor::with_handles(Point::new(0.0, 0.0), Point::new(0.0, 0.0), Point::new(0.0, 3.0)), + Anchor::with_handles(Point::new(100.0, 0.0), Point::new(0.0, -3.0), Point::new(100.0, 0.0)), + ]; + let curve = PathData::single(SubPath::new(curve_anchors.clone(), false)); + for smooth_edge in [false, true] { + let mut anchors = curve_anchors.clone(); + anchors.extend((1..n).map(|i| { + let p = Point::new(100.0 - f64::from(i) * step, 0.0); + if smooth_edge { + Anchor::with_handles(p, Point::new(p.x + step / 3.0, 0.0), Point::new(p.x - step / 3.0, 0.0)) + } else { + Anchor::corner(p) + } + })); + let path = PathData::single(SubPath::new(anchors, true)); + for straight_lines in [false, true] { + let s = simplify_with(&path, &SimplifyOptions { tolerance: 4.0, straight_lines, ..Default::default() }); + let at = format!("smooth edge {smooth_edge}, straight lines {straight_lines}"); + assert_eq!(s.subpaths.len(), 1, "{at}"); + let sp = &s.subpaths[0]; + assert!(sp.closed && sp.area().abs() > 1.0, "{at}: area {}", sp.area()); + assert!(max_deviation(&curve, &s) <= 4.0 + 1e-6, "{at}: {}", max_deviation(&curve, &s)); + assert!(!straight_lines || (0..sp.segment_count()).all(|i| sp.segment_is_line(i)), "{at}: a curve is left"); + } + } +} + /// The Simplify slider's levels: 1 pt at 50, doubled for every 10 levels down and halved for every /// 10 up; Auto-Simplify takes the lowest level whose tolerance is at most 1/400 of the size, and /// level 100 for a size under 12.5 pt. From dc98b59444753786f56a10b774dd2c2c2113c970 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 13:45:46 -0800 Subject: [PATCH 05/38] PDF: the in-points option leaves PDF/A pages within the standard's size limit longPagesInPoints now applies only to files without a standard. PDF/A-2 limits page boundaries to 14,400 units (ISO 19005-2, 6.1.13), so a PDF/A file with a page longer than 200 in keeps its UserUnit whether the option is on or off. The Save PDF dialog disables the checkbox for PDF/A as it does for PDF/X. Follows #6643. --- crates/engine/src/cmd/fileio/pdf.rs | 4 +-- crates/pdf/src/export/entry.rs | 15 ++++++--- crates/pdf/src/settings.rs | 5 +-- crates/pdf/src/tests/marks.rs | 23 ++++++++++++++ crates/ui-egui/src/dialogs/save_pdf.rs | 5 +-- crates/ui-egui/src/dialogs/save_pdf/tests.rs | 33 ++++++++++++++++++++ docs/mcp.md | 5 ++- docs/target-app-parity.md | 2 +- 8 files changed, 80 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/cmd/fileio/pdf.rs b/crates/engine/src/cmd/fileio/pdf.rs index 365edbedbf..a18af48af1 100644 --- a/crates/engine/src/cmd/fileio/pdf.rs +++ b/crates/engine/src/cmd/fileio/pdf.rs @@ -99,7 +99,7 @@ pub(crate) const OPTIONS: &[FormatOption] = &[ name: "longPagesInPoints", ty: "boolean", default: "false", - description: "a page with a side longer than 14,400 pt (200 in) is written at its size in points, without a UserUnit, at every PDF version", + description: "a page with a side longer than 14,400 pt (200 in) is written at its size in points, without a UserUnit, at every PDF version, in files without a standard (PDF/A files keep the UserUnit)", }, FormatOption { name: "createLayers", @@ -128,7 +128,7 @@ pub fn specs() -> Vec { "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), 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; 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; PDF/X files, 1.3 and 1.4 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?: false (true: such a page is written at its size in points, without a UserUnit, at every version, and 1.5 stays 1.5; apps that keep to the limit cut it to 200 in), 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, 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)|all|destination|taggedSource (documents assigned a profile: edit.assignProfile) (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), 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", + "{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), 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; 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; PDF/X files, 1.3 and 1.4 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?: false (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), 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, 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)|all|destination|taggedSource (documents assigned a profile: edit.assignProfile) (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), 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", has_doc, export_pdf ), diff --git a/crates/pdf/src/export/entry.rs b/crates/pdf/src/export/entry.rs index fc48485216..d6fb01a07c 100644 --- a/crates/pdf/src/export/entry.rs +++ b/crates/pdf/src/export/entry.rs @@ -192,10 +192,17 @@ const MIN_PAGE_SIDE: f64 = 3.0; const MAX_PDF14_REAL: f64 = 32_767.0; /// Pages with a side longer than [`MAX_PAGE_SIDE`] are written with a `UserUnit`: in PDF 1.6 and -/// later files that aren't PDF/X files, unless `long_pages_in_points` is on. Other files have +/// later files that aren't PDF/X files, unless `long_pages_in_points` applies. Other files have /// every page in points. fn writes_user_units(set: &PdfSettings) -> bool { - set.compatibility.has_user_unit() && !set.standard.is_pdfx() && !set.long_pages_in_points + set.compatibility.has_user_unit() && !set.standard.is_pdfx() && !long_pages_in_points(set) +} + +/// `long_pages_in_points` is on in a file without a standard. PDF/X files write long pages in +/// points anyway, and PDF/A files keep the `UserUnit`, which keeps their page boundaries within +/// 14,400 units (ISO 19005-2, 6.1.13). +fn long_pages_in_points(set: &PdfSettings) -> bool { + set.long_pages_in_points && set.standard == Standard::None } /// The `UserUnit` (PDF 1.6) of a page `w` × `h` points large: 1 when both sides are at most @@ -221,7 +228,7 @@ pub fn check_page_sizes(doc: &Document, opts: &PdfOptions) -> Result<(), PdfErro /// The settings `set` is written with when one of `pages` has a side longer than /// [`MAX_PAGE_SIDE`]: a PDF 1.5 file that isn't a PDF/X file is written as PDF 1.6, which has a -/// page's `UserUnit`, unless `long_pages_in_points` is on (`None`: `set` as it is). Other files +/// page's `UserUnit`, unless `long_pages_in_points` applies (`None`: `set` as it is). Other files /// without a `UserUnit` have the page in points. The writer puts a whole number as an integer and fails a PDF 1.3 or 1.4 file that has /// a real number past [`MAX_PDF14_REAL`]: a page whose side is past it and not a whole number of /// points is refused here, before anything is drawn ([`page_too_long`]). @@ -229,7 +236,7 @@ fn for_long_pages(set: &PdfSettings, pages: &[(usize, PageBoxes)]) -> Result MAX_PAGE_SIDE) { return Ok(None); } - let raised = (set.compatibility == Compatibility::Pdf15 && !set.standard.is_pdfx() && !set.long_pages_in_points) + let raised = (set.compatibility == Compatibility::Pdf15 && !set.standard.is_pdfx() && !long_pages_in_points(set)) .then(|| PdfSettings { compatibility: Compatibility::Pdf16, ..set.clone() }); // The writer's test for a whole number, on the `f32` it writes. let real = |side: f64| side > MAX_PDF14_REAL && (side as f32) as i32 as f32 != side as f32; diff --git a/crates/pdf/src/settings.rs b/crates/pdf/src/settings.rs index b4b25baebf..710037a7c1 100644 --- a/crates/pdf/src/settings.rs +++ b/crates/pdf/src/settings.rs @@ -237,8 +237,9 @@ pub struct PdfSettings { /// `create_layers` is on). pub include_non_printing: bool, /// Write a page with a side longer than 14,400 pt (200 in) at its size in points, without a - /// `UserUnit`, at every PDF version (off: PDF 1.6 and later files that aren't PDF/X files - /// write it with a `UserUnit`, and PDF 1.5 files are written as PDF 1.6 for it). + /// `UserUnit`, at every PDF version, in files without a standard (off, and in PDF/A files: + /// PDF 1.6 and later files that aren't PDF/X files write it with a `UserUnit`, and PDF 1.5 + /// files are written as PDF 1.6 for it). pub long_pages_in_points: bool, pub compression: CompressionSettings, pub marks: MarkSettings, diff --git a/crates/pdf/src/tests/marks.rs b/crates/pdf/src/tests/marks.rs index c829ed8d5a..47ee3dfa79 100644 --- a/crates/pdf/src/tests/marks.rs +++ b/crates/pdf/src/tests/marks.rs @@ -477,6 +477,29 @@ fn long_pages_in_points_keeps_every_version_and_changes_nothing_where_pages_are_ assert_eq!(report(&d, with(&x4)).unwrap().bytes, report(&d, x4).unwrap().bytes); } +/// PDF/A-2 limits page boundaries to 14,400 units (ISO 19005-2, 6.1.13): with +/// `long_pages_in_points`, a PDF/A file gives the same file as without it at every version its +/// standard allows, and a 10 m page keeps its `UserUnit` from PDF 1.5 on (PDF 1.5 is written as +/// PDF 1.6 for it). +#[test] +fn pdfa2b_long_page_stays_within_14400_units() { + let d = sized(TEN_M, TEN_M / 10.0); + for s in Standard::ALL.iter().copied().filter(|s| *s != Standard::None && !s.is_pdfx()) { + for c in Compatibility::ALL.iter().copied().filter(|c| s.allows(*c)) { + let off = PdfSettings { standard: s, compatibility: c, ..PdfSettings::default() }; + let on = PdfSettings { long_pages_in_points: true, ..off.clone() }; + let (on, off) = (report(&d, on).unwrap(), report(&d, off).unwrap()); + assert_eq!(on.bytes, off.bytes, "{} {}", s.label(), c.label()); + assert_eq!(on.warnings, off.warnings, "{} {}", s.label(), c.label()); + if c != Compatibility::Pdf14 { + assert_eq!(raw_numbers(&on.bytes, "/UserUnit", 1), [1.969], "{} {}", s.label(), c.label()); + let media = raw_numbers(&on.bytes, "/MediaBox", 4); + assert!(media[2] - media[0] <= 14_400.0 && media[3] - media[1] <= 14_400.0, "{} {}: {media:?}", s.label(), c.label()); + } + } + } +} + /// A page of 14,400 pt or less gives the same file with `long_pages_in_points` on or off, at every /// PDF version. #[test] diff --git a/crates/ui-egui/src/dialogs/save_pdf.rs b/crates/ui-egui/src/dialogs/save_pdf.rs index ba6d206074..e2f21c80cf 100644 --- a/crates/ui-egui/src/dialogs/save_pdf.rs +++ b/crates/ui-egui/src/dialogs/save_pdf.rs @@ -478,9 +478,10 @@ fn general(ui: &mut egui::Ui, d: &mut Dialog, editor: bool) { let layers = standard.allows_layers() && choice::(d, "compatibility").unwrap_or_default().has_layers(); flag(ui, d, "createLayers", tl!("Create PDF layers from layers and sublayers"), layers); flag(ui, d, "includeNonPrinting", tl!("Include non-printing layers"), true); - // PDF/X files and PDF 1.3 and 1.4 files always write long pages in points. + // PDF/X files and PDF 1.3 and 1.4 files always write long pages in points, and PDF/A files + // keep the `UserUnit`. let compatibility = choice::(d, "compatibility").unwrap_or_default(); - let scales = !standard.is_pdfx() && !matches!(compatibility, Compatibility::Pdf13 | Compatibility::Pdf14); + let scales = standard == Standard::None && !matches!(compatibility, Compatibility::Pdf13 | Compatibility::Pdf14); flag(ui, d, "longPagesInPoints", tl!("Write pages longer than 200 in at full size in points"), scales); if editor { heading(ui, tl!("Description")); diff --git a/crates/ui-egui/src/dialogs/save_pdf/tests.rs b/crates/ui-egui/src/dialogs/save_pdf/tests.rs index 7bb471a76e..a6f4e9884c 100644 --- a/crates/ui-egui/src/dialogs/save_pdf/tests.rs +++ b/crates/ui-egui/src/dialogs/save_pdf/tests.rs @@ -323,6 +323,39 @@ 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))); } +/// "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`. +#[test] +fn the_long_pages_in_points_check_box_is_disabled_with_a_standard() { + const LABEL: &str = "Write pages longer than 200 in at full size in points"; + let (mut app, _, _) = app(); + app.run("ui.savePdfDialog", json!({})).unwrap(); + let ctx = egui::Context::default(); + ctx.enable_accesskit(); + theme::install_fonts(&ctx); + let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1280.0, 900.0)); + let frame = |app: &mut VectorcraftApp| { + let input = egui::RawInput { screen_rect: Some(screen), ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| super::super::show(app, ui.ctx())); + out.textures_delta.clear(); + out + }; + for s in Standard::ALL.iter().copied() { + for c in Compatibility::ALL.iter().copied().filter(|c| s.allows(*c)) { + set_field(&mut app, "standard", json!(s.id())); + set_field(&mut app, "compatibility", json!(c.id())); + frame(&mut app); + let out = frame(&mut app); + let nodes = &out.platform_output.accesskit_update.as_ref().expect("an accessibility tree").nodes; + let node = nodes.iter().find(|(_, n)| n.label() == Some(LABEL) && n.role() == egui::accesskit::Role::CheckBox); + let disabled = node.unwrap_or_else(|| panic!("no check box named {LABEL:?}")).1.is_disabled(); + let enabled = s == Standard::None && !matches!(c, Compatibility::Pdf13 | Compatibility::Pdf14); + assert_eq!(disabled, !enabled, "{} {}", s.label(), c.label()); + } + } +} + #[test] fn create_layers_writes_pdf_layers() { let (mut app, written, _) = app(); diff --git a/docs/mcp.md b/docs/mcp.md index 5826c5c8c4..771f11ccdd 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -877,7 +877,10 @@ rounded up to the next thousandth, with the page's sizes and coordinates in thos keeps PDF 1.5's encryption (128-bit RC4). PDF/X files and PDF 1.3 and 1.4 files write such a page in points, and apps that keep to the limit cut it to 200 in. `longPagesInPoints: true` (off by default; "Write pages longer than 200 in at full size in points" in the Save PDF dialog's General section) writes such a page in points at every PDF version, without -a `UserUnit`, and a PDF 1.5 file stays PDF 1.5; the warning then says the page is written in points. In PDF 1.3 and 1.4 files, PDF/X-1a and PDF/X-3 among them, a real number can +a `UserUnit`, and a PDF 1.5 file stays PDF 1.5; the warning then says the page is written in points. The option applies +only to files without a standard: PDF/X files write such a page in points anyway, and PDF/A files keep the `UserUnit`, +which keeps their page boundaries within PDF/A-2's limit of 14,400 units (ISO 19005-2, 6.1.13). The dialog disables the +checkbox when a standard is chosen. In PDF 1.3 and 1.4 files, PDF/X-1a and PDF/X-3 among them, a real number can be at most 32,767, and whole numbers are written as integers: a page longer than 32,767 pt whose sides aren't whole numbers of points fails the export with an error naming the page before the thumbnails are drawn and the transparency is flattened, and one whose art needs a real number past 32,767 fails with the same error when the file is written. A page whose short side is 3 pt or longer but would be under 3 units at that diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index b4c949f742..4de9e947f9 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1441,7 +1441,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 envelope made with a warp, a mesh or a top object opens as a live envelope of its contents, with its warp style, bend and distortions, its mesh points and handles or its top object's outline, its Envelope Options, its Fidelity and whether its contents are being edited. When Distort Appearance is on and the size the file saves for the contents matches their bounds with strokes, the contents map from that stroked box, until an edit in Edit Contents changes how far the strokes reach; VectorCraft's new envelopes map from the geometric box, as do contents with no width or no height, such as a single straight line. An envelope that can't be read, or that VectorCraft draws differently from the file's drawn art, keeps that drawn art, with a note. An envelope of type opens live, its type laid out from the text document as its contents, where VectorCraft's own envelope of that type draws as the drawn art the file saves (compared as for the other envelopes, seen on white and on black, so white type counts, and only where the layers with it are compared with the page and draw as it, the envelope weighed as the art it draws); elsewhere, and where the type's font isn't available, a text or visibility variable binds the type, or the envelope is in a symbol's or a pattern's art, it keeps its drawn art, with its type hidden and a note that says the type isn't editable (#3179; `crates/eps/src/import/ai/tests.rs`, `crates/eps/src/import/tests_native.rs`). A warp of type whose own warp, VectorCraft's, doesn't draw as its drawn art is tried again as a mesh envelope on the grid the file saves for it: its type stays editable and keeps the file's shape, but the warp's settings (style, bend) are lost, as the document has no place for them on a mesh. Type with strokes in an envelope with Distort Appearance on is also tried mapped from its glyphs grown by as far as its strokes paint along a side (half the weight of a centred stroke), without what miter joins add at corners, where the size the file saves for it doesn't already give that box; the drawn-art check decides which one opens. An envelope's grid reads its way round from all its rows and columns, so a mesh bent far round reads the way it runs. While an envelope's contents are edited, its mesh is kept in its dictionary, and in some files that mesh lies away from the drawn art by a move, the contents with the drawn art (as if the mesh hadn't followed the envelope when it moved): a mesh or top object saved in Edit Contents whose mesh draws the contents as large as the drawn art but elsewhere is tried again, after every other way, with its mesh moved onto that art, and opens there where it then draws as it. 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`, off by default) writes such pages in points without a `UserUnit` at every PDF version. + 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`, off by default) writes such pages in points without a `UserUnit` at every PDF version, in files without a PDF/X or PDF/A standard. PDF export warns when a PDF/X file has no bleed on a side where the document's bleed has one, and writes the file as asked. PDF/X-1a, PDF/X-3 and PDF 1.3 files keep the art under the hidden part of a picture, gradient, pattern, mesh or raster effect that a clipping mask or clipping layer crops: flattening rasterizes only the part of such art that its clipping path shows, on its own page and on the next one. Layers the file leaves out are left out of the flattening, and transparent art that a clipping path hides entirely is removed (`crates/engine/src/cmd/fileio/tests_pdfx.rs`). Placed (linked) files in a `.ai`'s editing data come in 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 (a file found next to the document, at its path, or in the folder the editing data names relative to the document's, such as `src/`, is read as the document opens, and its link takes that file's size, modification time and hash). A file with them no longer falls back to its PDF part, so its guides, sublayers and hidden objects open (#1264; `crates/eps/src/import/ai/tests.rs`, `crates/engine/src/tests/links.rs`). In a file opened that way, a gradient with stops in the middle runs its whole ramp across its shape and a gradient object no longer passes its fill to the next path (#1390); 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 made taller with a warning in the open result (#1392). From fc767dad097a60648b8dc58089e0c4d8d070213e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 13:53:20 -0800 Subject: [PATCH 06/38] Type: Dynamic Text sets each line of area type to the frame width Type > Dynamic Text (type.dynamicText) now also works on area type as Block. Each line as typed (each paragraph, and each forced line break in one) is set to the frame's width, less the inset, the column gutters and the paragraph's indents, by changing its font size only. Lines are not broken again. The first character's size moves in 0.1 pt steps within 0.1 to 1,296 pt, and the line's other characters keep their proportions. The sizes are written into the characters and fitted again after every edit to the text or the frame, in the same undo step. - Word Gap (0 to 1,000 % of a word space, default 100) sets every paragraph's Desired word spacing; Line Gap (-1,296 to 1,296 pt, default 0) is added to each character's size for its leading. Both are VectorCraft's own ranges and defaults, saved in the area options only when they differ from the defaults. - Area Type Options gains a Block fit (text.areaOptions fit "block", with wordGap and lineGap), and the Properties panel's Paragraph section shows a Dynamic Text checkbox with Word Gap and Line Gap rows. - Block replaces Auto Size and Shrink Text to Fit. Off keeps the sizes. Threaded area type is refused, as for type on a path. - Empty lines keep their size, a frame with no width changes nothing, vertical type fits each line to the frame's height, and right-to-left lines and list markers are fitted like other lines. A refit runs at most four extra layouts. Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/doc/src/text.rs | 11 +- crates/doc/src/text/area.rs | 25 ++ crates/engine/src/cmd/create.rs | 17 +- crates/engine/src/cmd/textedit.rs | 4 +- crates/engine/src/cmd/typecmd.rs | 102 +++-- crates/engine/src/cmd/typecmd/block.rs | 309 ++++++++++++++ crates/engine/src/cmd/typecmd/block_tests.rs | 385 ++++++++++++++++++ crates/engine/src/cmd/typemenu.rs | 115 ++++-- crates/engine/src/inspect.rs | 7 +- crates/engine/src/tests/dynamic_text.rs | 10 +- crates/ui-egui/src/dialogs/command.rs | 6 +- crates/ui-egui/src/i18n/hi.tsv | 2 +- crates/ui-egui/src/i18n/sv.tsv | 2 +- crates/ui-egui/src/menus/state.rs | 18 +- crates/ui-egui/src/menus/tests.rs | 11 +- crates/ui-egui/src/panels/properties.rs | 3 + .../src/panels/properties/dynamic_text.rs | 84 ++++ crates/ui-egui/src/panels/properties/tests.rs | 35 ++ docs/mcp.md | 55 ++- docs/target-app-parity.md | 1 + 20 files changed, 1100 insertions(+), 102 deletions(-) create mode 100644 crates/engine/src/cmd/typecmd/block.rs create mode 100644 crates/engine/src/cmd/typecmd/block_tests.rs create mode 100644 crates/ui-egui/src/panels/properties/dynamic_text.rs diff --git a/crates/doc/src/text.rs b/crates/doc/src/text.rs index 0be38d261e..05f9c29041 100644 --- a/crates/doc/src/text.rs +++ b/crates/doc/src/text.rs @@ -77,10 +77,13 @@ pub struct TextObject { /// them up round the inside. #[serde(default, rename = "pathSpacing", skip_serializing_if = "crate::skip::is_default")] pub path_spacing: f64, - /// Type › Dynamic Text (type on a path only): the layout scales the text by one factor so it - /// fills the span between its start and end brackets, and fits it again after each edit. The - /// stored sizes keep their proportions; the layout's `fit_scale` is the factor drawn. Off for new - /// type and for documents from before it, and saved only when on. + /// Type › Dynamic Text. On type on a path, the layout scales the text by one factor so it + /// fills the span between its start and end brackets, and fits it again after each edit; the + /// stored sizes keep their proportions, and the layout's `fit_scale` is the factor drawn. On + /// area type it is Block: after each edit the engine sets each line as typed to the frame's + /// width by its font size and writes the sizes into the characters, with the gaps of + /// [`AreaOptions::word_gap`] and [`AreaOptions::line_gap`]. Point type does not use it. Off for + /// new type and for documents from before it, and saved only when on. #[serde(default, rename = "dynamicText", skip_serializing_if = "crate::skip::is_default")] pub dynamic_text: bool, /// Wrap objects above this area type, resolved by the engine after each edit (text space). diff --git a/crates/doc/src/text/area.rs b/crates/doc/src/text/area.rs index 7bb742f483..1901a23c8a 100644 --- a/crates/doc/src/text/area.rs +++ b/crates/doc/src/text/area.rs @@ -167,6 +167,14 @@ pub struct AreaOptions { /// How the frame and its text fit each other (Auto Size, Shrink Text to Fit). #[serde(skip_serializing_if = "crate::skip::is_default")] pub fit: AreaFit, + /// Dynamic Text's Block ([`super::TextObject::dynamic_text`] on area type): every paragraph's + /// Desired word spacing, in percent of a word space (100, the default, is left out when saved). + #[serde(skip_serializing_if = "AreaOptions::is_default_word_gap")] + pub word_gap: f64, + /// Dynamic Text's Block: the points added to each character's size to give its leading (0, the + /// default, is left out when saved). + #[serde(skip_serializing_if = "crate::skip::is_default")] + pub line_gap: f64, } impl Default for AreaOptions { @@ -182,6 +190,8 @@ impl Default for AreaOptions { vertical_align: VerticalAlign::Top, flow: TextFlow::Columns, fit: AreaFit::None, + word_gap: Self::DEFAULT_WORD_GAP, + line_gap: 0.0, } } } @@ -189,6 +199,21 @@ impl Default for AreaOptions { impl AreaOptions { /// The most rows, and the most columns, area type can have. pub const MAX_ROWS_COLUMNS: usize = 100; + /// Block's word gap range (percent of a word space), the Justification word spacing range. + pub const WORD_GAP: (f64, f64) = (0.0, 1000.0); + /// Block's word gap new type starts with: the font's own word space. + pub const DEFAULT_WORD_GAP: f64 = 100.0; + /// Block's line gap range in points. + pub const LINE_GAP: (f64, f64) = (-1296.0, 1296.0); + fn is_default_word_gap(v: &f64) -> bool { + *v == Self::DEFAULT_WORD_GAP + } + /// Block's gaps kept within their ranges; a gap that is not a number gives its default. + pub fn block_gaps(&self) -> (f64, f64) { + let word = if self.word_gap.is_finite() { self.word_gap.clamp(Self::WORD_GAP.0, Self::WORD_GAP.1) } else { Self::DEFAULT_WORD_GAP }; + let line = if self.line_gap.is_finite() { self.line_gap.clamp(Self::LINE_GAP.0, Self::LINE_GAP.1) } else { 0.0 }; + (word, line) + } } /// [`AreaOptions::rows`] or [`AreaOptions::columns`], read as a `u64` and clamped to diff --git a/crates/engine/src/cmd/create.rs b/crates/engine/src/cmd/create.rs index 973c82af53..f265c3ff3d 100644 --- a/crates/engine/src/cmd/create.rs +++ b/crates/engine/src/cmd/create.rs @@ -109,7 +109,7 @@ pub fn specs() -> Vec { "Create Text", [], None, - "{x, y, text, rotation?: deg clockwise about x, y (0: level), vertical?: bool = false, size?: pt, font?: family, style? (default Regular, or the family's closest style when it has no Regular), color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), area?: {width, height, fit?: none|autoHeight|shrinkText, fitMinPercent?}, placeholder?: bool (fill it with placeholder text instead, as the Type tools do with prefs placeholderText), justify?: \"auto\" (default: the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\" (point type: aligned on x, so \"center\" centres each line on the point and \"right\" ends it there; text.setStyle changes it later), leadingModel?: \"romanBaseline\"|\"emBoxTop\", charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (default: emBoxTop and emBoxCenter while the interface is in Japanese, else romanBaseline)} → {id, bounds: {x, y, width, height} (the new type's box as document.inspect reports it, after justify), overflow?: [id] (area type whose text doesn't fit its frame: the lines past it aren't drawn; left out when it fits), warning?: text (the font or style given isn't available: the type is drawn in the fallback font or the family's closest style)}; new area type gets Auto Size (fit autoHeight) when the autoSizeAreaType preference is on", + "{x, y, text, rotation?: deg clockwise about x, y (0: level), vertical?: bool = false, size?: pt, font?: family, style? (default Regular, or the family's closest style when it has no Regular), color? (#rrggbbaa and #rgba are refused), keepModel?: bool (as paint.setFill), area?: {width, height, fit?: none|autoHeight|shrinkText|block, fitMinPercent?, wordGap?, lineGap? (as text.areaOptions)}, placeholder?: bool (fill it with placeholder text instead, as the Type tools do with prefs placeholderText), justify?: \"auto\" (default: the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\" (point type: aligned on x, so \"center\" centres each line on the point and \"right\" ends it there; text.setStyle changes it later), leadingModel?: \"romanBaseline\"|\"emBoxTop\", charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (default: emBoxTop and emBoxCenter while the interface is in Japanese, else romanBaseline)} → {id, bounds: {x, y, width, height} (the new type's box as document.inspect reports it, after justify), overflow?: [id] (area type whose text doesn't fit its frame: the lines past it aren't drawn; left out when it fits), warning?: text (the font or style given isn't available: the type is drawn in the fallback font or the family's closest style)}; new area type gets Auto Size (fit autoHeight) when the autoSizeAreaType preference is on", has_doc, text_create ), @@ -752,7 +752,7 @@ fn text_create(s: &mut Session, p: &Value) -> Result { let w = f64_or(a, "width", 200.0); let h = f64_or(a, "height", 100.0); t.kind = vectorcraft_doc::TextKind::Area { frame: shapes::rectangle(Rect::new(0.0, 0.0, w, h)) }; - t.area.fit = new_area_fit(s, a, "text.create")?; + new_area_fit(s, a, "text.create", &mut t)?; } t.system_layout = s.doc()?.doc.setup.system_layout; if bool_or(p, "placeholder", false) { @@ -827,11 +827,16 @@ pub(crate) fn new_type_alignment(s: &mut Session, p: &Value, cmd: &str, t: &mut Ok(()) } -/// The fit new area type gets: `fit`/`fitMinPercent` from `p` (as `text.areaOptions` takes -/// them), else Auto Size when the "Auto Size New Area Type" preference is on. -pub(crate) fn new_area_fit(s: &Session, p: &Value, c: &str) -> Result { +/// The fit new area type `t` gets: `fit`/`fitMinPercent` from `p` (as `text.areaOptions` takes +/// them, `block` turning Dynamic Text on), else Auto Size when the "Auto Size New Area Type" +/// preference is on; and Block's `wordGap` and `lineGap`. +pub(crate) fn new_area_fit(s: &Session, p: &Value, c: &str, t: &mut TextObject) -> Result<()> { let default = if s.prefs.auto_size_area_type { vectorcraft_doc::AreaFit::AutoHeight } else { vectorcraft_doc::AreaFit::None }; - Ok(super::typecmd::fit_param(p, default, c)?.unwrap_or(default)) + let (word_gap, line_gap) = super::typecmd::block_gaps(p, c)?; + (t.area.fit, t.dynamic_text) = super::typecmd::fit_param(p, default, false, c)?.unwrap_or((default, false)); + t.area.word_gap = word_gap.unwrap_or(t.area.word_gap); + t.area.line_gap = line_gap.unwrap_or(t.area.line_gap); + Ok(()) } /// The character style new type gets: `size`, `font`, `style` and `color` from `p` (an RGB diff --git a/crates/engine/src/cmd/textedit.rs b/crates/engine/src/cmd/textedit.rs index 21ed6d8023..00f1dd8adb 100644 --- a/crates/engine/src/cmd/textedit.rs +++ b/crates/engine/src/cmd/textedit.rs @@ -85,7 +85,7 @@ pub fn specs() -> Vec { "Area / Path Type", [], None, - "{path: id, mode: \"area\"|\"onPath\", text?: \"\", vertical?: bool = false, at?: [x, y] (on-path start: nearest point), size?, font?, style?, color?, keepModel? (as text.create), fit?: none|autoHeight|shrinkText, fitMinPercent? (area: as text.areaOptions; default autoHeight when the autoSizeAreaType preference is on), placeholder?: bool (placeholder text instead, as text.create), justify?, leadingModel?, charAlign? (as text.create)} turn a path into an area-type frame or a type-on-a-path baseline (the path's paint is dropped) → {id, bounds: {x, y, width, height} (as text.create), overflow?: [id] (the text doesn't fit; left out when it fits)}", + "{path: id, mode: \"area\"|\"onPath\", text?: \"\", vertical?: bool = false, at?: [x, y] (on-path start: nearest point), size?, font?, style?, color?, keepModel? (as text.create), fit?: none|autoHeight|shrinkText|block, fitMinPercent?, wordGap?, lineGap? (area: as text.areaOptions; default autoHeight when the autoSizeAreaType preference is on), placeholder?: bool (placeholder text instead, as text.create), justify?, leadingModel?, charAlign? (as text.create)} turn a path into an area-type frame or a type-on-a-path baseline (the path's paint is dropped) → {id, bounds: {x, y, width, height} (as text.create), overflow?: [id] (the text doesn't fit; left out when it fits)}", has_doc, create_in_path ), @@ -1637,7 +1637,7 @@ fn create_in_path(s: &mut Session, p: &Value) -> Result { }; super::create::new_type_alignment(s, p, C, &mut t)?; if !on_path { - t.area.fit = super::create::new_area_fit(s, p, C)?; + super::create::new_area_fit(s, p, C, &mut t)?; } t.system_layout = s.doc()?.doc.setup.system_layout; if bool_or(p, "placeholder", false) { diff --git a/crates/engine/src/cmd/typecmd.rs b/crates/engine/src/cmd/typecmd.rs index 6d29550fa0..33dad39d93 100644 --- a/crates/engine/src/cmd/typecmd.rs +++ b/crates/engine/src/cmd/typecmd.rs @@ -93,7 +93,7 @@ pub fn specs() -> Vec { "Area Type Options…", ["Type"], None, - "{ids?|id?, width?: pt, height?: pt, rows?, columns?, gutter?: pt (between rows and columns), rowGutter?: pt|null (between rows when it differs from gutter, which is then between columns; gutter given alone sets both; the reply gives the rows' gutter either way), inset?: pt, firstBaseline?: ascent|capHeight|xHeight|leading|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, fitMinPercent?: 10..100, …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 (none given: query) → the first object's options, plus 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|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)", has_selection, area_options ), @@ -304,11 +304,13 @@ fn ruby(s: &mut Session, p: &Value) -> Result { /// Recompute the layout caches (bounds and baselines) after a text edit. Every engine text edit ends here (typing /// through `text.editRange` too), inside its `Session::edit`, so this is where Auto Size area type -/// ([`vectorcraft_doc::AreaFit::AutoHeight`]) fits its frame to the text: part of the same undo -/// step as the edit. +/// ([`vectorcraft_doc::AreaFit::AutoHeight`]) fits its frame to the text, and Dynamic Text's Block +/// (`dynamic_text` on area type, [`block::block_fit`]) sizes each line to the frame: part of the +/// same undo step as the edit. pub(crate) fn refresh_bounds(t: &mut TextObject) { // Edits that changed the paragraph count keep one paragraph style per paragraph. t.normalize_paras(); + block::block_fit(t); auto_height(t); let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t); t.cached_bounds = Some(lay.bounds); @@ -320,6 +322,7 @@ pub(crate) fn refresh_bounds(t: &mut TextObject) { /// ([`vectorcraft_text::take_kept_layout`]) instead of laying the object out again. pub(crate) fn refresh_bounds_for_first_frame(t: &mut TextObject) { t.normalize_paras(); + block::block_fit(t); auto_height(t); let stamp = vectorcraft_text::LayoutStamp::now(); let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t); @@ -1026,7 +1029,7 @@ pub(crate) fn reshape_area_with(t: &mut TextObject, f: impl FnOnce(&mut TextObje } /// Area type's text, if `n` is area type. -fn area_text(n: Option<&Node>) -> Option<&TextObject> { +pub(crate) fn area_text(n: Option<&Node>) -> Option<&TextObject> { match n.map(|n| &n.kind) { Some(NodeKind::Text(t)) if matches!(t.kind, vectorcraft_doc::TextKind::Area { .. }) => Some(t), _ => None, @@ -1059,10 +1062,15 @@ fn size_area(t: &mut TextObject, w: Option, h: Option) -> bool { reshape_area_with(t, |t| t.transform_area(a)) } -/// The fit `p` asks for (`fit`: none|autoHeight|shrinkText or `{"shrinkText": {"minPercent"}}`, -/// `fitMinPercent`), starting from `cur`. None when `p` sets neither (or only `fitMinPercent` -/// while the fit isn't Shrink Text). -pub(crate) fn fit_param(p: &Value, cur: AreaFit, c: &str) -> Result> { +/// A fit `p` asks for: the Area Type Options fit, and whether Dynamic Text's Block +/// ([`TextObject::dynamic_text`]) is on. Block's fit is [`AreaFit::None`]: it replaces Auto Size +/// and Shrink Text to Fit. +pub(crate) type FitChoice = (AreaFit, bool); + +/// The fit `p` asks for (`fit`: none|autoHeight|shrinkText|block or `{"shrinkText": {"minPercent"}}`, +/// `fitMinPercent`), starting from `cur` (`block`: Block is on). None when `p` sets neither (or only +/// `fitMinPercent` while the fit isn't Shrink Text). +pub(crate) fn fit_param(p: &Value, cur: AreaFit, block: bool, c: &str) -> Result> { check_numbers(p, &["fitMinPercent"], c)?; let min = p.get("fitMinPercent").and_then(Value::as_f64); let cur_min = match cur { @@ -1071,21 +1079,48 @@ pub(crate) fn fit_param(p: &Value, cur: AreaFit, c: &str) -> Result match (cur, min) { - (AreaFit::ShrinkText { .. }, Some(m)) => AreaFit::ShrinkText { min_percent: m }, + (AreaFit::ShrinkText { .. }, Some(m)) if !block => AreaFit::ShrinkText { min_percent: m }, _ => return Ok(None), }, + Some(Value::String(id)) if is_block_id(id) => return Ok(Some((AreaFit::None, true))), Some(Value::String(id)) => { - AreaFit::parse(id, min.or(cur_min)).ok_or_else(|| bad(c, format!("fit must be none|autoHeight|shrinkText, got {id}")))? + AreaFit::parse(id, min.or(cur_min)).ok_or_else(|| bad(c, format!("fit must be none|autoHeight|shrinkText|block, got {id}")))? } Some(v) => match serde_json::from_value::(v.clone()).map_err(|e| bad(c, format!("bad fit: {e}")))? { AreaFit::ShrinkText { min_percent } => AreaFit::ShrinkText { min_percent: min.unwrap_or(min_percent) }, f => f, }, }; - Ok(Some(match fit { - AreaFit::ShrinkText { min_percent } => AreaFit::ShrinkText { min_percent: AreaFit::clamp_percent(min_percent) }, - f => f, - })) + Ok(Some(( + match fit { + AreaFit::ShrinkText { min_percent } => AreaFit::ShrinkText { min_percent: AreaFit::clamp_percent(min_percent) }, + f => f, + }, + false, + ))) +} + +/// Whether a `fit` id names Dynamic Text's Block (case, spaces, dashes and underscores ignored). +fn is_block_id(id: &str) -> bool { + matches!(id.to_ascii_lowercase().replace([' ', '-', '_'], "").as_str(), "block" | "dynamictext") +} + +/// The `fit` id area type reports: `block` while Dynamic Text's Block is on, else its fit's. +pub(crate) fn fit_id(t: &TextObject) -> &'static str { + if t.dynamic_text { "block" } else { t.area.fit.id() } +} + +/// Dynamic Text's Block gaps `p` gives: `wordGap` (% of a word space, 0..1000) and `lineGap` (pt, +/// -1296..1296). A value that is not a number, or is outside its range, is an error. +pub(crate) fn block_gaps(p: &Value, c: &str) -> Result<(Option, Option)> { + let gap = |key: &str, (lo, hi): (f64, f64)| -> Result> { + match number_given(p, key, c)? { + Some(v) if !(v.is_finite() && (lo..=hi).contains(&v)) => Err(bad(c, format!("`{key}` must be from {lo} to {hi}, not {v}"))), + v => Ok(v), + } + }; + use vectorcraft_doc::AreaOptions as O; + Ok((gap("wordGap", O::WORD_GAP)?, gap("lineGap", O::LINE_GAP)?)) } /// Area type's options as `text.areaOptions` reports them: the Area Type Options with `fit` as @@ -1095,7 +1130,7 @@ pub(crate) fn area_options_json(t: &TextObject) -> Result { let mut v = serde_json::to_value(&t.area).map_err(|e| EngineError::Other(e.to_string()))?; let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t); if let Some(o) = v.as_object_mut() { - o.insert("fit".into(), json!(t.area.fit.id())); + o.insert("fit".into(), json!(fit_id(t))); o.insert("flow".into(), json!(t.area.flow)); // The gutter between rows, the gutter's when the rows have none of their own. o.insert("rowGutter".into(), json!(t.area.row_gutter.unwrap_or(t.area.gutter))); @@ -1104,6 +1139,9 @@ pub(crate) fn area_options_json(t: &TextObject) -> Result { _ => AreaFit::DEFAULT_MIN_PERCENT, }; o.insert("fitMinPercent".into(), json!(min)); + let (word_gap, line_gap) = t.area.block_gaps(); + o.insert("wordGap".into(), json!(word_gap)); + o.insert("lineGap".into(), json!(line_gap)); if let Some((w, h, _)) = area_size(t) { o.insert("width".into(), json!(w)); o.insert("height".into(), json!(h)); @@ -1132,8 +1170,9 @@ fn area_options(s: &mut Session, p: &Value) -> Result { // Checked once up front (its errors don't depend on the frame); each frame resolves `fit` // against its own setting below. let cur = area_text(s.doc()?.doc.node(first)).map(|t| t.area.clone()).unwrap_or_default(); - fit_param(p, cur.fit, C)?; - let fit_given = p.get("fit").is_some_and(|v| !v.is_null()) || p.get("fitMinPercent").is_some_and(|v| !v.is_null()); + fit_param(p, cur.fit, false, C)?; + let (word_gap, line_gap) = block_gaps(p, C)?; + let fit_given = ["fit", "fitMinPercent", "wordGap", "lineGap"].iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null())); let size = |k: &str| p.get(k).and_then(Value::as_f64).filter(|x| x.is_finite()).map(|x| x.clamp(1.0, 100_000.0)); let (w, h) = (size("width"), size("height")); let given: Vec<(&String, &Value)> = p.as_object().into_iter().flatten().filter(|(k, _)| AREA_KEYS.contains(&k.as_str())).collect(); @@ -1142,7 +1181,7 @@ fn area_options(s: &mut Session, p: &Value) -> Result { } // Each area type takes the options given over its own (#3759): setting one option on several // frames leaves their other options as they were. - let merged = |own: &vectorcraft_doc::AreaOptions| -> Result { + let merged = |own: &vectorcraft_doc::AreaOptions, block: bool| -> Result<(vectorcraft_doc::AreaOptions, bool)> { let mut v = serde_json::to_value(own).map_err(|e| EngineError::Other(e.to_string()))?; if let Some(o) = v.as_object_mut() { for (k, val) in &given { @@ -1162,17 +1201,29 @@ fn area_options(s: &mut Session, p: &Value) -> Result { opts.inset = finite(opts.inset).clamp(0.0, 10_000.0); opts.first_baseline_min = finite(opts.first_baseline_min).clamp(0.0, 10_000.0); // Each frame's fit from its own (`fitMinPercent` alone changes only Shrink Text frames). - opts.fit = fit_param(p, own.fit, C)?.unwrap_or(own.fit); - Ok(opts) + let (fit, block) = fit_param(p, own.fit, block, C)?.unwrap_or((own.fit, block)); + opts.fit = fit; + opts.word_gap = word_gap.unwrap_or(own.word_gap); + opts.line_gap = line_gap.unwrap_or(own.line_gap); + Ok((opts, block)) }; let d = &s.doc()?.doc; - let planned: Vec<(NodeId, vectorcraft_doc::AreaOptions)> = ids + let planned: Vec<(NodeId, (vectorcraft_doc::AreaOptions, bool))> = ids .iter() - .filter_map(|id| area_text(d.node(*id)).map(|t| (*id, &t.area))) - .map(|(id, own)| merged(own).map(|o| (id, o))) + .filter_map(|id| area_text(d.node(*id)).map(|t| (*id, t))) + .map(|(id, t)| merged(&t.area, t.dynamic_text).map(|o| (id, o))) .collect::>()?; - let apply = |t: &mut TextObject, opts: &vectorcraft_doc::AreaOptions| { + // Dynamic Text's Block is refused for threaded frames, as `type.dynamicText` refuses it. + let frames: Vec = + planned.iter().filter(|(id, (_, block))| *block && !super::threads::story_of(d, *id).is_empty()).map(|(id, _)| id.0.to_string()).collect(); + if !frames.is_empty() { + let frames = frames.join(", "); + return Err(bad(C, format!("area type in a thread cannot use Dynamic Text: {frames}"))); + } + let apply = |t: &mut TextObject, (opts, block): &(vectorcraft_doc::AreaOptions, bool)| { t.area = opts.clone(); + // Block off keeps the sizes it wrote into the characters. + t.dynamic_text = *block; // Auto Size sets the height (Illustrator's dialog turns the Height field off). let h = if opts.fit == AreaFit::AutoHeight { None } else { h }; // A resized frame has laid its text out again; otherwise the new options do here. @@ -1313,6 +1364,9 @@ fn set_path_handle(s: &mut Session, p: &Value) -> Result { #[cfg(test)] mod area_tests; +mod block; +#[cfg(test)] +mod block_tests; /// Width of the first line and of the space it can fill, with `tracking` on the first paragraph. /// The third value is where the first line ends in the plain text. diff --git a/crates/engine/src/cmd/typecmd/block.rs b/crates/engine/src/cmd/typecmd/block.rs new file mode 100644 index 0000000000..a78f5254cb --- /dev/null +++ b/crates/engine/src/cmd/typecmd/block.rs @@ -0,0 +1,309 @@ +//! Dynamic Text's Block for area type ([`TextObject::dynamic_text`] on area type): each line as +//! typed is set to the frame's width by changing its font size, after every edit +//! ([`super::refresh_bounds`]). + +use vectorcraft_doc::{TextKind, TextObject, TextRun}; + +/// The font size range a line's first character is fitted within, in document points (the +/// Character panel's). +const SIZES: (f64, f64) = (0.1, 1296.0); + +/// Most area layouts a refit runs to correct lines that still wrap after the first fit. +pub(crate) const BLOCK_PASSES: usize = 4; + +/// One line as typed: `start..content` is its text, `content..end` the `\n` or U+2028 that ends it +/// (empty for the last line). `para` is the index of its paragraph, and `para_start` whether it +/// starts that paragraph. +#[derive(Clone, Copy, Debug)] +struct TypedLine { + start: usize, + content: usize, + end: usize, + para: usize, + para_start: bool, +} + +/// The lines as typed: the text split after each `\n` and U+2028. +fn typed_lines(text: &str) -> Vec { + let mut out = vec![]; + let (mut start, mut para, mut para_start) = (0, 0, true); + for (i, c) in text.char_indices() { + if c == '\n' || c == '\u{2028}' { + let end = i + c.len_utf8(); + out.push(TypedLine { start, content: i, end, para, para_start }); + start = end; + para_start = c == '\n'; + if c == '\n' { + para += 1; + } + } + } + out.push(TypedLine { start, content: text.len(), end: text.len(), para, para_start }); + out +} + +/// The stored size of the character at `byte` (the run that holds it, not the one before it). +pub(crate) fn size_at(runs: &[TextRun], byte: usize) -> f64 { + let mut off = 0; + for r in runs { + let end = off + r.text.len(); + if (off..end).contains(&byte) { + return r.style.size; + } + off = end; + } + vectorcraft_text::edit::style_at(runs, byte).size +} + +/// The stored size of each line's first character, in one pass over the runs. +fn first_sizes(runs: &[TextRun], lines: &[TypedLine]) -> Vec { + let mut out = Vec::with_capacity(lines.len()); + let (mut ri, mut off) = (0, 0); + for l in lines { + while let Some(r) = runs.get(ri) { + if l.start < off + r.text.len() { + break; + } + off += r.text.len(); + ri += 1; + } + out.push(runs.get(ri).map_or_else(|| size_at(runs, l.start), |r| r.style.size)); + } + out +} + +/// Each line's content width (trailing spaces left out) by its first byte, with `t` laid out as +/// point type, where no line wraps. +fn line_widths(db: &vectorcraft_text::FontDb, t: &TextObject) -> std::collections::HashMap { + let mut probe = t.clone(); + probe.kind = TextKind::Point; + let laid = vectorcraft_text::layout(db, &probe); + let mut out = std::collections::HashMap::with_capacity(laid.lines.len()); + for m in &laid.lines { + out.entry(m.start).or_insert(m.x1 - m.x0); + } + out +} + +/// The size a line set at `size` points and `width` wide takes to fill `avail`, its width growing +/// by `slope` a point of size (`width / size` when the whole line follows its size): rounded down +/// to tenths and kept within [`SIZES`]. A line that fits and would not fit a tenth larger keeps its +/// size rounded down to tenths, and None when that is its size, so fitting again changes nothing. +/// Room taken entirely by indents gives the smallest size. +fn refit(size: f64, width: f64, avail: f64, slope: f64) -> Option { + if width <= avail + 1e-6 && width + 0.1 * slope > avail { + let rounded = tenths(size); + return ((rounded - size).abs() > 1e-9).then_some(rounded); + } + Some(tenths(size + (avail.max(0.0) - width) / slope)) +} + +/// A size in document points rounded down to a whole number of tenths and kept within [`SIZES`]. +fn tenths(points: f64) -> f64 { + ((points * 10.0 + 1e-6).floor() / 10.0).clamp(SIZES.0, SIZES.1) +} + +/// Fit area type with Dynamic Text (Block) on: every paragraph's Desired word spacing becomes the word gap, +/// then each line as typed gets the size (its first character's, in steps of 0.1 pt within 0.1 to +/// 1,296 pt, the line's other characters keeping their proportions to it) at which its width +/// equals the frame's width less the inset, the gutters and the paragraph's indents, and each +/// character's leading is its size plus the line gap. An empty line or one of only spaces keeps +/// its size. Nothing changes when the frame has no width along the lines or the type's transform +/// has no size. A line that still wraps at its first fit is made smaller, in at most +/// [`BLOCK_PASSES`] more layouts. True when the text changed. +pub(crate) fn block_fit(t: &mut TextObject) -> bool { + if !t.dynamic_text { + return false; + } + let TextKind::Area { frame } = &t.kind else { return false }; + let (word_gap, line_gap) = t.area.block_gaps(); + let Some(b) = frame.bounds().filter(|b| [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite())) else { return false }; + let Some(points) = t.style_scale().map(|s| s.points).filter(|p| p.is_finite() && *p > 1e-12) else { return false }; + let before = (t.runs.clone(), t.para.clone(), t.paras.clone()); + + // The word gap first: it changes the lines' widths. + let mut paras = t.paragraph_styles(); + for p in &mut paras { + let [min, _, max] = p.justification.word_spacing; + p.justification.word_spacing = [min.min(word_gap), word_gap, max.max(word_gap)]; + } + if paras != t.paragraph_styles() { + t.set_paragraph_styles(paras); + } + + // The room along a line in one cell of the frame, before indents. + let a = &t.area; + let (along, cells, gutter) = if t.vertical { (b.height(), a.rows, a.row_gutter.unwrap_or(a.gutter)) } else { (b.width(), a.columns, a.gutter) }; + let cells = cells.max(1) as f64; + let cell = (along - 2.0 * a.inset.max(0.0) - gutter.max(0.0) * (cells - 1.0)) / cells; + if !(cell.is_finite() && cell > 1e-9) { + return (t.runs.clone(), t.para.clone(), t.paras.clone()) != before; + } + + let db = vectorcraft_text::FontDb::global(); + let text = t.plain_text(); + let lines = typed_lines(&text); + let widths = line_widths(db, t); + let sizes = first_sizes(&t.runs, &lines); + // Per line: (factor applied to its sizes, the room it fills, the last size measured and its + // width), or None to keep its size. + let mut fits: Vec> = lines + .iter() + .zip(&sizes) + .map(|(l, size)| { + if l.content == l.start { + return None; + } + let width = widths.get(&l.start).copied().filter(|w| w.is_finite() && *w > 1e-9)?; + let para = t.para_at(l.para); + let first = if l.para_start { para.first_line_indent } else { 0.0 }; + let avail = cell - para.left_indent - para.right_indent - first; + let size = size * points; + if !(size.is_finite() && size > 0.0) { + return None; + } + Some((refit(size, width, avail, width / size).map_or(1.0, |n| n / size), avail, size, width)) + }) + .collect(); + + let gap = line_gap / points; + let min_leading = SIZES.0 / points; + // Always from the sizes the refit started with, so each pass sets a line's size once: the runs + // are split where the lines end and each piece scaled by its line's factor, in one pass. + let apply = |t: &mut TextObject, from: &[TextRun], fits: &[Option<(f64, f64, f64, f64)>]| { + let mut out = Vec::with_capacity(from.len() + lines.len()); + let (mut off, mut li) = (0, 0); + for r in from { + let end = off + r.text.len(); + let mut at = off; + loop { + while lines.get(li).is_some_and(|l| l.end <= at && li + 1 < lines.len()) { + li += 1; + } + let stop = lines.get(li).map_or(end, |l| l.end.clamp(at, end)); + let stop = if stop == at { end } else { stop }; + let f = fits.get(li).copied().flatten().map_or(1.0, |(f, ..)| f); + let mut piece = TextRun { text: r.text.get(at - off..stop - off).unwrap_or_default().to_string(), ..r.clone() }; + if at > off { + piece.style.glyph_alternate = None; + } + let st = &mut piece.style; + st.size *= f; + st.baseline_shift *= f; + st.tcy_up_down *= f; + st.tcy_left_right *= f; + st.leading = Some((st.size + gap).max(min_leading)); + if let Some(art) = &mut piece.inline { + art.baseline_shift *= f; + } + out.push(piece); + at = stop; + if at >= end { + break; + } + } + off = end; + } + vectorcraft_text::edit::normalize(&mut out); + t.runs = out; + }; + let start = t.runs.clone(); + apply(t, &start, &fits); + + // Each pass measures the lines again: a line whose width did not follow its size (a tab to a + // fixed stop) is fitted again from its measured width, and when every line measures right, a + // line the frame's shape or a list marker still wraps is made smaller, by what the line the + // layout gave it holds. + // Per line: the smallest size measured too wide, which a later pass never goes back to. + let mut too_wide = vec![f64::INFINITY; lines.len()]; + for _ in 0..BLOCK_PASSES { + let now_widths = line_widths(db, t); + let mut again = false; + for (((l, fit), size), wide) in lines.iter().zip(fits.iter_mut()).zip(&sizes).zip(too_wide.iter_mut()) { + let Some((f, avail, last_size, last_width)) = fit else { continue }; + let size = size * points; + let now = size * *f; + let Some(width) = now_widths.get(&l.start).copied().filter(|w| w.is_finite() && *w > 1e-9) else { continue }; + if width > *avail + 1e-6 { + *wide = wide.min(now); + } + // The slope between the last two sizes measured, where they differ: a line whose width + // has a part that stays as the size changes is fitted in one step. + let slope = Some((width - *last_width) / (now - *last_size)) + .filter(|s| (now - *last_size).abs() > 1e-9 && s.is_finite() && *s > 1e-9) + .unwrap_or(width / now); + (*last_size, *last_width) = (now, width); + let next = refit(now, width, *avail, slope).map(|n| if n >= *wide - 1e-9 { tenths(*wide - 0.1) } else { n }); + if let Some(next) = next.filter(|n| (n - now).abs() > 1e-9) { + *f = next / size; + again = true; + } + } + if !again { + let laid = vectorcraft_text::layout(db, t); + // Per typed line: how many laid-out lines it took, and the room of its first. + let mut parts: Vec<(usize, f64)> = vec![(0, 0.0); lines.len()]; + for m in &laid.lines { + let i = lines.partition_point(|l| l.start <= m.start).saturating_sub(1); + if let Some(p) = parts.get_mut(i) { + if p.0 == 0 { + p.1 = m.avail.1 - m.avail.0; + } + p.0 += 1; + } + } + for (((l, fit), (count, room)), size) in lines.iter().zip(fits.iter_mut()).zip(&parts).zip(&sizes) { + let Some((f, ..)) = fit else { continue }; + if *count < 2 { + continue; + } + let size = size * points; + let now = size * *f; + if now <= SIZES.0 + 1e-9 { + continue; + } + let width = now_widths.get(&l.start).copied().unwrap_or(f64::INFINITY); + let smaller = if room.is_finite() && *room > 0.0 && *room < width { tenths(now * room / width) } else { now }; + *f = smaller.min(tenths(now - 0.1)) / size; + again = true; + } + } + if !again { + break; + } + apply(t, &start, &fits); + } + (t.runs.clone(), t.para.clone(), t.paras.clone()) != before +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn typed_lines_split_after_returns_and_forced_breaks() { + let l = typed_lines("ab\ncd\u{2028}e\n"); + let spans: Vec<_> = l.iter().map(|l| (l.start, l.content, l.end, l.para, l.para_start)).collect(); + assert_eq!(spans, vec![(0, 2, 3, 0, true), (3, 5, 8, 1, true), (8, 9, 10, 1, false), (10, 10, 10, 2, true)]); + assert_eq!(typed_lines("").len(), 1); + } + + #[test] + fn a_fitting_line_keeps_its_size_in_tenths() { + // 100 pt wide at 12 pt, 100.5 pt of room: a tenth larger would not fit. + assert_eq!(refit(12.0, 100.0, 100.5, 100.0 / 12.0), None); + assert_eq!(refit(12.34, 100.0, 100.5, 100.0 / 12.34), Some(12.3), "a size between tenths is rounded down"); + // Room for twice the width: twice the size. + assert_eq!(refit(12.0, 100.0, 200.0, 100.0 / 12.0), Some(24.0)); + // A part of the width that stays (a slope below width / size) needs more size. + assert_eq!(refit(12.0, 100.0, 150.0, 5.0), Some(22.0)); + } + + #[test] + fn sizes_round_down_to_tenths_within_the_range() { + assert_eq!(tenths(23.99), 23.9); + assert_eq!(tenths(24.0 - 1e-9), 24.0); + assert_eq!(tenths(0.01), 0.1); + assert_eq!(tenths(5000.0), 1296.0); + } +} diff --git a/crates/engine/src/cmd/typecmd/block_tests.rs b/crates/engine/src/cmd/typecmd/block_tests.rs new file mode 100644 index 0000000000..1028fc0017 --- /dev/null +++ b/crates/engine/src/cmd/typecmd/block_tests.rs @@ -0,0 +1,385 @@ +//! Dynamic Text's Block for area type: `type.dynamicText`, Area Type Options › Block and the refit +//! after edits. + +use serde_json::{Value, json}; +use vectorcraft_doc::{AreaFit, NodeId, NodeKind, TextKind, TextObject}; + +use crate::Session; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 800, "height": 600})).unwrap(); + s +} + +fn area(s: &mut Session, w: f64, h: f64, text: &str) -> u64 { + let id = s.execute("text.create", &json!({"x": 40, "y": 40, "size": 12, "area": {"width": w, "height": h}, "text": text})).unwrap()["id"] + .as_u64() + .unwrap(); + s.execute("select.set", &json!({"ids": [id]})).unwrap(); + id +} + +fn text(s: &Session, id: u64) -> TextObject { + match &s.doc().unwrap().doc.node(NodeId(id)).unwrap().kind { + NodeKind::Text(t) => (**t).clone(), + k => panic!("not text: {k:?}"), + } +} + +fn undo_len(s: &Session) -> usize { + s.doc().unwrap().history.undo.len() +} + +/// The size of the character at `byte`. +fn size_at(t: &TextObject, byte: usize) -> f64 { + super::block::size_at(&t.runs, byte) +} + +/// Each laid-out line's (start byte, content width, room): the room is the frame's span less the +/// indents. +fn lines(t: &TextObject) -> Vec<(usize, f64, f64)> { + let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t); + lay.lines.iter().map(|l| (l.start, l.x1 - l.x0, l.avail.1 - l.avail.0)).collect() +} + +/// Every typed line is one laid-out line whose width is within one 0.1 pt size step of its room. +fn assert_block(t: &TextObject) { + let typed: Vec = std::iter::once(0).chain(t.plain_text().match_indices(['\n', '\u{2028}']).map(|(i, c)| i + c.len())).collect(); + let laid = lines(t); + assert_eq!(laid.iter().map(|l| l.0).collect::>(), typed, "one laid-out line per typed line: {laid:?}"); + for &(start, width, room) in &laid { + let size = size_at(t, start); + if width <= 1e-9 || size >= 1296.0 - 1e-9 || size <= 0.1 + 1e-9 { + continue; + } + assert!(width <= room + 0.01, "line at {start} is wider than its room: {width} > {room}"); + assert!(width >= room * (size - 0.1) / size - 0.01, "line at {start} at {size} pt is short of its room: {width} < {room}"); + } +} + +#[test] +fn block_sets_each_typed_line_to_the_frame_width_by_its_size() { + let mut s = session(); + let id = area(&mut s, 300.0, 400.0, "BIG\na much longer second line\nmid one"); + let n = undo_len(&s); + let r = s.execute("type.dynamicText", &json!({})).unwrap(); + assert_eq!(r, json!({"on": true, "ids": [id], "fitScale": 1.0, "wordGap": 100.0, "lineGap": 0.0})); + assert_eq!(undo_len(&s), n + 1, "one undo step"); + let t = text(&s, id); + assert!(t.dynamic_text); + assert_eq!(t.area.fit, AreaFit::None); + assert_block(&t); + let (big, long, mid) = (size_at(&t, 0), size_at(&t, 4), size_at(&t, 31)); + assert!(big > mid && mid > long, "a shorter line is set larger: {big} {mid} {long}"); + for size in [big, long, mid] { + assert!(((size * 10.0).round() - size * 10.0).abs() < 1e-6, "{size} is a whole number of tenths"); + } + // Each character's leading is its size (line gap 0). + assert!(t.runs.iter().all(|r| r.style.leading == Some(r.style.size)), "{:?}", t.runs); + // Inspect reports it. + let doc = s.execute("document.inspect", &json!({})).unwrap(); + let node = doc["layers"][0]["children"].as_array().unwrap().iter().find(|k| k["id"] == id).unwrap().clone(); + assert_eq!((node["dynamicText"].as_bool(), node["fit"].as_str()), (Some(true), Some("block"))); +} + +#[test] +fn block_keeps_the_proportions_inside_a_line_and_fits_again_after_edits() { + let mut s = session(); + let id = area(&mut s, 300.0, 400.0, "one two three\nfour"); + s.execute("text.setRangeStyle", &json!({"id": id, "start": 0, "end": 3, "size": 24})).unwrap(); + s.execute("type.dynamicText", &json!({"on": true})).unwrap(); + let t = text(&s, id); + assert_block(&t); + let ratio = size_at(&t, 0) / size_at(&t, 4); + assert!((ratio - 2.0).abs() < 0.02, "the first word stays twice the size of the rest: {ratio}"); + let four = size_at(&t, 14); + // Typing into the first line makes it smaller, in the edit's own undo step; the second line stays. + let first = size_at(&t, 4); + let n = undo_len(&s); + s.execute("text.editRange", &json!({"id": id, "start": 13, "end": 13, "insert": " and more words"})).unwrap(); + assert_eq!(undo_len(&s), n + 1); + let t = text(&s, id); + assert_block(&t); + assert!(size_at(&t, 4) < first, "{} < {first}", size_at(&t, 4)); + assert_eq!(size_at(&t, t.plain_text().find("four").unwrap()), four); + // A narrower frame sets every line smaller. + s.execute("text.areaOptions", &json!({"width": 150})).unwrap(); + let narrow = text(&s, id); + assert_block(&narrow); + let f = size_at(&narrow, narrow.plain_text().find("four").unwrap()) / four; + assert!((f - 0.5).abs() < 0.02, "half the width, half the size: {f}"); + // Undo brings the wider frame's sizes back. + s.execute("edit.undo", &json!({})).unwrap(); + assert_eq!(text(&s, id).runs, t.runs); +} + +#[test] +fn block_turns_off_keeping_its_sizes_and_records_nothing_when_nothing_changes() { + let mut s = session(); + // The tab goes to a stop that stays where it is as the size changes. + let id = area(&mut s, 300.0, 400.0, "Fit me\nand\tme too"); + s.execute("type.dynamicText", &json!({"on": true})).unwrap(); + let fitted = text(&s, id).runs; + let laid = lines(&text(&s, id)); + assert_eq!(laid.iter().map(|l| l.0).collect::>(), vec![0, 7], "{laid:?}"); + assert!(laid.iter().all(|l| l.1 <= l.2 + 0.01 && l.1 > l.2 * 0.95), "each line fills its room: {laid:?}"); + let n = undo_len(&s); + assert_eq!(s.execute("type.dynamicText", &json!({"on": true})).unwrap()["on"], true); + assert_eq!(undo_len(&s), n, "already on: no undo step"); + let r = s.execute("type.dynamicText", &json!({})).unwrap(); + assert_eq!(r["on"], false); + assert_eq!(undo_len(&s), n + 1); + let t = text(&s, id); + assert!(!t.dynamic_text); + assert_eq!(t.runs, fitted, "off keeps the sizes it was drawn at"); + // Edits no longer fit the lines. + s.execute("text.areaOptions", &json!({"width": 100})).unwrap(); + assert_eq!(text(&s, id).runs, fitted); + assert_eq!(s.execute("type.dynamicText", &json!({"on": false})).unwrap()["on"], false); + assert_eq!(undo_len(&s), n + 2, "already off: no undo step"); +} + +#[test] +fn bad_params_and_other_type_are_refused() { + let mut s = session(); + let id = area(&mut s, 300.0, 400.0, "Fit me"); + for bad in [ + json!({"on": "yes"}), + json!({"on": 1}), + json!({"wordGap": "wide"}), + json!({"wordGap": -1}), + json!({"wordGap": 1001}), + json!({"lineGap": 1297}), + json!({"lineGap": -1297}), + json!({"lineGap": true}), + ] { + assert!(s.execute("type.dynamicText", &bad).is_err(), "{bad}"); + } + assert!(!text(&s, id).dynamic_text); + let point = s.execute("text.create", &json!({"x": 10, "y": 500, "text": "point"})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [point]})).unwrap(); + let e = s.execute("type.dynamicText", &json!({})).unwrap_err().to_string(); + assert!(e.contains("select type on a path or area type"), "{e}"); + // With point type selected too, only the area type changes. + s.execute("select.set", &json!({"ids": [id, point]})).unwrap(); + let r = s.execute("type.dynamicText", &json!({})).unwrap(); + assert_eq!(r["ids"], json!([id])); + assert!(text(&s, id).dynamic_text && !text(&s, point).dynamic_text); +} + +#[test] +fn gaps_set_word_spacing_and_leading() { + let mut s = session(); + let id = area(&mut s, 300.0, 400.0, "two words\nthree more words"); + s.execute("type.dynamicText", &json!({"on": true})).unwrap(); + let plain = text(&s, id); + let r = s.execute("type.dynamicText", &json!({"wordGap": 300, "lineGap": 6})).unwrap(); + assert_eq!((r["on"].as_bool(), r["wordGap"].as_f64(), r["lineGap"].as_f64()), (Some(true), Some(300.0), Some(6.0))); + let t = text(&s, id); + assert!(t.dynamic_text); + assert_eq!((t.area.word_gap, t.area.line_gap), (300.0, 6.0)); + assert_eq!(t.para_at(0).justification.word_spacing, [80.0, 300.0, 300.0]); + assert!(t.runs.iter().all(|r| (r.style.leading.unwrap() - r.style.size - 6.0).abs() < 1e-9), "{:?}", t.runs); + assert_block(&t); + assert!(size_at(&t, 0) < size_at(&plain, 0), "wider word spaces leave the letters less room"); + // A gap alone on a frame without Block turns it on. + let other = area(&mut s, 200.0, 200.0, "x y"); + let r = s.execute("type.dynamicText", &json!({"lineGap": -2})).unwrap(); + assert_eq!(r["on"], true); + let t = text(&s, other); + assert!(t.dynamic_text); + assert_eq!((t.area.word_gap, t.area.line_gap), (100.0, -2.0)); +} + +#[test] +fn area_type_options_offer_block_with_its_gaps() { + let mut s = session(); + let id = area(&mut s, 300.0, 400.0, "Fit me\nand me too"); + let q = s.execute("text.areaOptions", &json!({})).unwrap(); + assert_eq!((q["wordGap"].as_f64(), q["lineGap"].as_f64()), (Some(100.0), Some(0.0))); + // Gaps alone are kept for Block, without turning it on or changing the text. + let (n, runs) = (undo_len(&s), text(&s, id).runs); + s.execute("text.areaOptions", &json!({"wordGap": 200})).unwrap(); + let t = text(&s, id); + assert_eq!((undo_len(&s), t.dynamic_text, t.area.word_gap), (n + 1, false, 200.0)); + assert_eq!(t.runs, runs); + let r = s.execute("text.areaOptions", &json!({"fit": "block", "lineGap": 4})).unwrap(); + assert_eq!((r["fit"].as_str(), r["wordGap"].as_f64(), r["lineGap"].as_f64()), (Some("block"), Some(200.0), Some(4.0))); + assert!(text(&s, id).dynamic_text); + assert_block(&text(&s, id)); + // The reply passed back (as the dialog does) changes nothing; naming Block again keeps the gaps. + let n = undo_len(&s); + assert_eq!(s.execute("text.areaOptions", &r).unwrap(), r); + s.execute("text.areaOptions", &json!({"fit": "block"})).unwrap(); + assert_eq!(undo_len(&s), n); + s.execute("text.areaOptions", &json!({"lineGap": 2})).unwrap(); + let t = text(&s, id); + assert_eq!((t.dynamic_text, t.area.word_gap, t.area.line_gap), (true, 200.0, 2.0)); + assert!(s.execute("text.areaOptions", &json!({"lineGap": 5000})).is_err()); + assert!(s.execute("text.areaOptions", &json!({"wordGap": 2000})).is_err()); + assert!(s.execute("text.areaOptions", &json!({"wordGap": "wide"})).is_err()); + assert!(s.execute("text.areaOptions", &json!({"fit": "squash"})).unwrap_err().to_string().contains("shrinkText|block")); + // Shrink Text to Fit replaces Block, keeping the sizes. + let runs = text(&s, id).runs; + s.execute("text.areaOptions", &json!({"fit": "shrinkText"})).unwrap(); + let t = text(&s, id); + assert!(!t.dynamic_text); + assert_eq!(t.runs, runs); + // Block replaces Shrink Text to Fit and Auto Size. + s.execute("text.areaOptions", &json!({"fit": "block"})).unwrap(); + assert_eq!(text(&s, id).area.fit, AreaFit::None); + // New area type can start with it. + let made = s + .execute( + "text.create", + &json!({"x": 10, "y": 300, "size": 12, "area": {"width": 200, "height": 200, "fit": "block", "wordGap": 150}, "text": "made"}), + ) + .unwrap()["id"] + .as_u64() + .unwrap(); + let t = text(&s, made); + assert_eq!((t.dynamic_text, t.area.word_gap, t.area.line_gap), (true, 150.0, 0.0)); + assert_block(&t); +} + +#[test] +fn block_round_trips_through_the_native_format() { + let mut s = session(); + let id = area(&mut s, 300.0, 400.0, "Fit me\nand me too"); + s.execute("type.dynamicText", &json!({"wordGap": 120, "lineGap": 3})).unwrap(); + let doc = s.doc().unwrap().doc.clone(); + let bytes = vectorcraft_format::save(&doc, false); + let back = vectorcraft_format::load(&bytes).unwrap(); + let NodeKind::Text(t) = &back.node(NodeId(id)).unwrap().kind else { panic!("text") }; + assert_eq!((t.dynamic_text, t.area.word_gap, t.area.line_gap), (true, 120.0, 3.0)); + assert_eq!(t.runs, text(&s, id).runs, "the fitted sizes are saved in the characters"); + // Saved as `dynamicText` with the gaps beside the area options; missing gaps read as their + // defaults, which are left out when saved. + let saved = serde_json::to_value(&**t).unwrap(); + assert_eq!((&saved["dynamicText"], &saved["area"]["wordGap"], &saved["area"]["lineGap"]), (&json!(true), &json!(120.0), &json!(3.0))); + let plain = serde_json::from_value::(json!({})).unwrap(); + assert_eq!((plain.word_gap, plain.line_gap), (100.0, 0.0)); + let plain: Value = serde_json::to_value(&plain).unwrap(); + assert!(plain.get("wordGap").is_none() && plain.get("lineGap").is_none(), "{plain}"); + // Turned off, it opens off with the sizes it had. + s.execute("type.dynamicText", &json!({"on": false})).unwrap(); + let back = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap(); + let NodeKind::Text(t) = &back.node(NodeId(id)).unwrap().kind else { panic!("text") }; + assert!(!t.dynamic_text); + assert_eq!(t.runs, text(&s, id).runs); +} + +#[test] +fn edge_cases_fit_without_failing() { + let mut s = session(); + // Empty text, an empty line and a line of spaces keep their sizes. + let empty = area(&mut s, 300.0, 400.0, ""); + s.execute("type.dynamicText", &json!({"on": true})).unwrap(); + assert_eq!(size_at(&text(&s, empty), 0), 12.0); + let gaps = area(&mut s, 300.0, 400.0, "top\n\n \nbottom line"); + s.execute("type.dynamicText", &json!({"on": true})).unwrap(); + let t = text(&s, gaps); + assert_eq!((size_at(&t, 4), size_at(&t, 5)), (12.0, 12.0)); + assert_block(&t); + // One word. + let word = area(&mut s, 300.0, 400.0, "Word"); + s.execute("type.dynamicText", &json!({"on": true})).unwrap(); + assert_block(&text(&s, word)); + // A wide frame stops at 1,296 pt; a very long line in a narrow frame stops at 0.1 pt and wraps. + let wide = area(&mut s, 100_000.0, 400.0, "i"); + s.execute("type.dynamicText", &json!({"on": true})).unwrap(); + assert_eq!(size_at(&text(&s, wide), 0), 1296.0); + let narrow = area(&mut s, 1.0, 400.0, &"long words ".repeat(40)); + s.execute("type.dynamicText", &json!({"on": true})).unwrap(); + let t = text(&s, narrow); + assert_eq!(size_at(&t, 0), 0.1); + assert!(vectorcraft_text::layout(vectorcraft_text::FontDb::global(), &t).overflow, "at 0.1 pt the line still does not fit"); + // A frame inset so far that it has no width keeps the sizes. + let inset = area(&mut s, 50.0, 400.0, "Inset"); + s.execute("text.areaOptions", &json!({"inset": 30})).unwrap(); + s.execute("type.dynamicText", &json!({"on": true})).unwrap(); + assert_eq!(size_at(&text(&s, inset), 0), 12.0); +} + +#[test] +fn block_fits_columns_lists_vertical_and_right_to_left_type() { + let mut s = session(); + // Two columns: each line is set to a column's width. + let cols = area(&mut s, 400.0, 600.0, "left column\nsecond"); + s.execute("text.areaOptions", &json!({"columns": 2, "gutter": 20})).unwrap(); + s.execute("type.dynamicText", &json!({"on": true})).unwrap(); + let t = text(&s, cols); + assert_block(&t); + assert!(lines(&t).iter().all(|l| (l.2 - 190.0).abs() < 1e-6), "{:?}", lines(&t)); + // A bulleted list: each item stays one line, the marker and its tab taking their room before + // the text (the room the layout reports takes in the marker's too). + let list = area(&mut s, 300.0, 400.0, "first item\nsecond item here"); + s.execute("text.setFormat", &json!({"list": "bullet"})).unwrap(); + s.execute("type.dynamicText", &json!({"on": true})).unwrap(); + let t = text(&s, list); + let laid = lines(&t); + assert_eq!(laid.iter().map(|l| l.0).collect::>(), vec![0, 11], "{laid:?}"); + assert!(laid.iter().all(|l| l.1 <= l.2), "{laid:?}"); + assert!(size_at(&t, 0) > size_at(&t, 11), "the shorter item is larger"); + // Right-to-left text. + let rtl = area(&mut s, 300.0, 400.0, "שלום עולם\nטקסט ארוך יותר בשורה"); + s.execute("type.dynamicText", &json!({"on": true})).unwrap(); + assert_block(&text(&s, rtl)); + // Vertical type: each column of text is set to the frame's height. + let v = s + .execute( + "text.create", + &json!({"x": 40, "y": 40, "size": 12, "vertical": true, "area": {"width": 300, "height": 200}, "text": "縦書き\nもっと長い縦書きの行"}), + ) + .unwrap()["id"] + .as_u64() + .unwrap(); + s.execute("select.set", &json!({"ids": [v]})).unwrap(); + s.execute("type.dynamicText", &json!({"on": true})).unwrap(); + let t = text(&s, v); + assert!(t.vertical); + assert_block(&t); + assert!(lines(&t).iter().all(|l| (l.2 - 200.0).abs() < 1e-6), "{:?}", lines(&t)); +} + +#[test] +fn threaded_frames_are_refused_and_threading_turns_block_off() { + let mut s = session(); + let a = area(&mut s, 200.0, 300.0, "Fit me\nand me too"); + s.execute("type.dynamicText", &json!({"on": true})).unwrap(); + let fitted = text(&s, a).runs; + let b = s.execute("shape.rectangle", &json!({"x": 400, "y": 40, "width": 200, "height": 300})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [a, b]})).unwrap(); + let n = undo_len(&s); + s.execute("text.thread.create", &json!({})).unwrap(); + assert_eq!(undo_len(&s), n + 1); + let t = text(&s, a); + assert!(!t.dynamic_text, "threading turns Block off"); + assert_eq!(t.runs, fitted, "the text keeps its sizes"); + s.execute("select.set", &json!({"ids": [a]})).unwrap(); + let e = s.execute("type.dynamicText", &json!({"on": true})).unwrap_err().to_string(); + assert!(e.contains("area type in a thread") && e.contains(&a.to_string()), "{e}"); + let runs = text(&s, a).runs; + let e = s.execute("text.areaOptions", &json!({"fit": "block"})).unwrap_err().to_string(); + assert!(e.contains("area type in a thread") && e.contains(&a.to_string()), "{e}"); + assert_eq!(text(&s, a).runs, runs, "Area Type Options refuses it too, changing nothing"); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(text(&s, a).dynamic_text, "undo brings it back with the thread gone"); + assert!(matches!(text(&s, a).kind, TextKind::Area { .. })); +} + +#[test] +fn long_text_fits_in_a_bounded_number_of_layouts() { + let mut s = session(); + let story: String = (0..300).map(|i| format!("line number {i} {}\n", "x".repeat(i % 17))).collect(); + let id = area(&mut s, 300.0, 100_000.0, &story); + let before = vectorcraft_text::test_fonts::layouts_on_this_thread(); + s.execute("type.dynamicText", &json!({"on": true})).unwrap(); + let used = vectorcraft_text::test_fonts::layouts_on_this_thread() - before; + assert_block(&text(&s, id)); + // The command fits the object to compare and to apply (each a measure, at most two layouts a + // pass and the caches), plus the reply's own. + let bound = 2 * (2 + 2 * super::block::BLOCK_PASSES as u64) + 4; + assert!(used <= bound, "{used} layouts"); +} diff --git a/crates/engine/src/cmd/typemenu.rs b/crates/engine/src/cmd/typemenu.rs index deaac8acc4..c3db479332 100644 --- a/crates/engine/src/cmd/typemenu.rs +++ b/crates/engine/src/cmd/typemenu.rs @@ -1,13 +1,13 @@ //! Type menu long tail (Change Case, Smart Punctuation, Convert To Area/Point Type, Type on a Path -//! Options, Fill with Placeholder Text, Insert Special/Whitespace/Break characters) and the text -//! commands of the Edit menu (Find and Replace, Find Next, Paste without Formatting). +//! Options, Dynamic Text, Fill with Placeholder Text, Insert Special/Whitespace/Break characters) +//! and the text commands of the Edit menu (Find and Replace, Find Next, Paste without Formatting). use serde_json::{Value, json}; -use vectorcraft_doc::{CharStyle, Document, Justify, LockedArtboards, Node, NodeId, NodeKind, Quotes, TextKind, TextObject, TextRun}; +use vectorcraft_doc::{AreaFit, CharStyle, Document, Justify, LockedArtboards, Node, NodeId, NodeKind, Quotes, TextKind, TextObject, TextRun}; use vectorcraft_geom::{Affine, Rect, shapes}; use super::object::choice; -use super::typecmd::refresh_bounds; +use super::typecmd::{area_text, block_gaps, refresh_bounds}; use super::{ CommandSpec, EngineError, Result, Session, bad, checked_ids_param, cmd, find_command, has_clipboard, has_doc, has_selection, number_or, switch_or, targets, text_param, @@ -65,8 +65,8 @@ pub fn specs() -> Vec { "Dynamic Text", ["Type"], None, - "{ids?|id?, on?: bool} turn Dynamic Text on or off for the selected type on a path (on omitted: the opposite of the first object's setting). On, the layout scales the text by one factor (every character's size, leading and baseline shift; Type on a Path Options › Spacing stays) so that it fills the span between its start and end brackets, larger or smaller, and fits it again after every edit to the text, the path or the brackets; the first character's size moves in steps of 0.1 pt within 0.1 to 1,296 pt, and at 0.1 pt text that still runs past the end bracket overflows. The stored sizes keep their proportions. Off, the text keeps the sizes it was drawn at. Point type and area type in the selection are left as they are; a selection holding type on a path in a thread is refused (threading type turns Dynamic Text off, keeping its drawn sizes). When every object already has the setting, nothing changes and no undo step is recorded → {on, ids, fitScale (the first object's factor, 1 when off)}", - has_free_path_type, + "{ids?|id?, on?: bool, wordGap?: % of a word space 0..1000 (100), lineGap?: pt -1296..1296 (0)} turn Dynamic Text on or off for the selected type on a path and area type (on omitted: the opposite of the first object's setting, or on when a gap is given). On type on a path, the layout scales the text by one factor (every character's size, leading and baseline shift; Type on a Path Options › Spacing stays) so that it fills the span between its start and end brackets, larger or smaller, and fits it again after every edit to the text, the path or the brackets; the first character's size moves in steps of 0.1 pt within 0.1 to 1,296 pt, and at 0.1 pt text that still runs past the end bracket overflows. The stored sizes keep their proportions. On area type it is Block: each line as typed (each paragraph, and each forced line break in one; lines are not broken again) is set to the frame's width, less the inset, the gutters and the paragraph's indents, by changing its font size only: its first character's size, in steps of 0.1 pt within 0.1 to 1,296 pt, the line's other characters keeping their proportions to it, with baseline shifts following. Every character's leading is its size plus lineGap, and every paragraph's Desired word spacing is wordGap (the gaps are area type's, and are kept while Block is off). The sizes are written into the characters and fitted again after every edit to the text or the frame, in the same undo step; at a size limit a line can be narrower than the frame or wrap. An empty line keeps its size. Block replaces Auto Size and Shrink Text to Fit (Area Type Options › Block is the same setting). Off, the text keeps the sizes it was drawn at. Point type in the selection is left as it is; a selection holding type in a thread is refused (threading type turns Dynamic Text off, keeping its drawn sizes). When nothing changes, no undo step is recorded → {on, ids, fitScale (the first object's factor; 1 when off and for area type), wordGap?, lineGap? (the first area type's; left out without area type)}", + has_dynamic_type, dynamic_text ), cmd!( @@ -520,26 +520,40 @@ fn path_options(s: &mut Session, p: &Value) -> Result { options(s) } -/// Whether type on a path `id` is a frame of a thread. +/// Whether type `id` is a frame of a thread. fn threaded(d: &Document, id: NodeId) -> bool { !super::threads::story_of(d, id).is_empty() } -/// `type.dynamicText` is enabled for a selection holding type on a path, none of it in a thread. -fn has_free_path_type(s: &Session) -> std::result::Result<(), String> { +/// Type on a path or area type: the type Dynamic Text works on. +fn dynamic_type(n: Option<&Node>) -> Option<&TextObject> { + path_text(n).or_else(|| area_text(n)) +} + +/// `type.dynamicText` is enabled for a selection holding type on a path or area type, none of it +/// in a thread. +fn has_dynamic_type(s: &Session) -> std::result::Result<(), String> { has_selection(s)?; let st = s.active().ok_or("no document open")?; let d = &st.doc; let selected: Vec = st.selection.objects.to_vec(); - let paths: Vec = text_ids(d, &selected).into_iter().filter(|id| path_text(d.node(*id)).is_some()).collect(); - if paths.is_empty() { - return Err("select type on a path".into()); + let types: Vec = text_ids(d, &selected).into_iter().filter(|id| dynamic_type(d.node(*id)).is_some()).collect(); + if types.is_empty() { + return Err("select type on a path or area type".into()); } + threaded_refusal(d, &types).map_or(Ok(()), Err) +} + +/// Why Dynamic Text is refused for `ids`: the frames among them that are in a thread, type on a +/// path first; None when none is. +fn threaded_refusal(d: &Document, ids: &[NodeId]) -> Option { + let (paths, areas): (Vec, Vec) = ids.iter().copied().partition(|id| path_text(d.node(*id)).is_some()); let frames = threaded_ids(d, &paths); if !frames.is_empty() { - return Err(format!("type on a path in a thread cannot use Dynamic Text: {frames}")); + return Some(format!("type on a path in a thread cannot use Dynamic Text: {frames}")); } - Ok(()) + let frames = threaded_ids(d, &areas); + (!frames.is_empty()).then(|| format!("area type in a thread cannot use Dynamic Text: {frames}")) } /// The ids among `ids` of frames of threads, as a list for a message; empty when there are none. @@ -547,32 +561,57 @@ fn threaded_ids(d: &Document, ids: &[NodeId]) -> String { ids.iter().filter(|id| threaded(d, **id)).map(|id| id.0.to_string()).collect::>().join(", ") } -/// Type › Dynamic Text: set `on` (without it, the opposite of the first object's setting) on the -/// selected type on a path, in one undo step, and none when every object already has it. Turning -/// it off keeps the sizes the text was drawn at ([`bake_dynamic_text`]). +/// Type › Dynamic Text: set `on` (without it, the opposite of the first object's setting, or on +/// when a gap is given) on the selected type on a path and area type (Block, with its gaps), in +/// one undo step, and none when nothing changes. Turning it off keeps the sizes the text was drawn +/// at ([`bake_dynamic_text`]). fn dynamic_text(s: &mut Session, p: &Value) -> Result { const C: &str = "type.dynamicText"; - let (ids, on, changing) = { + let (word_gap, line_gap) = block_gaps(p, C)?; + let (ids, on, planned) = { let d = &s.doc()?.doc; - let ids: Vec = texts(s, p, C)?.into_iter().filter(|i| path_text(d.node(*i)).is_some()).collect(); - let first = *ids.first().ok_or_else(|| bad(C, "select type on a path"))?; - let frames = threaded_ids(d, &ids); - if !frames.is_empty() { - return Err(bad(C, format!("type on a path in a thread cannot use Dynamic Text: {frames}"))); + let ids: Vec = texts(s, p, C)?.into_iter().filter(|i| dynamic_type(d.node(*i)).is_some()).collect(); + let first = *ids.first().ok_or_else(|| bad(C, "select type on a path or area type"))?; + if let Some(why) = threaded_refusal(d, &ids) { + return Err(bad(C, why)); } - let on = switch_or(p, "on", !path_text(d.node(first)).is_some_and(|t| t.dynamic_text), C)?; - let changing: Vec = ids.iter().copied().filter(|id| path_text(d.node(*id)).is_some_and(|t| t.dynamic_text != on)).collect(); - (ids, on, changing) + let gap_given = word_gap.is_some() || line_gap.is_some(); + let on = switch_or(p, "on", gap_given || !dynamic_type(d.node(first)).is_some_and(|t| t.dynamic_text), C)?; + // Each object as the command leaves it, and only those it changes. + let mut planned: Vec<(NodeId, TextObject)> = vec![]; + for id in &ids { + let Some(t) = dynamic_type(d.node(*id)) else { continue }; + let mut after = t.clone(); + if matches!(t.kind, TextKind::Area { .. }) { + after.area.word_gap = word_gap.unwrap_or(t.area.word_gap); + after.area.line_gap = line_gap.unwrap_or(t.area.line_gap); + } + match (on, t.dynamic_text) { + (true, true) => refresh_bounds(&mut after), + (true, false) => { + after.dynamic_text = true; + // Block replaces Auto Size and Shrink Text to Fit. + if matches!(t.kind, TextKind::Area { .. }) { + after.area.fit = AreaFit::None; + } + refresh_bounds(&mut after); + } + (false, true) => { + bake_dynamic_text(&mut after); + } + (false, false) => {} + } + if after != *t { + planned.push((*id, after)); + } + } + (ids, on, planned) }; - if !changing.is_empty() { + if !planned.is_empty() { s.edit("Dynamic Text", |d, _| { - for id in &changing { - let Some(NodeKind::Text(t)) = d.node_mut(*id).map(|n| &mut n.kind) else { continue }; - if on { - t.dynamic_text = true; - refresh_bounds(t); - } else { - bake_dynamic_text(t); + for (id, after) in &planned { + if let Some(NodeKind::Text(t)) = d.node_mut(*id).map(|n| &mut n.kind) { + **t = after.clone(); } } Ok(()) @@ -581,7 +620,13 @@ fn dynamic_text(s: &mut Session, p: &Value) -> Result { let d = &s.doc()?.doc; let fit = ids.first().and_then(|id| path_text(d.node(*id))).map_or(1.0, |t| vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t).fit_scale); - Ok(json!({"on": on, "ids": ids.iter().map(|i| i.0).collect::>(), "fitScale": fit})) + let mut reply = json!({"on": on, "ids": ids.iter().map(|i| i.0).collect::>(), "fitScale": fit}); + if let Some(t) = ids.iter().find_map(|id| area_text(d.node(*id))) { + let (w, l) = t.area.block_gaps(); + reply["wordGap"] = json!(w); + reply["lineGap"] = json!(l); + } + Ok(reply) } /// Turn Dynamic Text off on `t`, keeping the sizes its layout draws it at: every run's size, diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs index 347f6734e7..9bad62a6c8 100644 --- a/crates/engine/src/inspect.rs +++ b/crates/engine/src/inspect.rs @@ -99,14 +99,15 @@ pub fn node_summary_opts(n: &Node, opts: SummaryOpts, symbols: &SymbolBoxes) -> NodeKind::Text(t) => { v["text"] = json!(t.plain_text()); // Area type and type on a path: does the text fit (the red overflow "+")? Area type - // also reports its fit and Shrink Text's factor (1 unshrunk), and type on a path its - // Dynamic Text setting and factor (1 when off). + // also reports its fit (`block` for Dynamic Text's Block) and Shrink Text's factor (1 + // unshrunk), and type on a path its factor (1 when off); both report Dynamic Text. if !matches!(t.kind, vectorcraft_doc::TextKind::Point) { let lay = vectorcraft_text::layout(vectorcraft_text::FontDb::global(), t); v["overflow"] = json!(lay.overflow); if matches!(t.kind, vectorcraft_doc::TextKind::Area { .. }) { - v["fit"] = json!(t.area.fit.id()); + v["fit"] = json!(crate::cmd::typecmd::fit_id(t)); v["fitScale"] = json!(lay.fit_scale); + v["dynamicText"] = json!(t.dynamic_text); } else { v["dynamicText"] = json!(t.dynamic_text); v["fitScale"] = json!(lay.fit_scale); diff --git a/crates/engine/src/tests/dynamic_text.rs b/crates/engine/src/tests/dynamic_text.rs index 80ad1f1af9..3512db9c59 100644 --- a/crates/engine/src/tests/dynamic_text.rs +++ b/crates/engine/src/tests/dynamic_text.rs @@ -88,14 +88,10 @@ fn dynamic_text_refuses_bad_params_and_other_type() { assert!(err(s.execute("type.dynamicText", &json!({"on": 1}))).contains("on")); assert_eq!(undo_len(&s), before); assert!(!text(&s, id).dynamic_text); - // Point type and area type alone: refused. + // Point type alone: refused (area type takes Block, `typecmd::block_tests`). let point = s.execute("text.create", &json!({"x": 10, "y": 10, "text": "Point"})).unwrap()["id"].as_u64().unwrap(); - let area = - s.execute("text.create", &json!({"x": 10, "y": 100, "text": "Area", "area": {"width": 100, "height": 50}})).unwrap()["id"].as_u64().unwrap(); - for other in [point, area] { - s.execute("select.set", &json!({"ids": [other]})).unwrap(); - assert!(err(s.execute("type.dynamicText", &json!({}))).contains("select type on a path")); - } + s.execute("select.set", &json!({"ids": [point]})).unwrap(); + assert!(err(s.execute("type.dynamicText", &json!({}))).contains("select type on a path or area type")); let empty = s.execute("shape.rectangle", &json!({"x": 300, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); s.execute("select.set", &json!({"ids": [empty]})).unwrap(); assert!(s.execute("type.dynamicText", &json!({})).is_err()); diff --git a/crates/ui-egui/src/dialogs/command.rs b/crates/ui-egui/src/dialogs/command.rs index 0a722cbcf8..3acd7e6c0e 100644 --- a/crates/ui-egui/src/dialogs/command.rs +++ b/crates/ui-egui/src/dialogs/command.rs @@ -102,7 +102,7 @@ fn lengths(command: &str) -> &'static [&'static str] { "shape.flare" => &["diameter", "pathLength"], "perspective.grid.set" => &["cell", "distance"], "object.repeat.options" => &["radius", "hSpacing", "vSpacing"], - "text.areaOptions" => &["width", "height", "gutter", "rowGutter", "inset", "firstBaselineMin"], + "text.areaOptions" => &["width", "height", "gutter", "rowGutter", "inset", "firstBaselineMin", "lineGap"], "type.pathOptions" => &["spacing"], "object.pathfinder.trap" => &["thickness"], _ => &[], @@ -156,8 +156,8 @@ const RASTERIZE_CMYK: form::Choices = &[("CMYK", "cmyk"), ("Grayscale", "graysca /// Type on a Path Options › Align to Path. const PATH_ALIGN: form::Choices = &[("Ascender", "ascender"), ("Descender", "descender"), ("Center", "center"), ("Baseline", "baseline")]; -/// Area Type Options › Fit. -const AREA_FIT: form::Choices = &[("None", "none"), ("Auto Size", "autoHeight"), ("Shrink Text to Fit", "shrinkText")]; +/// Area Type Options › Fit (Block is Dynamic Text's, as `type.dynamicText` sets it). +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 = diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 572a19779f..73a18cb18b 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -6371,7 +6371,7 @@ antiAlias Sharp शार्प @msg files must be {name, dataBase64} files: फ़ाइलों को {name, dataBase64} होना चाहिए @msg finish editing the pattern first पहले पैटर्न को संपादित करना @msg First measured segment no longer exists पहले मापा खंड अब मौजूद नहीं है -@msg fit must be none|autoHeight|shrinkText, got {id} fit को none|autoHeight|shrinkText होना चाहिए, {id} मिला +@msg fit must be none|autoHeight|shrinkText|block, got {id} fit को none|autoHeight|shrinkText|block होना चाहिए, {id} मिला @msg Flare click coordinates must be finite numbers फ्लेयर क्लिक निर्देशांक परिमित संख्या होना चाहिए @msg Flat Logo traced the image at {_1} × {_2} pixels, averaged down from {_3} × {_4}. फ्लैट लोगो ने {_1} × {_2} पिक्सेल पर इमेज का पता लगाया, जो {_3} × {_4} से नीचे है। @msg Flatten Transparency: {e} Flatten transparency: {e} diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index fb2c463de0..24dcb30bb4 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -7406,7 +7406,7 @@ digits Hindi Hindi @msg features must be a list of tags features måste vara en lista med taggar @msg fidelity must be 0..100 fidelity måste vara 0..100 @msg files must be {name, dataBase64} files måste vara {name, dataBase64} -@msg fit must be none|autoHeight|shrinkText, got {id} fit måste vara none|autoHeight|shrinkText, fick {id} +@msg fit must be none|autoHeight|shrinkText|block, got {id} fit måste vara none|autoHeight|shrinkText|block, fick {id} @msg Flare click coordinates must be finite numbers Klickkoordinaterna för Ljusreflex måste vara ändliga tal @msg flattener: {e} utplattning: {e} @msg flattenerPreset `{name}`: high, medium, low or a saved one (see flattener.presets.list) flattenerPreset `{name}`: high, medium, low eller en sparad (se flattener.presets.list) diff --git a/crates/ui-egui/src/menus/state.rs b/crates/ui-egui/src/menus/state.rs index 2e45a88483..9cbeda6043 100644 --- a/crates/ui-egui/src/menus/state.rs +++ b/crates/ui-egui/src/menus/state.rs @@ -16,16 +16,16 @@ pub fn checked(app: &VectorcraftApp, id: &str, p: &Value) -> Option { let v = &app.ui.view; // An item that can be on or off is `Some` whatever the document and selection (off with none): // the macOS menu bar can't change an item's kind without rebuilding. - // The first type object (of type on a path, with `onpath`) among the selected objects and the - // objects inside them, in the order the type commands act on them. - let selected_text = |onpath: bool| { + // The first type object of a kind `kinds` takes among the selected objects and the objects + // inside them, in the order the type commands act on them. + let selected_text = |kinds: fn(&vectorcraft_engine::doc::TextKind) -> bool| { let st = app.session.active()?; let mut found = None; for n in st.selection.objects.iter().filter_map(|id| st.doc.node(*id)) { n.walk(&mut |c| { if found.is_none() && let vectorcraft_engine::doc::NodeKind::Text(t) = &c.kind - && (!onpath || matches!(t.kind, vectorcraft_engine::doc::TextKind::OnPath { .. })) + && kinds(&t.kind) { found = Some(t); } @@ -41,17 +41,17 @@ pub fn checked(app: &VectorcraftApp, id: &str, p: &Value) -> Option { crate::panels::character::shared_text_flag(app, |t| t.vertical) == Some(id == "type.orientation.vertical") } "type.opticalMarginAlignment" => crate::panels::character::shared_text_flag(app, |t| t.optical_margin) == Some(true), - // Dynamic Text of the first selected type on a path, which the item turns the other way. - "type.dynamicText" => selected_text(true).is_some_and(|t| t.dynamic_text), + // Dynamic Text of the first selected type on a path or area type, which the item turns the + // other way. + "type.dynamicText" => selected_text(|k| !matches!(k, vectorcraft_engine::doc::TextKind::Point)).is_some_and(|t| t.dynamic_text), "view.outline" => app.outline_view(), "view.pixelPreview" => v.pixel_preview, "view.trimView" => v.trim_view, "view.snapToPixel" => v.snap_to_pixel, "view.snapToGlyph" => v.snap_to_glyph, // Type on a Path effect of the selected path type. - "type.pathOptions" if p.get("effect").is_some() => { - selected_text(true).is_some_and(|t| p.get("effect").and_then(Value::as_str) == Some(t.path_effect.id())) - } + "type.pathOptions" if p.get("effect").is_some() => selected_text(|k| matches!(k, vectorcraft_engine::doc::TextKind::OnPath { .. })) + .is_some_and(|t| p.get("effect").and_then(Value::as_str) == Some(t.path_effect.id())), "view.smartGuides" => v.smart_guides, "edit.autoSpellCheck" => v.auto_spell_check, "view.grid" => v.grid, diff --git a/crates/ui-egui/src/menus/tests.rs b/crates/ui-egui/src/menus/tests.rs index a449fb0361..8591c4d89d 100644 --- a/crates/ui-egui/src/menus/tests.rs +++ b/crates/ui-egui/src/menus/tests.rs @@ -313,8 +313,8 @@ fn optical_margin_alignment_is_a_checked_type_menu_item() { assert_eq!(checked(&app, "type.orientation.horizontal", &Value::Null), Some(false)); } -/// Type › Dynamic Text runs `type.dynamicText`, is enabled for type on a path that is in no -/// thread, and is checked while the selected type on a path has it on. +/// Type › Dynamic Text runs `type.dynamicText`, is enabled for type on a path and area type that +/// are in no thread, and is checked while the selected type has it on. #[test] fn dynamic_text_is_a_checked_type_menu_item() { let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), crate::Services::default()); @@ -349,6 +349,13 @@ fn dynamic_text_is_a_checked_type_menu_item() { app.run("text.thread.create", json!({})).unwrap(); app.run("select.set", json!({"ids": [t]})).unwrap(); assert!(!enabled(&app, id), "type on a path in a thread"); + // Area type takes Block, and the item is checked while it is on. + let area = app.run("text.create", json!({"x": 10, "y": 400, "text": "Block", "area": {"width": 100, "height": 50}})).unwrap()["id"].clone(); + app.run("select.set", json!({"ids": [area]})).unwrap(); + assert!(enabled(&app, id), "area type"); + assert_eq!(checked(&app, id, &Value::Null), Some(false)); + app.run(id, json!({})).unwrap(); + assert_eq!(checked(&app, id, &Value::Null), Some(true)); } /// Type › Optical Margin Alignment menu check uses `shared_text_flag`; mixed values stay unchecked. diff --git a/crates/ui-egui/src/panels/properties.rs b/crates/ui-egui/src/panels/properties.rs index 3dd7da7d6e..6dcd4a516f 100644 --- a/crates/ui-egui/src/panels/properties.rs +++ b/crates/ui-egui/src/panels/properties.rs @@ -1014,9 +1014,12 @@ pub fn type_sections(app: &mut VectorcraftApp, ui: &mut Ui) { }); } super::paragraph::hyphenate_check(app, ui, ¶); + // Area type: Dynamic Text's Block and its gaps. + dynamic_text::rows(app, ui); } } +pub(crate) mod dynamic_text; pub(crate) mod vertical_align; #[cfg(test)] diff --git a/crates/ui-egui/src/panels/properties/dynamic_text.rs b/crates/ui-egui/src/panels/properties/dynamic_text.rs new file mode 100644 index 0000000000..7caf9e41f5 --- /dev/null +++ b/crates/ui-egui/src/panels/properties/dynamic_text.rs @@ -0,0 +1,84 @@ +//! Dynamic Text in the Properties panel's Paragraph section: the Dynamic Text checkbox for the +//! selected area type (Block, `type.dynamicText`) and, while it is on, its Word Gap and Line Gap +//! rows ([Dynamic Text overview](https://helpx.adobe.com/photoshop/desktop/text-typography/work-with-dynamic-text/dynamic-text-overview.html) +//! describes Block and its spacing between words and between lines). + +use egui::Ui; +use serde_json::{Value, json}; +use vectorcraft_doc::{AreaOptions, NodeKind, TextKind}; + +use crate::VectorcraftApp; +use crate::widgets; + +/// What the selected area type shows: whether Block is on in every frame (`None` when they +/// differ), the gaps every frame shares (`None` when they differ), and whether every frame can +/// take it (none is threaded). +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct Shown { + pub(crate) on: Option, + pub(crate) word_gap: Option, + pub(crate) line_gap: Option, + pub(crate) enabled: bool, +} + +/// Dynamic Text of the selected area type (and area type in selected groups); `None` when the +/// selection holds no area type, or holds other type too (the command refuses it). +pub(crate) fn shown(app: &VectorcraftApp) -> Option { + let st = app.session.active()?; + let threaded = |id| st.doc.text_threads.iter().any(|t| t.len() > 1 && t.contains(&id)); + let mut frames = vec![]; + let mut other = false; + for n in st.selection.objects.iter().filter_map(|id| st.doc.node(*id)) { + n.walk(&mut |c| { + let NodeKind::Text(t) = &c.kind else { return }; + if matches!(t.kind, TextKind::Area { .. }) { + let (word, line) = t.area.block_gaps(); + frames.push((t.dynamic_text, word, line, threaded(c.id))); + } else { + other = true; + } + }); + } + let &(on, word, line, _) = frames.first().filter(|_| !other)?; + Some(Shown { + on: frames.iter().all(|f| f.0 == on).then_some(on), + word_gap: frames.iter().all(|f| f.1 == word).then_some(word), + line_gap: frames.iter().all(|f| f.2 == line).then_some(line), + enabled: frames.iter().all(|f| !f.3), + }) +} + +fn run(app: &mut VectorcraftApp, p: Value) { + if let Err(e) = app.run("type.dynamicText", p) { + app.status(e); + } +} + +/// The checkbox, and the gap rows while every selected frame has Block on. Nothing shows without +/// area type. Returns whether anything was drawn. +pub(crate) fn rows(app: &mut VectorcraftApp, ui: &mut Ui) -> bool { + let Some(s) = shown(app) else { return false }; + if widgets::check(ui, tl!("Dynamic Text"), s.on == Some(true), s.enabled) { + run(app, json!({ "on": s.on != Some(true) })); + } + if s.on != Some(true) { + return true; + } + let fw = super::super::field_width(ui); + let (lo, hi) = AreaOptions::WORD_GAP; + ui.horizontal(|ui| { + ui.label(tl!("Word Gap")); + if let Some(v) = widgets::spin_plain_named(ui, "props-dt-word", Some(tl!("Word Gap")), s.word_gap, "%", 0, fw, 10.0, lo, &[]) { + run(app, json!({ "wordGap": v.clamp(lo, hi) })); + } + }); + let (lo, hi) = AreaOptions::LINE_GAP; + let unit = app.session.general_unit(); + ui.horizontal(|ui| { + ui.label(tl!("Line Gap")); + if let Some(v) = widgets::spin_field_named(ui, "props-dt-line", Some(tl!("Line Gap")), s.line_gap, unit, fw, 1.0, lo, &[]) { + run(app, json!({ "lineGap": v.clamp(lo, hi) })); + } + }); + true +} diff --git a/crates/ui-egui/src/panels/properties/tests.rs b/crates/ui-egui/src/panels/properties/tests.rs index a9853d3173..5ed020c326 100644 --- a/crates/ui-egui/src/panels/properties/tests.rs +++ b/crates/ui-egui/src/panels/properties/tests.rs @@ -1946,3 +1946,38 @@ fn vertical_alignment_buttons_align_the_selected_area_type() { app.run("select.set", json!({"ids": [a]})).unwrap(); assert_eq!(vertical_align::shown(&app).map(|s| s.enabled), Some(false)); } + +/// With area type selected, the Paragraph section shows a Dynamic Text checkbox, and Word Gap and +/// Line Gap while Block is on in every selected frame. Point type in the selection shows none; +/// threaded frames turn the checkbox off. +#[test] +fn dynamic_text_rows_follow_the_selected_area_type() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 500, "height": 400})).unwrap(); + let make = |app: &mut VectorcraftApp, x: f64, y: f64| { + app.run("text.create", json!({"x": x, "y": y, "text": "Panel\ntext", "area": {"width": 100, "height": 120}})).unwrap()["id"].as_u64().unwrap() + }; + let (a, b) = (make(&mut app, 10.0, 10.0), make(&mut app, 200.0, 10.0)); + let point = app.run("text.create", json!({"x": 10, "y": 350, "text": "Point"})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [a, point]})).unwrap(); + assert_eq!(dynamic_text::shown(&app), None, "point type selected too: no rows"); + app.run("select.set", json!({"ids": [a, b]})).unwrap(); + let off = dynamic_text::Shown { on: Some(false), word_gap: Some(100.0), line_gap: Some(0.0), enabled: true }; + assert_eq!(dynamic_text::shown(&app), Some(off)); + let ctx = egui::Context::default(); + let texts = panel_frame(&mut app, &ctx, vec![], type_sections); + assert!(texts.iter().any(|(t, _)| t == "Dynamic Text") && !texts.iter().any(|(t, _)| t == "Word Gap"), "{texts:?}"); + app.run("type.dynamicText", json!({"on": true, "lineGap": 2})).unwrap(); + let on = dynamic_text::Shown { on: Some(true), word_gap: Some(100.0), line_gap: Some(2.0), enabled: true }; + assert_eq!(dynamic_text::shown(&app), Some(on)); + let texts = panel_frame(&mut app, &ctx, vec![], type_sections); + assert!(texts.iter().any(|(t, _)| t == "Word Gap") && texts.iter().any(|(t, _)| t == "Line Gap"), "{texts:?}"); + // Differing gaps and settings show as mixed. + app.run("type.dynamicText", json!({"ids": [b], "wordGap": 200})).unwrap(); + assert_eq!(dynamic_text::shown(&app).map(|s| (s.on, s.word_gap, s.line_gap)), Some((Some(true), None, Some(2.0)))); + app.run("type.dynamicText", json!({"ids": [b], "on": false})).unwrap(); + assert_eq!(dynamic_text::shown(&app).map(|s| (s.on, s.word_gap)), Some((None, None))); + // A threaded frame turns the checkbox off. + app.run("text.thread.create", json!({})).unwrap(); + assert_eq!(dynamic_text::shown(&app).map(|s| (s.on, s.enabled)), Some((Some(false), false))); +} diff --git a/docs/mcp.md b/docs/mcp.md index 5826c5c8c4..44da10f748 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -6477,12 +6477,17 @@ Native files save it only when it is `rows`, so files from before it open by col sizes don't change: the scaling happens at layout time, so rendering and every export see it. The factor is found by bisection over the first run's size in steps of 0.1 pt (its scaled size is a whole number of tenths of a point, so the result is deterministic); at `fitMinPercent` the text may still overflow. +- `block`: Dynamic Text's Block, as `type.dynamicText` turns it on (see below), in place of Auto Size and Shrink Text + to Fit; another fit turns it off. `wordGap` (0–1,000 % of a word space, default 100) and `lineGap` (-1,296 to 1,296 + pt, default 0) set its gaps, and are kept while Block is off. The file stores `"fit": "autoHeight"` or `"fit": {"shrinkText": {"minPercent": 40}}` in the object's `area`; the -command also accepts that object form. The query (and every reply) of `text.areaOptions` reports `fit` as its id, -`fitMinPercent`, `overflow` (the text doesn't fit its frame) and `fitScale` (Shrink Text's factor, 1 unshrunk). +command also accepts that object form. Block is stored as the object's `"dynamicText": true`, with `wordGap` and +`lineGap` in its `area` when they differ from their defaults. The query (and every reply) of `text.areaOptions` +reports `fit` as its id (`block` while Block is on), `fitMinPercent`, `wordGap`, `lineGap`, `overflow` (the text +doesn't fit its frame) and `fitScale` (Shrink Text's factor, 1 unshrunk). `document.inspect` (and `document.node {summary: true}`) reports `overflow` for area type and type on a path (text past -the end of the path), and `fit` and `fitScale` for area type. +the end of the path), and `fit`, `fitScale` and `dynamicText` (Block is on) for area type. Given for several area types (`ids`, or a selection of several), `text.areaOptions` changes only the options given on each one: each frame keeps its other options (it used to take the first frame's), and `fitMinPercent` alone changes only @@ -6507,6 +6512,45 @@ chosen artboards draw all of them. A PDF leaves out the layers that don't print {"name":"run_command","arguments":{"command":"text.areaOptions","params":{"fit":"shrinkText","fitMinPercent":60}}} ``` +### Dynamic Text: Block + +`type.dynamicText {ids?|id?, on?: bool, wordGap?, lineGap?}` (Type › Dynamic Text) turns Block on or off for the +selected area type, as it turns Dynamic Text on or off for type on a path ([Dynamic Text](#dynamic-text)). Area Type +Options › Block is the same setting, and the Properties panel's Paragraph section has a Dynamic Text checkbox, which +shows Word Gap and Line Gap while it is on. The [Dynamic Text overview](https://helpx.adobe.com/photoshop/desktop/text-typography/work-with-dynamic-text/dynamic-text-overview.html) +describes Block as text that scales to fill a rectangular box, with settings for the spacing between words and between +lines. The rest are VectorCraft's own rules: + +- Each line as typed (each paragraph, and each forced line break, Shift+Enter, in one) is one line; lines are not + broken again. Each line is set to the frame's width, less the inset, the gutters between columns and the paragraph's + left, right and first-line indents, by its font size only (tracking and scaling stay): the first character's size in + steps of 0.1 pt within 0.1 to 1,296 pt, the line's other characters keeping their proportions to it and their + baseline shifts following. Vertical type sets each line to the frame's height (less the gutters between rows). +- `wordGap` is every paragraph's Desired word spacing (Justification…), and each character's leading is its size + plus `lineGap`. +- The sizes are written into the characters, so every export and the Character panel see them. After every edit to + the text or the frame (typing, `text.editRange`, character and paragraph changes, `text.areaOptions {width}`, a + frame resize) the lines are fitted again, in the edit's own undo step. The lines are then measured again, in at + most four passes: a line whose width does not follow its size (a tab to a fixed stop) is sized again from what it + measures, and a line that still wraps (a frame that is not a rectangle) is made smaller. +- An empty line, or a line of spaces, keeps its size. At 1,296 pt a line can be narrower than the frame; at 0.1 pt it + can still wrap. A frame with no room along its lines changes nothing. Right-to-left lines are fitted as left-to-right + ones are. +- Off keeps the sizes the text was drawn at. On replaces Auto Size and Shrink Text to Fit. Point type in the selection + is left as it is. Area type in a thread is refused with an error that names it (`text.areaOptions {fit: "block"}` + refuses it too); threading a frame turns Block off, keeping its sizes. Without `on`, it toggles from the first + object's setting, or turns on when a gap is given. A value that is not a boolean, or a gap outside its range, is an + error. When nothing changes, no undo step is recorded. +- Saved and opened, the native file keeps Block on with its gaps and the sizes in the characters; with Block off it + keeps the sizes. + +The reply is `{on, ids, fitScale, wordGap, lineGap}` (`fitScale` as for type on a path, 1 when the first object is area +type; the gaps are the first area type's). + +```json +{"name":"run_command","arguments":{"command":"type.dynamicText","params":{"on":true,"wordGap":120,"lineGap":2}}} +``` + ## Threading text from the in and out ports As in the reference app, selected area type and type on a path show an in port and an out port: area type's on the @@ -7314,12 +7358,13 @@ and tate-chu-yoko offsets by one factor, so runs keep their proportions; Type on scaled. The first character's size, in document points, moves in steps of 0.1 pt within 0.1 to 1,296 pt; text that still runs past the end bracket at 0.1 pt overflows. Reshaping or scaling the path fits the text again. The stored sizes do not change: turning Dynamic Text off writes the sizes the text was drawn at into its characters, so it keeps -its look, in one undo step. Point type and area type in the selection are left as they are. Type on a path in a +its look, in one undo step. Point type in the selection is left as it is, and area type in it takes Block +([Dynamic Text: Block](#dynamic-text-block)). Type on a path in a thread is refused with an error that names it, and the menu item and the task bar item are not offered for it; `text.thread.create` and `text.thread.add` turn Dynamic Text off on the frames they thread, at their drawn sizes, and list them in `dynamicTextOff`. When every object already has the setting asked for, nothing changes and no undo step is recorded. It replies `{on, ids, fitScale}` (the first object's factor, 1 when off), and the menu item is checked -while the first selected type on a path has it on. `document.inspect` reports `dynamicText` and `fitScale` for type +while the first selected type on a path or area type has it on. `document.inspect` reports `dynamicText` and `fitScale` for type on a path. New type and documents from before it have it off, and it is saved only when on. SVG, PDF, EPS and the editing data for other apps write the type at its drawn sizes; the editing data does not hold the setting and says so in a warning. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index b4c949f742..cd3f49ef69 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1159,6 +1159,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur With Optical Margin Alignment on, or Roman Hanging Punctuation on in the first paragraph, the glyphs at the ends of left-to-right type on a path hang outside its brackets, measured along the path. The type hangs at the start bracket when its line is placed there, hangs at the end bracket when the line is placed there, and hangs at both when it is centered. Glyphs that hang past the end bracket do not make the type overflow, and a hang stops at an open path's end. SVG export writes such type as outlines. Type on a Path Options › Align to Path (option names as in [Create type on a path](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/create-type-on-a-path.html)) moves each character by its own font, size and vertical scale: Ascender runs the top of the font's em box along the path (the ideographic em box that its `BASE` table, its typographic or `hhea` box or its ideographs give, else an em box centered on the cap height), Descender runs the bottom of the font's bounding box along it, and Center runs a line at half the height of the top of the font's H above the baseline along it. In vertical type, Ascender and Descender move the characters half an em, and Center leaves them on the path. These distances are VectorCraft's own values (`tests::on_path_align_runs_each_glyph_by_its_own_metrics`, `tests::on_path_align_finds_the_em_box_of_each_kind_of_face`, `tests::on_path_align_in_vertical_type_moves_half_an_em`). Type › Dynamic Text (`type.dynamicText`, also on the Contextual Task Bar for type on a path) sizes type on a path to fill the span between its start and end brackets and fits it again after each edit to the text, the path or a bracket ([Dynamic Text overview](https://helpx.adobe.com/photoshop/desktop/text-typography/work-with-dynamic-text/dynamic-text-overview.html), [start and end points](https://helpx.adobe.com/photoshop/desktop/text-typography/work-with-dynamic-text/reposition-start-and-end-points.html)). VectorCraft's own rules: one factor scales every size, leading and baseline shift; the first character's size moves in 0.1 pt steps within 0.1 to 1,296 pt; turning it off or threading the type keeps the drawn sizes; SVG, EPS and the editing data write the drawn sizes (`crates/text/src/tests/fit.rs`, `crates/engine/src/tests/dynamic_text.rs`). + Dynamic Text on area type is Block (Type › Dynamic Text, Area Type Options › Block, the Properties panel's Dynamic Text checkbox with Word Gap and Line Gap; [Dynamic Text overview](https://helpx.adobe.com/photoshop/desktop/text-typography/work-with-dynamic-text/dynamic-text-overview.html)): each line as typed is set to the frame's width by its font size, again after every edit to the text or the frame. VectorCraft's own rules: lines are not broken again, the first character's size moves in 0.1 pt steps within 0.1 to 1,296 pt, Word Gap (0 to 1,000 %, default 100) is the Desired word spacing and Line Gap (-1,296 to 1,296 pt, default 0) is added to each size for the leading, the sizes are written into the characters, and threaded frames cannot use it (`crates/engine/src/cmd/typecmd/block_tests.rs`). The frames of threaded text share one Optical Margin Alignment setting: turning it on or off in one frame sets it in every frame, threading frames gives the thread its first frame's setting, and frames taken out of a thread keep it. The frames of threaded text share one writing direction: Type › Type Orientation (`type.orientation.vertical`, `type.orientation.horizontal`) in one frame sets every frame, threading frames gives the thread its first frame's direction, frames taken out of a thread keep theirs, and the story flows through every frame in the thread's direction. Type › Optical Margin Alignment (`type.opticalMarginAlignment`) hangs the punctuation and letter edges at the ends of a type object's lines outside its margins: at the left of left-aligned lines, at the right of right-aligned lines, and at both ends of centered and justified lines, in point and area type of left-to-right paragraphs. Quotation marks, hyphens, full stops and commas hang wholly; asterisks, tildes, ellipses, en and em dashes, colons and semicolons hang by half; and A, V, W, Y, v, w and y hang by a tenth of their width. It is off by default and saved with the type object. Justification's Glyph Scaling leaves the glyphs that hang at their width, so they hang exactly their share, and Standard burasagari counts what hangs at a line's start as room before hanging a comma; `crates/text/src/tests/hang.rs` checks whole paragraphs with both composers, ragged, centred and justified, with Line-end Punctuation Half Width and bidirectional lines. From 7f3a046b184661e8e9386acf3706f9a1eeb1d1c6 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Wed, 11 Nov 2026 23:04:49 +0100 Subject: [PATCH 07/38] CI: nightly release dry run (#6678) release.yml also runs nightly on main with craft-common-actions' dry-run: every release build except macOS, with nothing signed, pushed or drafted. Breakage that only the release build hits (riscv64, Flatpak, FreeBSD, packaging) then shows up the next morning instead of on release day, as it did on 11 Nov 2026. --- .github/workflows/release.yml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index eee66ab3be..fd836de6c7 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -3,6 +3,10 @@ name: Release on: + # A nightly dry run on main: every release build except macOS, nothing signed or released + # (craft-common-actions release.yml `dry-run`). Finds release-only breakage before release day. + schedule: + - cron: "52 2 * * *" push: branches: [release] workflow_dispatch: @@ -77,6 +81,7 @@ jobs: # Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos. uses: storytold/craft-common-actions/.github/workflows/release.yml@main with: + dry-run: ${{ github.event_name == 'schedule' }} app-name: vectorcraft app-title: VectorCraft craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83 From 0d600449d12636bf60dc654be2af09e9b965a98d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 14:31:33 -0800 Subject: [PATCH 08/38] Simplify: the samples of a flat loop count its line segments in the limit When a flat closed loop becomes the lines between samples of its curved segments, the line segments it keeps now count toward the 2,097,152-line limit before the rest is shared among the curved segments. When that leaves no line for some curved segment, the loop stays as it is. --- crates/pathops/src/edit.rs | 32 +++++++++++++++++++++++++++++--- 1 file changed, 29 insertions(+), 3 deletions(-) diff --git a/crates/pathops/src/edit.rs b/crates/pathops/src/edit.rs index da8e5e4d8f..17b231a5dc 100644 --- a/crates/pathops/src/edit.rs +++ b/crates/pathops/src/edit.rs @@ -146,8 +146,9 @@ fn simplify_subpath(sp: &SubPath, opts: &SimplifyOptions) -> Option { // ends and those lines enclose an area: with straight lines they are the result, and without // them the loop stays as it is. When no split within those limits encloses an area, the loop // stays as it is, or with straight lines each curved segment becomes the lines between its - // samples, up to `MAX_RUN_RESULT` lines in all. A loop whose points are all in line keeps the - // lines of the refit. + // samples, up to `MAX_RUN_RESULT` lines in all with the line segments; when that leaves no + // line for some curved segment, the loop stays as it is. A loop whose points are all in line + // keeps the lines of the refit. let near = |c: &CubicBez| [c.p1, c.p2].iter().all(|&p| Line::new(c.p0, c.p3).nearest(p, 1e-9).distance_sq.sqrt() <= opts.tolerance); let curved = segs.iter().filter(|s| !s.line).count(); for k in 1..=10u32 { @@ -174,7 +175,9 @@ fn simplify_subpath(sp: &SubPath, opts: &SimplifyOptions) -> Option { if !opts.straight_lines { return Some(sp.clone()); } - let room = (MAX_RUN_RESULT / curved.max(1)).min(MAX_SEGMENT_SAMPLES); + let Some(room) = sample_room(curved, n - curved) else { + return Some(sp.clone()); + }; let mut lines: Vec = Vec::new(); for s in &segs { if s.line { @@ -192,6 +195,17 @@ fn simplify_subpath(sp: &SubPath, opts: &SimplifyOptions) -> Option { Some(if opts.straight_lines { s } else { no_worse(sp, s) }) } +/// Most lines between samples of each of `curved` segments, so that they and the `kept` line segments +/// make at most [`MAX_RUN_RESULT`] lines, and each has at most [`MAX_SEGMENT_SAMPLES`]. `None` when +/// that leaves no line for some curved segment. +fn sample_room(curved: usize, kept: usize) -> Option { + let left = MAX_RUN_RESULT.checked_sub(kept)?; + if curved > left { + return None; + } + Some((left / curved.max(1)).min(MAX_SEGMENT_SAMPLES)) +} + /// How far a segment may be from the lines between its samples, as a share of the tolerance. const SAMPLE_GAP: f64 = 0.005; @@ -1156,6 +1170,18 @@ mod tests { assert!(work <= 400 * pts.len(), "{work} steps for {} samples", pts.len()); } + #[test] + fn the_samples_of_a_flat_loop_and_its_line_segments_stay_within_the_result_limit() { + for (curved, kept) in [(1, 0), (32, 1), (40, 1_000_000), (1_000, MAX_RUN_RESULT - 1_000), (3, MAX_RUN_RESULT - 7)] { + let room = sample_room(curved, kept).unwrap_or_else(|| panic!("{curved} curved, {kept} kept: no room")); + assert!((1..=MAX_SEGMENT_SAMPLES).contains(&room), "{curved} curved, {kept} kept: room {room}"); + assert!(curved * room + kept <= MAX_RUN_RESULT, "{curved} curved, {kept} kept: room {room}"); + } + assert_eq!(sample_room(32, 0), Some(MAX_SEGMENT_SAMPLES)); + assert_eq!(sample_room(2, MAX_RUN_RESULT - 1), None); + assert_eq!(sample_room(1, MAX_RUN_RESULT + 5), None); + } + #[test] fn smoothing_points_whose_arc_length_overflows_returns_every_point() { let pts: Vec = (0..40).map(|i| Point::new(if i % 2 == 0 { -1e308 } else { 1e308 }, f64::from(i))).collect(); From 883c24a3a8d64081d0c2a091e24dd55a55b927e5 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 14:39:25 -0800 Subject: [PATCH 09/38] Simplify: lines between samples of a flat loop stay within the tolerance When the room left in the result limit is too small for the lines of a curved segment to stay within the tolerance, the loop stays as it is instead of taking fewer lines that can pass it. --- crates/pathops/src/edit.rs | 43 +++++++++++++++++++++++++++++++++----- 1 file changed, 38 insertions(+), 5 deletions(-) diff --git a/crates/pathops/src/edit.rs b/crates/pathops/src/edit.rs index 17b231a5dc..d8d121ecb9 100644 --- a/crates/pathops/src/edit.rs +++ b/crates/pathops/src/edit.rs @@ -90,7 +90,8 @@ pub fn simplify_with(path: &PathData, opts: &SimplifyOptions) -> PathData { /// no area, straight lines follow the subpath within the tolerance, and without straight lines it /// stays as it is, as does one of a single segment. When no lines within the limits on pieces enclose /// an area, it stays as it is, or with straight lines follows the lines between samples of each -/// curved segment; one that is all in line keeps the refit. +/// curved segment when the limits leave room for lines within the tolerance; one that is all in line +/// keeps the refit. fn simplify_subpath(sp: &SubPath, opts: &SimplifyOptions) -> Option { let mut segs = subpath_segs(sp); let n = segs.len(); @@ -146,9 +147,9 @@ fn simplify_subpath(sp: &SubPath, opts: &SimplifyOptions) -> Option { // ends and those lines enclose an area: with straight lines they are the result, and without // them the loop stays as it is. When no split within those limits encloses an area, the loop // stays as it is, or with straight lines each curved segment becomes the lines between its - // samples, up to `MAX_RUN_RESULT` lines in all with the line segments; when that leaves no - // line for some curved segment, the loop stays as it is. A loop whose points are all in line - // keeps the lines of the refit. + // samples, up to `MAX_RUN_RESULT` lines in all with the line segments; when those do not keep + // some curved segment within the tolerance, the loop stays as it is. A loop whose points are + // all in line keeps the lines of the refit. let near = |c: &CubicBez| [c.p1, c.p2].iter().all(|&p| Line::new(c.p0, c.p3).nearest(p, 1e-9).distance_sq.sqrt() <= opts.tolerance); let curved = segs.iter().filter(|s| !s.line).count(); for k in 1..=10u32 { @@ -184,8 +185,11 @@ fn simplify_subpath(sp: &SubPath, opts: &SimplifyOptions) -> Option { lines.push(Seg::line(s.c.p0, s.c.p3)); continue; } + let Some(steps) = steps_within(&s.c, opts.tolerance.max(1e-6), room) else { + return Some(sp.clone()); + }; let mut pts = Vec::new(); - sample(&s.c, sample_steps(&s.c, opts.tolerance.max(1e-6)).min(room).max(1), &mut pts, true); + sample(&s.c, steps, &mut pts, true); lines.extend(pts.windows(2).map(|p| Seg::line(p[0], p[1]))); } return segs_to_subpath(&lines, true); @@ -206,6 +210,14 @@ fn sample_room(curved: usize, kept: usize) -> Option { Some((left / curved.max(1)).min(MAX_SEGMENT_SAMPLES)) } +/// How many evenly spaced lines along `c`, at most `room`, follow it: [`sample_steps`] when that +/// fits, or fewer, but never fewer than keep `c` within `tol` of them. `None` when those do not fit +/// in `room`. +fn steps_within(c: &CubicBez, tol: f64, room: usize) -> Option { + let need = line_steps(c, tol).max(1); + (need <= room).then(|| sample_steps(c, tol).min(room).max(need)) +} + /// How far a segment may be from the lines between its samples, as a share of the tolerance. const SAMPLE_GAP: f64 = 0.005; @@ -1182,6 +1194,27 @@ mod tests { assert_eq!(sample_room(1, MAX_RUN_RESULT + 5), None); } + #[test] + fn lines_with_too_little_room_for_the_tolerance_are_not_used() { + let c = CubicBez::new((0.0, 0.0), (0.0, 100.0), (100.0, 100.0), (100.0, 0.0)); + let tol = 0.01; + let need = line_steps(&c, tol); + assert!(need > 4, "{need}"); + assert_eq!(steps_within(&c, tol, need - 1), None); + for room in [need, need + 3, MAX_SEGMENT_SAMPLES] { + let steps = steps_within(&c, tol, room).unwrap_or_else(|| panic!("room {room}: no steps")); + assert!((need..=room).contains(&steps), "room {room}: {steps} steps"); + let mut pts = Vec::new(); + sample(&c, steps, &mut pts, true); + let lines: Vec = pts.windows(2).map(|p| Line::new(p[0], p[1])).collect(); + for i in 0..=1000 { + let p = c.eval(f64::from(i) / 1000.0); + let gap = lines.iter().map(|l| l.nearest(p, 1e-9).distance_sq.sqrt()).fold(f64::INFINITY, f64::min); + assert!(gap <= tol + 1e-9, "room {room}, {steps} steps: {gap} at {i}"); + } + } + } + #[test] fn smoothing_points_whose_arc_length_overflows_returns_every_point() { let pts: Vec = (0..40).map(|i| Point::new(if i % 2 == 0 { -1e308 } else { 1e308 }, f64::from(i))).collect(); From 7bd559cb1dbaec61f0014cc8b7567f09ec9a35f4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 14:47:18 -0800 Subject: [PATCH 10/38] Docs: PDF/A files at PDF 1.4 write long pages in points A PDF/A file at PDF 1.4 has no UserUnit, so a page longer than 14,400 pt is written in points with or without longPagesInPoints. The param text, docs/mcp.md and the exporter comment now say that only PDF/A files at PDF 1.5 and later keep the UserUnit. --- crates/engine/src/cmd/fileio/pdf.rs | 4 ++-- crates/pdf/src/export/entry.rs | 5 +++-- docs/mcp.md | 6 ++++-- 3 files changed, 9 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/fileio/pdf.rs b/crates/engine/src/cmd/fileio/pdf.rs index a18af48af1..2e42ab94e6 100644 --- a/crates/engine/src/cmd/fileio/pdf.rs +++ b/crates/engine/src/cmd/fileio/pdf.rs @@ -99,7 +99,7 @@ pub(crate) const OPTIONS: &[FormatOption] = &[ name: "longPagesInPoints", ty: "boolean", default: "false", - description: "a page with a side longer than 14,400 pt (200 in) is written at its size in points, without a UserUnit, at every PDF version, in files without a standard (PDF/A files keep the UserUnit)", + description: "a page with a side longer than 14,400 pt (200 in) is written at its size in points, without a UserUnit, at every PDF version, in files without a standard (PDF/A files from 1.5 on keep the UserUnit)", }, FormatOption { name: "createLayers", @@ -128,7 +128,7 @@ pub fn specs() -> Vec { "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), 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; 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; PDF/X files, 1.3 and 1.4 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?: false (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), 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, 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)|all|destination|taggedSource (documents assigned a profile: edit.assignProfile) (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), 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", + "{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), 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; 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; PDF/X files, 1.3 and 1.4 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?: false (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 from 1.5 on keep the UserUnit); apps that keep to the limit cut it to 200 in), 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, 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)|all|destination|taggedSource (documents assigned a profile: edit.assignProfile) (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), 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", has_doc, export_pdf ), diff --git a/crates/pdf/src/export/entry.rs b/crates/pdf/src/export/entry.rs index d6fb01a07c..a53394f0f0 100644 --- a/crates/pdf/src/export/entry.rs +++ b/crates/pdf/src/export/entry.rs @@ -199,8 +199,9 @@ fn writes_user_units(set: &PdfSettings) -> bool { } /// `long_pages_in_points` is on in a file without a standard. PDF/X files write long pages in -/// points anyway, and PDF/A files keep the `UserUnit`, which keeps their page boundaries within -/// 14,400 units (ISO 19005-2, 6.1.13). +/// points anyway, and PDF/A files from PDF 1.5 on keep the `UserUnit`, which keeps their page +/// boundaries within 14,400 units (ISO 19005-2, 6.1.13). A PDF/A file at PDF 1.4 has no +/// `UserUnit` and writes long pages in points either way. fn long_pages_in_points(set: &PdfSettings) -> bool { set.long_pages_in_points && set.standard == Standard::None } diff --git a/docs/mcp.md b/docs/mcp.md index 771f11ccdd..4a875123ed 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -878,8 +878,10 @@ keeps PDF 1.5's encryption (128-bit RC4). PDF/X files and PDF 1.3 and 1.4 files that keep to the limit cut it to 200 in. `longPagesInPoints: true` (off by default; "Write pages longer than 200 in at full size in points" in the Save PDF dialog's General section) writes such a page in points at every PDF version, without a `UserUnit`, and a PDF 1.5 file stays PDF 1.5; the warning then says the page is written in points. The option applies -only to files without a standard: PDF/X files write such a page in points anyway, and PDF/A files keep the `UserUnit`, -which keeps their page boundaries within PDF/A-2's limit of 14,400 units (ISO 19005-2, 6.1.13). The dialog disables the +only to files without a standard: PDF/X files write such a page in points anyway, and PDF/A files at PDF 1.5 and later keep +the `UserUnit`, which keeps their page boundaries within PDF/A-2's limit of 14,400 units (ISO 19005-2, 6.1.13). A PDF/A +file at PDF 1.4 writes such a page in points, as other PDF 1.4 files do, so its page boundaries are longer than that +limit. The dialog disables the checkbox when a standard is chosen. In PDF 1.3 and 1.4 files, PDF/X-1a and PDF/X-3 among them, a real number can be at most 32,767, and whole numbers are written as integers: a page longer than 32,767 pt whose sides aren't whole numbers of points fails the export with an error naming the page before the thumbnails are drawn and the transparency is From 3fda7ad83e5773b30314c39e57bd8f1df8585a1e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 14:51:21 -0800 Subject: [PATCH 11/38] Actions: Batch shows the data set File Name row only where it applies The Batch dialog showed File Name for every destination when Play was Data Sets, though only Destination Folder writes a file named from it. The row now shows after Destination Folder for Data Sets with a folder destination, and the dialog sends datasetFileNaming only then. The chosen value stays in the dialog while another destination is picked. action.batch and its default for an omitted datasetFileNaming are unchanged. --- crates/ui-egui/src/dialogs/action_batch.rs | 71 +++++++++++++++++----- docs/mcp.md | 3 +- docs/target-app-parity.md | 1 + 3 files changed, 60 insertions(+), 15 deletions(-) diff --git a/crates/ui-egui/src/dialogs/action_batch.rs b/crates/ui-egui/src/dialogs/action_batch.rs index 4e8a3bfae8..61ef75c5e1 100644 --- a/crates/ui-egui/src/dialogs/action_batch.rs +++ b/crates/ui-egui/src/dialogs/action_batch.rs @@ -66,14 +66,6 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { form::check(ui, d, "includeSubdirs", "Include All Subdirectories"); } else { ui.label(egui::RichText::new(tl!("Uses every data set of the open document.")).size(11.5).color(t.text_dim)); - form::choice( - ui, - d, - "datasetFileNaming", - "File Name:", - (LABEL, 200.0), - &[("fileNumber", "File + Number"), ("fileDataSetName", "File + Data Set Name"), ("dataSetName", "Data Set Name")], - ); } ui.add_space(8.0); @@ -86,6 +78,16 @@ fn body(app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool { } }); } + if names_data_set_files(d) { + form::choice( + ui, + d, + "datasetFileNaming", + "File Name:", + (LABEL, 200.0), + &[("fileNumber", "File + Number"), ("fileDataSetName", "File + Data Set Name"), ("dataSetName", "Data Set Name")], + ); + } ui.add_space(6.0); widgets::subheader(ui, tl!("Overrides")); form::check(ui, d, "overrideOpen", "Override Action \"Open\" Commands"); @@ -160,7 +162,8 @@ fn params(d: &Dialog, action_name: &str, commands: Vec) -> Value { }); if source == "folder" { params["folder"] = json!(d.str("folder")); - } else if source == "datasets" { + } + if names_data_set_files(d) { params["datasetFileNaming"] = json!(d.str("datasetFileNaming")); } if destination == "folder" { @@ -169,14 +172,22 @@ fn params(d: &Dialog, action_name: &str, commands: Vec) -> Value { params } +/// Whether the File Name choice names the batch's output: a Data Sets source with a +/// destination folder. With None or Save and Close the dialog sends no folder, so no file +/// takes the data set's name. +fn names_data_set_files(d: &Dialog) -> bool { + d.str("source") == "datasets" && d.str("destination") == "folder" +} + #[cfg(test)] mod tests { use super::*; use vectorcraft_engine::Session; - fn shown(source: &str) -> Vec { + fn shown(source: &str, destination: &str) -> Vec { let mut d = Dialog::new(KIND, initial_fields(0, 0, "Test")); d.fields["source"] = json!(source); + d.fields["destination"] = json!(destination); render(&mut d) } @@ -205,11 +216,35 @@ mod tests { labels } + /// The File Name row's caption and its selected choice (the dropdown shows only that one). + const NAMING: [&str; 2] = ["File Name:", "File + Number"]; + #[test] - fn file_name_choice_shows_only_for_data_sets() { - assert!(shown("datasets").iter().any(|label| label == "File Name:")); - assert!(shown("datasets").iter().any(|label| label == "File + Number")); - assert!(!shown("folder").iter().any(|label| label == "File Name:")); + fn file_name_choice_shows_only_for_data_sets_into_a_folder() { + for source in ["folder", "datasets"] { + for destination in ["none", "saveAndClose", "folder"] { + let labels = shown(source, destination); + let expected = source == "datasets" && destination == "folder"; + for text in NAMING { + assert_eq!(labels.iter().any(|label| label == text), expected, "{source} to {destination}, {text}: {labels:?}"); + } + } + } + } + + #[test] + fn file_name_choice_comes_back_after_another_destination() { + let mut d = Dialog::new(KIND, initial_fields(0, 0, "Test")); + d.fields["source"] = json!("datasets"); + d.fields["datasetFileNaming"] = json!("dataSetName"); + for (destination, shown) in [("folder", true), ("none", false), ("saveAndClose", false), ("folder", true)] { + d.fields["destination"] = json!(destination); + let labels = render(&mut d); + assert_eq!(labels.iter().any(|label| label == "File Name:"), shown, "{destination}: {labels:?}"); + assert_eq!(labels.iter().any(|label| label == "Data Set Name"), shown, "{destination}: {labels:?}"); + assert_eq!(d.str("datasetFileNaming"), "dataSetName", "{destination}"); + } + assert_eq!(params(&d, "Test", vec![])["datasetFileNaming"], "dataSetName"); } /// Batch plays an action recorded with a key its command no longer reads, as Play does. @@ -240,6 +275,14 @@ mod tests { d.fields["datasetFileNaming"] = json!(choice); assert_eq!(params(&d, "Test", vec![])["datasetFileNaming"], choice); } + d.fields["datasetFileNaming"] = json!("dataSetName"); + for destination in ["none", "saveAndClose"] { + d.fields["destination"] = json!(destination); + let p = params(&d, "Test", vec![]); + assert!(p.get("datasetFileNaming").is_none(), "{destination}: {p}"); + assert!(p.get("destinationFolder").is_none(), "{destination}: {p}"); + } + d.fields["destination"] = json!("folder"); d.fields["source"] = json!("folder"); assert!(params(&d, "Test", vec![]).get("datasetFileNaming").is_none()); } diff --git a/docs/mcp.md b/docs/mcp.md index 5826c5c8c4..7df361b4eb 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -4443,7 +4443,8 @@ Save for Office Documents included) that writes a file and that the batch does n warning. For a Data Sets source, `datasetFileNaming?: fileNumber | fileDataSetName | dataSetName` chooses File + Number (`source001`), File + Data Set Name (`source_Alpha`), or Data Set Name (`Alpha`). An omitted parameter keeps File + Data Set Name -for existing callers; the dialog starts with File + Number. A folder source ignores this parameter. The folder +for existing callers; the dialog starts with File + Number, and shows and sends the choice only when Destination is +Folder. A folder source ignores this parameter. The folder destination and overridden Save/Export paths use the chosen stem with the output format's extension. An empty data set name under Data Set Name falls back to the document stem plus its three-digit ordinal. Batch writes `/`, `\`, `:`, `<`, `>`, `"`, `|`, `?`, `*` and control characters in the data set's name as `-`, and adds the next free `-2`, diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index b4c949f742..a48091a270 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -715,6 +715,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Actions panel: the panel menu's Duplicate copies the selected action, else the current action set with all its actions ([Actions panel overview](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/actions-panel-overview.html); `ui.actionSet.duplicate`). VectorCraft's own rules, which the overview does not cover: the copy goes right after the original, is named after it with " copy" added and is selected. - Batch… over data sets names each file after the document and the data set (`action.batch`). It writes `/`, `\`, `:`, `<`, `>`, `"`, `|`, `?`, `*` and control characters in the data set's name as `-`, and adds `-2`, `-3`… to a name an earlier data set used. - Batch… offers File + Number, File + Data Set Name, and Data Set Name for a Data Sets source. The dialog defaults to File + Number; `action.batch` without `datasetFileNaming` keeps File + Data Set Name. An output already in a destination folder the batch may read and write gets the next free `-2`, `-3` suffix. [Batch options](https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/batch-options.html). + - The Batch dialog shows its data set File Name row only when Destination is Folder, and keeps the choice while another destination is picked. With None or Save and Close it does not send `datasetFileNaming`. - Batch… over data sets offers None, Save and Close and Folder as the destination, as for a folder source. Save and Close saves the open document over its own file after each data set, so the file keeps only the last data set, unless a recorded Save step that Override Save points into the destination folder first makes each data set's file the document's own. A recorded Save, Save a Copy, Save as Template or export step that writes a file and that the batch does not point into the destination folder (destination None, Override Save or Override Export off, or a copy, template, PDF, EPS, DXF, Save for Web or Save for Office Documents step) also writes the same file for every data set. In either case the dialog shows a warning and `action.batch` returns a `warning`. Unless a recorded Save or Save As step writes a file and makes it the document's own first, `action.batch` refuses Save and Close over the data sets of a document that was never saved, was converted from an older version or was restored by Data Recovery. - Export for Screens: the dialog's Example line shows the path of the file the export writes first, sub-folder included, named as the export names it, for the first chosen artboard, asset, layer or object (`document.exportForScreens`). - Export presets: the Asset Export panel menu lists the export presets of Export for Screens, with Import Preset… and Export Preset…, which read and write `.vcexportpresets` files (`document.exportPresets.import`, `document.exportPresets.export`). An imported preset whose name is taken gets a number. In the panel, a preset applies to the shared export settings (`assets.settings.set {exportPreset}`), and Save Preset… saves them. With Create Sub-folders off, the panel's Export writes every file into the folder itself, mobile and density rows included. From 634b9c7ff86c9fe8c00f1cf52b7f5fd18dd6767d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 14:55:46 -0800 Subject: [PATCH 12/38] Objects on Path: the Move All widget slides every attached object along the path With one Objects on Path group selected whose objects have room to move, the Selection and Objects on Path tools show a diamond below the first object. Dragging it moves every object along the path together, keeping the distances between them (object.objectsOnPath.options with start), in one undo step; Escape cancels it, and the first object's distance along the path shows next to the pointer. On an open path the widget shows only when the distance from the first object to the last is shorter than the path, and the objects stop at its ends; on a closed path they go on round across the first anchor. Where Auto or a Space value the open path is too short for sets the distance, the drag also sets spacing to the distance as drawn. --- crates/tools/src/cursors.toml | 1 + crates/tools/src/objects_on_path.rs | 448 ++++++++++++++++++++++++-- crates/tools/src/select.rs | 27 +- crates/ui-egui/src/canvas/overlays.rs | 16 +- crates/ui-egui/src/canvas/tests.rs | 39 +++ docs/mcp.md | 12 + docs/target-app-parity.md | 3 +- 7 files changed, 514 insertions(+), 32 deletions(-) diff --git a/crates/tools/src/cursors.toml b/crates/tools/src/cursors.toml index c5b0f52327..13e98ec4ee 100644 --- a/crates/tools/src/cursors.toml +++ b/crates/tools/src/cursors.toml @@ -102,6 +102,7 @@ shown_when = [ "The Artboard tool inside an artboard.", "The Gradient tool over the annotator's handles and during most gradient drags.", "The Perspective Grid and Perspective Selection over plane widgets and handles.", + "Selection and Objects on Path over an Objects on Path group's Move All widget, and while dragging it.", ] hotspot = "The centre." look = "A four-way move cursor." diff --git a/crates/tools/src/objects_on_path.rs b/crates/tools/src/objects_on_path.rs index fe5a8b9215..c2f90d0bef 100644 --- a/crates/tools/src/objects_on_path.rs +++ b/crates/tools/src/objects_on_path.rs @@ -20,13 +20,22 @@ //! one. The distance shows next to the pointer in the document's units, the drag is previewed and //! kept as one undo step on release, and Escape cancels it. //! +//! The Move All widget: with one Objects on Path group selected whose objects have room to move +//! along its path, the same tools show a diamond beyond the group's first object, below it. +//! Dragging it along the path moves every object along it as far, keeping the distances between +//! them (`object.objectsOnPath.options` with `start`). On an open path, the widget shows only when +//! the distance from the first object to the last is shorter than the path, and the objects stop +//! at its ends; on a closed path they go on round across its first anchor. The first object's +//! distance along the path shows next to the pointer in the document's units, the drag is +//! previewed and kept as one undo step on release, and Escape cancels it. +//! //! Behavior: , //! . use serde_json::{Value, json}; use vectorcraft_doc::blend::Spine; -use vectorcraft_doc::objects_on_path::{CENTER, ObjectsOnPath, attachable_path, is_objects_on_path, layout, nth_length, path_length, stop}; -use vectorcraft_doc::{Document, NodeId, Selection}; +use vectorcraft_doc::objects_on_path::{CENTER, Member, ObjectsOnPath, attachable_path, is_objects_on_path, layout, nth_length, path_length, stop}; +use vectorcraft_doc::{Document, Node, NodeId, Selection}; use vectorcraft_geom::{BezPath, Point, Vec2}; use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; @@ -51,6 +60,14 @@ pub const SPACE_HALF_PX: f32 = 3.5; /// How near (screen px) the pointer must be to hit the Space widget. const SPACE_HIT_PX: f64 = 6.0; +/// The Move All widget's center sits this far (screen px) beyond the first object, on the side its +/// bottom faces. +const MOVE_ALL_OFFSET_PX: f64 = 16.0; +/// Half the diagonal of the Move All widget's diamond (screen px), as the canvas draws it. +pub const MOVE_ALL_HALF_PX: f32 = 4.5; +/// How near (screen px) the pointer must be to hit the Move All widget. +const MOVE_ALL_HIT_PX: f64 = 6.0; + /// The Objects on Path group the widgets show for at `zoom` (screen px per document point), with /// its record, its children and its path: only when the selection is that one editable group, on /// a path with length, and no anchors are Direct-Selected. @@ -73,6 +90,30 @@ fn one_group<'a>( Some((*group, rec, children.as_slice(), path)) } +/// The direction the top of the object `m` faces: the -y direction of the frame it is drawn in +/// (the document's y axis points down), so a reflected or sheared frame turns it with the art's +/// top. A unit vector in the document's axes. +fn top(m: &Member) -> Vec2 { + let [_, _, a2, a3, _, _] = m.frame.as_coeffs(); + let len = a2.hypot(a3); + if len.is_finite() && len > 1e-12 { + Vec2::new(-a2 / len, -a3 / len) + } else { + let (sin, cos) = m.angle.sin_cos(); + Vec2::new(sin, -cos) + } +} + +/// The point `gap` (points) beyond the bounds of the object `m` (one of `children`), from its +/// attachment point `from` in the direction `dir`. `None` when it is not finite. +fn beside(doc: &Document, children: &[std::sync::Arc], m: &Member, from: Point, dir: Vec2, gap: f64) -> Option { + let b = children.iter().find(|c| c.id == m.id)?.geometric_bounds_with(&doc.symbol_boxes())?; + let corners = [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 reach = corners.iter().map(|c| (*c - from).dot(dir)).fold(0.0, f64::max); + let at = from + dir * (reach + gap); + (at.x.is_finite() && at.y.is_finite() && from.x.is_finite() && from.y.is_finite()).then_some(at) +} + /// The Rotate All widget of a selected Objects on Path group. #[derive(Clone, Copy, Debug, PartialEq)] pub struct RotateAllWidget { @@ -93,23 +134,8 @@ impl RotateAllWidget { let (group, rec, children, path) = one_group(doc, selection, zoom)?; let first = rec.members.first()?; let (pivot, _) = stop(path, rec.members.len(), rec.spacing, rec.start, 0)?; - let art = children.iter().find(|c| c.id == first.id)?; - let b = art.geometric_bounds_with(&doc.symbol_boxes())?; - // The object's top is the -y direction of the frame it is drawn in (the document's y axis - // points down), so a reflected or sheared frame moves the widget with the art's top. - let [_, _, a2, a3, _, _] = first.frame.as_coeffs(); - let len = a2.hypot(a3); - let up = if len.is_finite() && len > 1e-12 { - Vec2::new(-a2 / len, -a3 / len) - } else { - let (sin, cos) = first.angle.sin_cos(); - Vec2::new(sin, -cos) - }; - let corners = [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 reach = corners.iter().map(|c| (*c - pivot).dot(up)).fold(0.0, f64::max); - let at = pivot + up * (reach + ROTATE_ALL_OFFSET_PX / zoom); - let finite = at.x.is_finite() && at.y.is_finite() && pivot.x.is_finite() && pivot.y.is_finite(); - finite.then_some(Self { group, pivot, at, rotate: rec.rotate }) + let at = beside(doc, children, first, pivot, top(first), ROTATE_ALL_OFFSET_PX / zoom)?; + Some(Self { group, pivot, at, rotate: rec.rotate }) } /// The widget of `cx` when `p` is within reach of it. @@ -394,6 +420,160 @@ impl SpaceDrag { } } +/// The Move All widget of a selected Objects on Path group. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct MoveAllWidget { + pub group: NodeId, + /// The first object's attachment point, in the document. + pub first: Point, + /// The widget's center in the document. + pub at: Point, + /// The length of the path (points). + pub len: f64, + /// Is the path closed? + pub closed: bool, + /// Where the first object attaches along the path (points from its first anchor), as drawn. + pub start: f64, + /// The farthest along an open path the first object can attach with the others still on it + /// (points); the path's length on a closed path. + pub most: f64, + /// The Space value a drag sets with the start: the distance between the objects as drawn, when + /// the saved value would draw them apart differently from another start (Auto, or a Space value + /// an open path is too short for). `None` keeps the saved value. + pub gap: Option, + /// The group's start, as saved. + pub saved: f64, +} + +impl MoveAllWidget { + /// The widget of the selection at `zoom` (screen px per document point): only when the + /// selection is one editable Objects on Path group with at least one object on a path with + /// length, no anchors are Direct-Selected, and the objects have room to move: on an open path, + /// the distance from the first object to the last is shorter than the path. It sits beyond the + /// first object's bounds, on the side its bottom faces. + pub fn of(doc: &Document, selection: &Selection, zoom: f64) -> Option { + let (group, rec, children, path) = one_group(doc, selection, zoom)?; + let count = rec.members.len(); + let first = rec.members.first()?; + let (len, closed) = path_length(path)?; + let (start, gap) = layout(len, closed, count, rec.spacing, rec.start); + let most = if closed { len } else { len - gap * count.saturating_sub(1) as f64 }; + if !closed && (!most.is_finite() || most <= 1e-9) { + return None; + } + // On an open path, Auto and a Space value the path is too short for draw the objects apart + // by what is left of the path after the start, so another start would change the distance. + let keeps = closed || count < 2 || rec.spacing.is_some_and(|g| (g - gap).abs() < 1e-9); + let (at_first, _) = stop(path, count, rec.spacing, rec.start, 0)?; + let at = beside(doc, children, first, at_first, -top(first), MOVE_ALL_OFFSET_PX / zoom)?; + let finite = [len, start, most, rec.start].iter().all(|v| v.is_finite()); + finite.then_some(Self { group, first: at_first, at, len, closed, start, most, gap: (!keeps).then_some(gap), saved: rec.start }) + } + + /// The widget of `cx` when `p` is within reach of it. + fn at_point(cx: &ToolContext, p: Point) -> Option { + Self::of(cx.doc, cx.selection, cx.zoom).filter(|w| w.at.distance(p) <= cx.tol(MOVE_ALL_HIT_PX)) + } +} + +/// Is `p` over the Move All widget? +pub fn over_move_all(cx: &ToolContext, p: Point) -> bool { + MoveAllWidget::at_point(cx, p).is_some() +} + +/// Dragging the Move All widget: the distance the pointer moves along the path moves every object +/// along it as far, keeping the distances between them. On an open path the objects stop at its +/// ends, and on a closed path they go on round across its first anchor. +#[derive(Clone, Debug)] +pub struct MoveAllDrag { + widget: MoveAllWidget, + start: Point, + began: bool, + /// The distance along the path to the point nearest the pointer at the last drag (points). + last: f64, + /// Where the drag puts the first object along the path (points from its first anchor). + to: f64, + at: Point, +} + +impl MoveAllDrag { + /// The drag has left the click: the objects are moving. + pub fn adjusting(&self) -> bool { + self.began + } + + /// Start a drag when the press `ev` is on the Move All widget. + pub fn hit(cx: &ToolContext, ev: &PointerEvent) -> Option { + let widget = MoveAllWidget::at_point(cx, ev.pos)?; + let (_, last) = group_spine(cx.doc, widget.group)?.nearest(ev.pos, Some(widget.start))?; + last.is_finite().then_some(Self { widget, start: ev.pos, began: false, last, to: widget.start, at: ev.pos }) + } + + /// The pointer moved to `p`: move the first object as far along the path as the point nearest + /// the pointer moved, the shorter way round a closed path. On an open path it stays between + /// the first anchor and [`MoveAllWidget::most`], so moving back from beyond an end moves the + /// objects back at once. + fn follow(&mut self, doc: &Document, p: Point) { + let w = &self.widget; + let Some((_, t)) = group_spine(doc, w.group).and_then(|s| s.nearest(p, Some(self.last))) else { return }; + let step = if w.closed { (t - self.last + w.len / 2.0).rem_euclid(w.len) - w.len / 2.0 } else { t - self.last }; + if !t.is_finite() || !step.is_finite() { + return; + } + self.last = t; + self.to = if w.closed { + let s = (self.to + step).rem_euclid(w.len); + if s.is_finite() && s < w.len { s } else { 0.0 } + } else { + (self.to + step).clamp(0.0, w.most) + }; + } + + /// The pointer moved to `p`. + pub fn drag(&mut self, cx: &ToolContext, p: Point) -> Vec { + let mut out = vec![]; + if !self.began { + if p.distance(self.start) < cx.tol(3.0) { + return out; + } + self.began = true; + out.push(Action::Begin("Objects on Path Options".into())); + } + self.follow(cx.doc, p); + self.at = p; + let w = &self.widget; + // Where the objects stay as they are drawn, the group keeps its saved values. + let params = if (self.to - w.start).abs() < 1e-9 { + json!({ "ids": [w.group.0], "start": w.saved }) + } else if let Some(gap) = w.gap { + json!({ "ids": [w.group.0], "start": self.to, "spacing": gap }) + } else { + json!({ "ids": [w.group.0], "start": self.to }) + }; + out.push(Action::Preview("object.objectsOnPath.options".into(), params)); + out + } + + pub fn finish(self) -> Vec { + if self.began { vec![Action::Commit] } else { vec![] } + } + + /// The first object's distance along the path next to the pointer, in the document's units. + pub fn overlays(&self, cx: &ToolContext) -> Vec { + if !self.began || !cx.measurement_labels { + return vec![]; + } + vec![Overlay::Measure { p: self.at, text: cx.len(self.to) }] + } +} + +/// The path of the Objects on Path group `g` of `doc`, to measure along. +fn group_spine(doc: &Document, g: NodeId) -> Option { + let n = doc.node(g)?; + let rec = n.extras().objects_on_path.as_deref()?; + Spine::new(attachable_path(n.children()?.iter().find(|c| c.id == rec.path)?)?) +} + /// The path a click at `p` attaches the selected objects to: the path object hit there, when it can /// take objects, is in no Objects on Path group, is not a clipping path or part of a compound path, /// blend, envelope, repeat or Intertwine group ([`vectorcraft_doc::objects_on_path::held`]), and @@ -420,6 +600,8 @@ pub struct ObjectsOnPathTool { rotating: Option, /// The Space widget drag, while the button is down after a press on the widget. spacing: Option, + /// The Move All widget drag, while the button is down after a press on the widget. + moving: Option, /// The reference point of each object attached next (0-8, row by row from the top left). pivot: u8, /// The angle of each object attached next, in degrees counter-clockwise from upright on the path. @@ -428,7 +610,7 @@ pub struct ObjectsOnPathTool { impl Default for ObjectsOnPathTool { fn default() -> Self { - Self { hover: None, press: None, rotating: None, spacing: None, pivot: CENTER, rotate: 0.0 } + Self { hover: None, press: None, rotating: None, spacing: None, moving: None, pivot: CENTER, rotate: 0.0 } } } @@ -453,9 +635,16 @@ impl Tool for ObjectsOnPathTool { _ => vec![], }; } + if let Some(d) = &mut self.moving { + return match ev.kind { + PointerKind::Drag => d.drag(cx, p), + PointerKind::Up => self.moving.take().map(MoveAllDrag::finish).unwrap_or_default(), + _ => vec![], + }; + } match ev.kind { PointerKind::Move => { - self.hover = if over_rotate_all(cx, p) || over_space(cx, p) { None } else { target(cx, p) }; + self.hover = if over_rotate_all(cx, p) || over_space(cx, p) || over_move_all(cx, p) { None } else { target(cx, p) }; vec![] } PointerKind::Down => { @@ -469,6 +658,11 @@ impl Tool for ObjectsOnPathTool { self.hover = None; return vec![]; } + if let Some(d) = MoveAllDrag::hit(cx, ev) { + self.moving = Some(d); + self.hover = None; + return vec![]; + } self.press = Some(p); vec![] } @@ -492,14 +686,20 @@ impl Tool for ObjectsOnPathTool { if let Some(d) = &self.spacing { o.extend(d.overlays(cx)); } + if let Some(d) = &self.moving { + o.extend(d.overlays(cx)); + } o } fn cursor(&self, cx: &ToolContext, p: Point, _mods: Mods) -> Cursor { - if self.rotating.is_some() || (self.spacing.is_none() && over_rotate_all(cx, p)) { + let idle = self.spacing.is_none() && self.moving.is_none(); + if self.rotating.is_some() || (idle && over_rotate_all(cx, p)) { Cursor::Rotate - } else if self.spacing.is_some() || over_space(cx, p) { + } else if self.spacing.is_some() || (self.moving.is_none() && over_space(cx, p)) { Cursor::ArrowHollow + } else if self.moving.is_some() || over_move_all(cx, p) { + Cursor::Move } else if target(cx, p).is_some() { Cursor::ObjectsOnPath } else { @@ -508,14 +708,16 @@ impl Tool for ObjectsOnPathTool { } /// Escape while the button is down cancels the click, so the release attaches nothing, or the - /// Rotate All or Space drag, so the objects go back to the Rotate or Space they had. + /// Rotate All, Space or Move All drag, so the objects go back to the Rotate, Space or place + /// they had. fn key(&mut self, _cx: &ToolContext, key: ToolKey, _mods: Mods) -> Vec { if key == ToolKey::Escape { self.press = None; self.hover = None; let rotated = self.rotating.take().is_some_and(|d| d.adjusting()); let spaced = self.spacing.take().is_some_and(|d| d.adjusting()); - if rotated || spaced { + let moved = self.moving.take().is_some_and(|d| d.adjusting()); + if rotated || spaced || moved { return vec![Action::Cancel]; } } @@ -545,11 +747,13 @@ impl Tool for ObjectsOnPathTool { } fn busy(&self) -> bool { - self.press.is_some() || self.rotating.is_some() || self.spacing.is_some() + self.press.is_some() || self.rotating.is_some() || self.spacing.is_some() || self.moving.is_some() } fn transforming(&self) -> bool { - self.rotating.as_ref().is_some_and(RotateAllDrag::adjusting) || self.spacing.as_ref().is_some_and(SpaceDrag::adjusting) + self.rotating.as_ref().is_some_and(RotateAllDrag::adjusting) + || self.spacing.as_ref().is_some_and(SpaceDrag::adjusting) + || self.moving.as_ref().is_some_and(MoveAllDrag::adjusting) } } @@ -1056,6 +1260,196 @@ mod tests { assert_eq!(spaced(&t.pointer(&c, &ev(PointerKind::Drag, 1000.0, 100.0))), Some((400.0, 0.0)), "half way round at most"); } + /// The start a Move All drag's last action previews, to 1/1,000,000 pt, and whether it also + /// sets a Space value. + fn moved(acts: &[Action]) -> Option<(f64, Option)> { + let round = |v: f64| (v * 1e6).round() / 1e6 + 0.0; + match acts.last() { + Some(Action::Preview(cmd, p)) if cmd == "object.objectsOnPath.options" && p.get("rotate").is_none() => { + Some((round(p["start"].as_f64()?), p.get("spacing").and_then(Value::as_f64).map(round))) + } + _ => None, + } + } + + /// A document holding an Objects on Path group of one 20 × 20 square on the line from (0, 300) + /// to (400, 300), and a selection of the group. + fn single_doc() -> (Document, Selection) { + let mut d = Document::new(500.0, 500.0); + let l = d.layers[0].id; + let (line, a, g) = (d.alloc_id(), d.alloc_id(), d.alloc_id()); + let line = Node::path(line, shapes::line(Point::new(0.0, 300.0), Point::new(400.0, 300.0)), Appearance::default_art()); + let a = Node::path(a, shapes::rectangle(Rect::new(50.0, 50.0, 70.0, 70.0)), Appearance::default_art()); + let rec = vectorcraft_doc::objects_on_path::ObjectsOnPath::new(line.id, &[&a], CENTER, 0.0); + let mut group = Node::new(g, NodeKind::Group { children: vec![Arc::new(line), Arc::new(a)], clip: false }); + group.extras_mut().objects_on_path = Some(Box::new(rec)); + vectorcraft_doc::objects_on_path::place(&mut group, &Document::new(1.0, 1.0).symbol_boxes()); + d.insert(Some(l), 0, group).unwrap(); + let mut sel = Selection::default(); + sel.set([g]); + (d, sel) + } + + #[test] + fn the_move_all_widget_sits_below_the_first_object_when_the_objects_have_room() { + // Space 100 from 50: the first square spans 290 to 310 down the page, and the widget is + // 16 px below its bottom. The two objects take 100 pt of the 400 pt path, so the first + // one can go from 0 to 300 along it. + let (d, g, sel) = spaced_doc(Some(100.0), 50.0); + let w = MoveAllWidget::of(&d, &sel, 1.0).unwrap(); + assert_eq!(w.group, g); + assert!(near(w.first, Point::new(50.0, 300.0)) && near(w.at, Point::new(50.0, 326.0)), "{w:?}"); + assert!(w.start == 50.0 && (w.most - 300.0).abs() < 1e-9 && w.gap.is_none() && !w.closed, "{w:?}"); + assert!(near(MoveAllWidget::of(&d, &sel, 2.0).unwrap().at, Point::new(50.0, 318.0))); + // Auto spreads the objects from one end of an open path to the other: no room to move. + let (d, _, sel) = group_doc(0.0); + assert!(MoveAllWidget::of(&d, &sel, 1.0).is_none(), "Auto"); + // Nor with a Space value that reaches the end. + let (d, _, sel) = spaced_doc(Some(400.0), 0.0); + assert!(MoveAllWidget::of(&d, &sel, 1.0).is_none(), "the whole path"); + // On a closed path the objects always have room, Auto included. + let (d, sel) = path_doc(shapes::rectangle(Rect::new(100.0, 100.0, 300.0, 300.0)), None); + let w = MoveAllWidget::of(&d, &sel, 1.0).unwrap(); + assert!(w.closed && (w.most - 800.0).abs() < 1e-9 && w.gap.is_none(), "{w:?}"); + // One object on an open path can move along all of it. + let (d, sel) = single_doc(); + let w = MoveAllWidget::of(&d, &sel, 1.0).unwrap(); + assert!(w.start == 0.0 && (w.most - 400.0).abs() < 1e-9 && w.gap.is_none(), "{w:?}"); + // No widget for an object in the group, or for a locked group. + let (d, _, sel) = spaced_doc(Some(100.0), 50.0); + let children: Vec = d.node(sel.objects[0]).and_then(|n| n.children()).unwrap().iter().map(|c| c.id).collect(); + let mut one = Selection::default(); + one.set([children[1]]); + assert!(MoveAllWidget::of(&d, &one, 1.0).is_none()); + let (mut d, g, sel) = spaced_doc(Some(100.0), 50.0); + if let Some(n) = d.node_mut(g) { + n.locked = true; + } + assert!(MoveAllWidget::of(&d, &sel, 1.0).is_none()); + } + + /// Dragging the widget 80 pt along the path moves both objects 80 pt, keeping the Space, with + /// the Selection tool and with the Objects on Path tool, previewed while dragging and kept as + /// one undo step on release. On an open path the objects stop at its ends, and coming back + /// moves them back at once. + #[test] + fn dragging_the_move_all_widget_moves_every_object_along_the_path() { + let (d, g, sel) = spaced_doc(Some(100.0), 50.0); + let paint = paint(); + let c = cx(&d, &sel, &paint); + let at = MoveAllWidget::of(&d, &sel, 1.0).unwrap().at; + let tools: [Box; 2] = [Box::new(crate::select::SelectionTool::default()), Box::new(ObjectsOnPathTool::default())]; + for mut t in tools { + let id = t.id(); + assert_eq!(t.cursor(&c, at, Mods::default()), Cursor::Move, "{id}"); + assert!(t.pointer(&c, &ev(PointerKind::Down, at.x, at.y)).is_empty(), "{id}"); + let a = t.pointer(&c, &ev(PointerKind::Drag, at.x + 80.0, at.y + 10.0)); + assert_eq!(a.first(), Some(&Action::Begin("Objects on Path Options".into())), "{id}"); + assert!(matches!(a.last(), Some(Action::Preview(_, p)) if p["ids"] == json!([g.0])), "{a:?}"); + assert_eq!(moved(&a), Some((130.0, None)), "{id}: only the start changes"); + assert!(t.transforming() && t.cursor(&c, at, Mods::default()) == Cursor::Move, "{id}"); + let label = c.len(130.0); + assert!(t.overlays(&c).iter().any(|o| matches!(o, Overlay::Measure { text, .. } if *text == label)), "{id}"); + // Shift and Alt change nothing. + let mods = Mods { shift: true, alt: true, ..Mods::default() }; + assert_eq!(moved(&t.pointer(&c, &PointerEvent { mods, ..ev(PointerKind::Drag, at.x + 90.0, at.y) })), Some((140.0, None)), "{id}"); + // No further than where the last object reaches the end, and back at once. + assert_eq!(moved(&t.pointer(&c, &ev(PointerKind::Drag, at.x + 900.0, at.y))), Some((300.0, None)), "{id}"); + assert_eq!(moved(&t.pointer(&c, &ev(PointerKind::Drag, at.x + 880.0, at.y))), Some((280.0, None)), "{id}"); + assert_eq!(moved(&t.pointer(&c, &ev(PointerKind::Drag, at.x - 900.0, at.y))), Some((0.0, None)), "{id}"); + assert_eq!(t.pointer(&c, &ev(PointerKind::Up, at.x, at.y)), vec![Action::Commit], "{id}"); + assert!(!t.busy(), "{id}"); + // A click on the widget that does not move changes nothing. + assert!(t.pointer(&c, &ev(PointerKind::Down, at.x, at.y)).is_empty()); + assert!(t.pointer(&c, &ev(PointerKind::Up, at.x + 1.0, at.y)).is_empty(), "{id}"); + } + } + + /// Where the saved Space would draw the objects apart differently from another start (Auto, + /// or a value the path is too short for), the drag sets the distance as drawn with the start; + /// back where it began, the group keeps its saved values. + #[test] + fn a_move_all_drag_keeps_the_distance_the_objects_are_drawn_at() { + for (spacing, what) in [(Some(1000.0), "a Space value too large for the path"), (None, "Auto")] { + let (d, _, sel) = spaced_doc(spacing, 100.0); + let paint = paint(); + let c = cx(&d, &sel, &paint); + let w = MoveAllWidget::of(&d, &sel, 1.0).unwrap(); + assert!((w.most - 100.0).abs() < 1e-9 && w.gap == Some(300.0), "{what}: {w:?}"); + let mut t = ObjectsOnPathTool::default(); + t.pointer(&c, &ev(PointerKind::Down, w.at.x, w.at.y)); + assert_eq!(moved(&t.pointer(&c, &ev(PointerKind::Drag, w.at.x - 40.0, w.at.y))), Some((60.0, Some(300.0))), "{what}"); + let a = t.pointer(&c, &ev(PointerKind::Drag, w.at.x, w.at.y)); + assert_eq!(moved(&a), Some((100.0, None)), "{what}: back where it began"); + } + } + + /// On an L-shaped path the drag counts the distance along the path, round the corner. + #[test] + fn a_move_all_drag_follows_the_path_round_a_corner() { + let (d, sel) = corner_doc(Some(100.0)); + let paint = paint(); + let c = cx(&d, &sel, &paint); + let w = MoveAllWidget::of(&d, &sel, 1.0).unwrap(); + assert!(near(w.at, Point::new(0.0, 326.0)) && (w.most - 600.0).abs() < 1e-9, "{w:?}"); + let mut t = ObjectsOnPathTool::default(); + t.pointer(&c, &ev(PointerKind::Down, w.at.x, w.at.y)); + assert_eq!(moved(&t.pointer(&c, &ev(PointerKind::Drag, 200.0, 326.0))), Some((200.0, None))); + // Up the upright leg, 200 pt from the corner. + assert_eq!(moved(&t.pointer(&c, &ev(PointerKind::Drag, 426.0, 100.0))), Some((600.0, None)), "no further than the end"); + assert_eq!(moved(&t.pointer(&c, &ev(PointerKind::Drag, 426.0, 200.0))), Some((500.0, None))); + } + + /// On a closed path the objects go on round across the first anchor, both ways. + #[test] + fn a_move_all_drag_on_a_closed_path_goes_round_across_the_first_anchor() { + // The square's outline is 800 pt round, from (100, 100) to the right. + let (d, sel) = path_doc(shapes::rectangle(Rect::new(100.0, 100.0, 300.0, 300.0)), Some(100.0)); + let paint = paint(); + let c = cx(&d, &sel, &paint); + let w = MoveAllWidget::of(&d, &sel, 1.0).unwrap(); + assert!(near(w.first, Point::new(100.0, 100.0)) && near(w.at, Point::new(100.0, 126.0)), "{w:?}"); + let mut t = ObjectsOnPathTool::default(); + t.pointer(&c, &ev(PointerKind::Down, w.at.x, w.at.y)); + // Down the left side, back before the first anchor. + assert_eq!(moved(&t.pointer(&c, &ev(PointerKind::Drag, 100.0, 150.0))), Some((776.0, None))); + // Round the corner onto the top, ahead of it again. + assert_eq!(moved(&t.pointer(&c, &ev(PointerKind::Drag, 130.0, 100.0))), Some((56.0, None))); + } + + /// One object moves along all of an open path. + #[test] + fn a_move_all_drag_moves_a_single_object_to_the_end() { + let (d, sel) = single_doc(); + let paint = paint(); + let c = cx(&d, &sel, &paint); + let w = MoveAllWidget::of(&d, &sel, 1.0).unwrap(); + let mut t = crate::select::SelectionTool::default(); + t.pointer(&c, &ev(PointerKind::Down, w.at.x, w.at.y)); + assert_eq!(moved(&t.pointer(&c, &ev(PointerKind::Drag, w.at.x + 150.0, w.at.y))), Some((150.0, None))); + assert_eq!(moved(&t.pointer(&c, &ev(PointerKind::Drag, w.at.x + 600.0, w.at.y))), Some((400.0, None))); + } + + /// Escape during a Move All drag cancels it: the readout is removed, and the release keeps + /// nothing. + #[test] + fn escape_cancels_a_move_all_drag() { + let (d, _, sel) = spaced_doc(Some(100.0), 50.0); + let paint = paint(); + let c = cx(&d, &sel, &paint); + let at = MoveAllWidget::of(&d, &sel, 1.0).unwrap().at; + let tools: [Box; 2] = [Box::new(crate::select::SelectionTool::default()), Box::new(ObjectsOnPathTool::default())]; + for mut t in tools { + t.pointer(&c, &ev(PointerKind::Down, at.x, at.y)); + assert!(moved(&t.pointer(&c, &ev(PointerKind::Drag, at.x + 40.0, at.y))).is_some()); + assert_eq!(t.key(&c, ToolKey::Escape, Mods::default()), vec![Action::Cancel], "{}", t.id()); + assert!(!t.busy() && !t.transforming(), "{}", t.id()); + assert!(!t.overlays(&c).iter().any(|o| matches!(o, Overlay::Measure { .. })), "{}", t.id()); + assert!(t.pointer(&c, &ev(PointerKind::Drag, at.x, at.y)).is_empty(), "{}", t.id()); + assert!(t.pointer(&c, &ev(PointerKind::Up, at.x, at.y)).is_empty(), "{}: the release keeps nothing", t.id()); + } + } + /// Escape during a Space drag cancels it: the readout is removed, and the release keeps /// nothing. #[test] diff --git a/crates/tools/src/select.rs b/crates/tools/src/select.rs index 8dbdb461ea..1658346127 100644 --- a/crates/tools/src/select.rs +++ b/crates/tools/src/select.rs @@ -47,7 +47,7 @@ use vectorcraft_geom::{Affine, Point, Rect, Vec2}; use crate::bbox::{Handle, hit_handle, in_rotate_zone, move_delta, rotate_for_drag, scale_for_drag}; use crate::corners::{self, CornerDrag, over_widget}; use crate::guides::{PointSnap, Targets, distance_guides, hold_on_path}; -use crate::objects_on_path::{RotateAllDrag, SpaceDrag, over_rotate_all, over_space}; +use crate::objects_on_path::{MoveAllDrag, RotateAllDrag, SpaceDrag, over_move_all, over_rotate_all, over_space}; use crate::pathtype::{self, BracketDrag, over_bracket}; use crate::pie::{self, PieDrag}; use crate::rulerguide::GuideEdit; @@ -133,6 +133,8 @@ enum State { RotateAll(RotateAllDrag), /// Dragging an Objects on Path group's Space widget. Space(SpaceDrag), + /// Dragging an Objects on Path group's Move All widget. + MoveAll(MoveAllDrag), /// Move or rotate a live mirror axis. Mirror(crate::mirror::MirrorDrag), /// Drag a grid repeat's row, column or corner handle or a spacing slider. @@ -751,7 +753,7 @@ impl Tool for SelectionTool { /// E during a marquee drag switches the marquee between the objects it touches and only the /// objects inside it. Escape during a drag (a move or an Alt-drag copy, a bounding-box scale or - /// rotation, a marquee, a corner widget, a pie widget, the Rotate All or Space widget, the brackets of type on a path, a mirror + /// rotation, a marquee, a corner widget, a pie widget, the Rotate All, Space or Move All widget, the brackets of type on a path, a mirror /// axis, a grid repeat's handles, a ruler guide) cancels it: what it changed goes back, no copy /// is left, and the tool waits for the next press. With the pointer loaded with text, Escape /// drops the text. @@ -842,6 +844,7 @@ impl Tool for SelectionTool { State::Pie(d) => d.adjusting(), State::RotateAll(d) => d.adjusting(), State::Space(d) => d.adjusting(), + State::MoveAll(d) => d.adjusting(), State::Bracket(b) => b.adjusting(), State::Mirror(d) => d.adjusting(), State::GridRepeat(d) => d.adjusting(), @@ -1030,6 +1033,15 @@ impl Tool for SelectionTool { self.state = State::Idle; d.finish() } + (PointerKind::Drag, State::MoveAll(mut d)) => { + let out = d.drag(cx, p); + self.state = State::MoveAll(d); + out + } + (PointerKind::Up, State::MoveAll(d)) => { + self.state = State::Idle; + d.finish() + } (PointerKind::Drag, State::Bracket(mut b)) => { let out = b.drag(cx, p, m.cmd); self.state = State::Bracket(b); @@ -1094,6 +1106,7 @@ impl Tool for SelectionTool { State::Pie(d) => o.extend(d.overlays(cx)), State::RotateAll(d) => o.extend(d.overlays(cx)), State::Space(d) => o.extend(d.overlays(cx)), + State::MoveAll(d) => o.extend(d.overlays(cx)), State::Loaded { press: Some((start, cur)), .. } => o.push(Overlay::Marquee(Rect::from_points(*start, *cur))), _ => {} } @@ -1145,6 +1158,7 @@ impl Tool for SelectionTool { State::Pie(_) => return Cursor::ArrowHollow, State::RotateAll(_) => return Cursor::Rotate, State::Space(_) => return Cursor::ArrowHollow, + State::MoveAll(_) => return Cursor::Move, State::Bracket(_) => return Cursor::PathBracket, State::Loaded { .. } => return Cursor::LoadedText, _ => {} @@ -1170,6 +1184,9 @@ impl Tool for SelectionTool { if over_space(cx, p) { return Cursor::ArrowHollow; } + if over_move_all(cx, p) { + return Cursor::Move; + } if over_bracket(cx, p) { return Cursor::PathBracket; } @@ -1519,7 +1536,7 @@ impl SelectionTool { self.state = State::Loaded { from, before: port == crate::text::Port::In, press: None }; return Some(vec![]); } - // 1. Live Corners widgets, pie widgets, the Rotate All and Space widgets and type on a path's brackets, then the + // 1. Live Corners widgets, pie widgets, the Rotate All, Space and Move All widgets and type on a path's brackets, then the // bounding-box handles of the current selection. if let Some(c) = CornerDrag::hit(cx, ev, false) { self.state = State::Corner(c); @@ -1537,6 +1554,10 @@ impl SelectionTool { self.state = State::Space(d); return Some(vec![]); } + if let Some(d) = MoveAllDrag::hit(cx, ev) { + self.state = State::MoveAll(d); + return Some(vec![]); + } if let Some(b) = BracketDrag::hit(cx, ev) { self.state = State::Bracket(b); return Some(vec![]); diff --git a/crates/ui-egui/src/canvas/overlays.rs b/crates/ui-egui/src/canvas/overlays.rs index fcda53def0..8570b87448 100644 --- a/crates/ui-egui/src/canvas/overlays.rs +++ b/crates/ui-egui/src/canvas/overlays.rs @@ -238,7 +238,7 @@ pub(super) fn selection_overlay(app: &mut VectorcraftApp, p: &egui::Painter, xf: rotate_all_widget(p, xf, tool, &st.doc, &st.selection); } -/// The Rotate All and Space widgets (Selection and Objects on Path tools, one Objects on Path +/// The Rotate All, Space and Move All widgets (Selection and Objects on Path tools, one Objects on Path /// group selected). The Rotate All widget is joined by a line to the first object's attachment /// point. It stays while dragged. fn rotate_all_widget(p: &egui::Painter, xf: &Xf, tool: &str, doc: &vectorcraft_doc::Document, selection: &vectorcraft_doc::Selection) { @@ -253,6 +253,7 @@ fn rotate_all_widget(p: &egui::Painter, xf: &Xf, tool: &str, doc: &vectorcraft_d p.circle_stroke(c, ROTATE_ALL_RADIUS_PX, Stroke::new(1.0, color)); } space_widget(p, xf, doc, selection); + move_all_widget(p, xf, doc, selection); } /// The Space widget (beside the Rotate All widget, with two or more objects on the path): a square @@ -267,6 +268,19 @@ fn space_widget(p: &egui::Painter, xf: &Xf, doc: &vectorcraft_doc::Document, sel p.rect_stroke(r, 0.0, Stroke::new(1.0, color), StrokeKind::Inside); } +/// The Move All widget (beside the Rotate All widget, when the objects have room to move along the +/// path): a diamond below the first object joined by a line to its attachment point. It stays while +/// dragged. +fn move_all_widget(p: &egui::Painter, xf: &Xf, doc: &vectorcraft_doc::Document, selection: &vectorcraft_doc::Selection) { + use vectorcraft_tools::objects_on_path::{MOVE_ALL_HALF_PX, MoveAllWidget}; + let Some(w) = MoveAllWidget::of(doc, selection, xf.zoom) else { return }; + let (on, c, color) = (xf.to_screen(w.first), xf.to_screen(w.at), c32(doc.layer_color(w.group))); + let h = MOVE_ALL_HALF_PX; + p.line_segment([on, c], Stroke::new(1.0, color)); + let corners = vec![c + vec2(0.0, -h), c + vec2(h, 0.0), c + vec2(0.0, h), c + vec2(-h, 0.0)]; + p.add(Shape::convex_polygon(corners, Color32::WHITE, Stroke::new(1.0, color))); +} + /// Record where the Type tool's IME candidate window goes this pass, if it has an editor. /// /// The descriptor itself is observed once at the end of the pass (`crate::ime::end_of_pass`), diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index efe59c127e..1e83c87ec6 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -4806,6 +4806,45 @@ fn a_selected_objects_on_path_group_shows_its_space_widget() { assert_eq!(widgets(&mut app), 0, "one object"); } +/// A selected Objects on Path group whose objects have room to move along the path shows its Move +/// All widget, a white diamond below its first object, with the Selection and Objects on Path tools; +/// objects spread evenly to both ends of an open path have no room, and show none. +#[test] +fn a_selected_objects_on_path_group_shows_its_move_all_widget_when_it_has_room() { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.session.execute("file.new", &json!({"width": 400, "height": 300})).unwrap(); + let id = |v: serde_json::Value| v["id"].as_u64().unwrap(); + let line = id(app.session.execute("shape.line", &json!({"x1": 20, "y1": 200, "x2": 380, "y2": 200})).unwrap()); + let a = id(app.session.execute("shape.rectangle", &json!({"x": 40, "y": 40, "width": 20, "height": 20})).unwrap()); + let b = id(app.session.execute("shape.rectangle", &json!({"x": 80, "y": 40, "width": 20, "height": 20})).unwrap()); + app.run("select.set", json!({"ids": [a, b]})).unwrap(); + let g = id(app.session.execute("object.objectsOnPath.attach", &json!({"path": line})).unwrap()); + let ctx = egui::Context::default(); + // A diamond: its top and bottom corners one above the other, its full height apart. + let diamond = |d: &egui::epaint::PathShape| { + let h = 2.0 * vectorcraft_tools::objects_on_path::MOVE_ALL_HALF_PX; + let [top, _, bottom, _] = d.points[..] else { return false }; + d.closed && d.fill == Color32::WHITE && top.x == bottom.x && (bottom.y - top.y - h).abs() < 1e-3 + }; + let widgets = |app: &mut VectorcraftApp| shapes(app, &ctx).iter().filter(|s| matches!(s, Shape::Path(d) if diamond(d))).count(); + app.select_tool("selection"); + assert_eq!(widgets(&mut app), 0, "Auto: the objects reach both ends"); + app.session.execute("object.objectsOnPath.options", &json!({"ids": [g], "spacing": 60})).unwrap(); + assert_eq!(widgets(&mut app), 1); + app.select_tool("objectsOnPath"); + assert_eq!(widgets(&mut app), 1); + app.select_tool("directSelection"); + assert_eq!(widgets(&mut app), 0); + app.select_tool("selection"); + app.run("select.set", json!({"ids": [a]})).unwrap(); + assert_eq!(widgets(&mut app), 0, "an object in the group, not the group"); + // One object can move along the path whatever its Space. + app.session.execute("object.objectsOnPath.options", &json!({"ids": [g], "spacing": "auto"})).unwrap(); + app.run("edit.clear", json!({"ids": [b]})).unwrap(); + app.run("select.set", json!({"ids": [g]})).unwrap(); + assert_eq!(widgets(&mut app), 1, "one object"); +} + /// The shapes Type → Show Hidden Characters draws in one frame, seen through `xf`. fn hidden_chars(app: &mut VectorcraftApp, ctx: &egui::Context, xf: &Xf) -> Vec { let raw = egui::RawInput { screen_rect: Some(xf.rect), ..Default::default() }; diff --git a/docs/mcp.md b/docs/mcp.md index 5826c5c8c4..2a26c8523c 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -8160,6 +8160,18 @@ than the end. With Alt (Option on macOS) held, the objects spread from both ends open path, or of the first anchor of a closed path, up to the whole path. With measurement labels on, the distance between the objects shows next to the pointer in the document's units. Escape cancels the drag. +When the objects have room to move along the path, the same tools show the Move All widget, a diamond below the +group's first object joined by a line to its attachment point. On an open path that is when the distance from the first +object to the last is shorter than the path: one object, or a Space value that leaves part of the path free, but not +Auto from the first anchor, which spreads the objects to both ends. On a closed path the widget always shows. Dragging +it moves every object along the path as far as the pointer moves along the path, keeping the distances between them, +and previews `object.objectsOnPath.options {ids: [group], start}` and keeps it as one undo step on release. On an open +path the objects stop where the first one reaches the first anchor or the last one reaches the end, and moving the +pointer back moves them back at once; on a closed path they go on round across the first anchor. Where Auto or a Space +value the open path is too short for sets the distance, the drag also sets `spacing` to the distance as drawn, so the +objects stay that far apart. Shift and Alt do not change the drag. With measurement labels on, the first object's +distance along the path shows next to the pointer in the document's units. Escape cancels the drag. + ```json {"name":"run_command","arguments":{"command":"tool.setOption","params":{"tool":"objectsOnPath","values":{"pivot":7,"rotate":30}}}} {"name":"run_command","arguments":{"command":"object.objectsOnPath.attach","params":{"path":30,"ids":[12,15,18]}}} diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index b4c949f742..825d066a6e 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1251,8 +1251,9 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur When the object the Blend tool picked first is deleted or undone away before the second click, the next click on an object picks that object first instead of doing nothing. Regression tests: `blend_tool_picks_again_when_its_first_pick_is_gone` in `meshblend.rs` and `the_blend_tool_picks_again_when_its_first_pick_is_deleted` in `tests/blendopts.rs`. Window › Blend opens the Blend panel: Make, the selected blend's Spacing and Orientation (with no blend selected, the options new blends start with), Reverse Front to Back, Reverse Spine, Replace Spine, Expand and Release, each running its Object › Blend command. Make is dimmed until two or more objects are selected. Spacing and Orientation are dimmed until a blend or two or more objects are selected, and the other buttons are dimmed until a blend is selected. With the Blend tool, Escape drops the object clicked first and stops the next click adding to the blend just made, so the next click picks a new first object; the document and the selection stay as they are. Regression tests: `escape_drops_the_blend_tools_first_pick` in `meshblend.rs` and `tests/blendopts.rs`. - Objects on Path (#2545): a click with the Objects on Path tool (in Edit Toolbar's Modify section and the Blend tool's flyout; Object › Objects on Path › Attach and the context menu with two or more objects selected choose it) attaches the selected objects to the path clicked, open or closed, in an Objects on Path group with the path at its bottom. The objects go along the path column by column from left to right, spread evenly from its first anchor (the last one sits on the end of an open path), each turned to the path at its attachment point; Pivot and Rotate set where each one attaches and how far it tilts (`object.objectsOnPath.attach`, `object.objectsOnPath.options`), and with Objects on Path groups selected the Properties panel's Objects on Path Options section shows them as a nine-point Pivot grid and a Rotate field with common angles, each change one undo step for every selected group. Editing the path moves the objects, an object moved on its own goes back, objects moved into or out of the group in the Layers panel join or leave the path, and Object › Objects on Path › Expand leaves a plain group. The group saves and reopens live and exports as plain art. With one Objects on Path group selected, the Selection and Objects on Path tools show the Rotate All widget beside its first object: dragging it turns every object about its attachment point by the angle the pointer turns, adding it to the group's Rotate in one undo step, in 15° steps with Shift ([Objects on Path](https://helpx.adobe.com/illustrator/using/objects-on-path.html)). The Move All and Select/Move widgets and Detach are missing. + Objects on Path (#2545): a click with the Objects on Path tool (in Edit Toolbar's Modify section and the Blend tool's flyout; Object › Objects on Path › Attach and the context menu with two or more objects selected choose it) attaches the selected objects to the path clicked, open or closed, in an Objects on Path group with the path at its bottom. The objects go along the path column by column from left to right, spread evenly from its first anchor (the last one sits on the end of an open path), each turned to the path at its attachment point; Pivot and Rotate set where each one attaches and how far it tilts (`object.objectsOnPath.attach`, `object.objectsOnPath.options`), and with Objects on Path groups selected the Properties panel's Objects on Path Options section shows them as a nine-point Pivot grid and a Rotate field with common angles, each change one undo step for every selected group. Editing the path moves the objects, an object moved on its own goes back, objects moved into or out of the group in the Layers panel join or leave the path, and Object › Objects on Path › Expand leaves a plain group. The group saves and reopens live and exports as plain art. With one Objects on Path group selected, the Selection and Objects on Path tools show the Rotate All widget beside its first object: dragging it turns every object about its attachment point by the angle the pointer turns, adding it to the group's Rotate in one undo step, in 15° steps with Shift ([Objects on Path](https://helpx.adobe.com/illustrator/using/objects-on-path.html)). The Select/Move widget and Detach are missing. Objects on Path Space widget: with one Objects on Path group of two or more objects selected, the Selection and Objects on Path tools show a square handle beyond its last object; dragging it along the path, round its bends, sets the distance between the objects' attachment points in one undo step, the first object staying where it is, and with Alt (Option on macOS) the objects spread from both ends toward the center; the distance shows next to the pointer during the drag, in the document's units ([Rearrange and edit objects on a path](https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/rearrange-and-edit-objects-on-a-path.html), [Objects on Path](https://helpx.adobe.com/illustrator/using/objects-on-path.html)). The group keeps the distance (`object.objectsOnPath.options {spacing, start}`) through Pivot and Rotate changes, path edits, copies, saving and reopening, and scales it with the group; by default (`"auto"`) the objects are spread evenly as before. Evidence: `objects_on_path::tests::{space_sets_the_distance_between_the_stops, space_on_a_closed_path_wraps_at_the_first_anchor_and_stops_short_of_the_first_object}` in `crates/doc`, `tests::objects_on_path::space_sets_the_distance_between_the_objects_in_one_undo_step` in `crates/engine`, `objects_on_path::tests::dragging_the_space_widget_spaces_the_objects_from_the_first_one` in `crates/tools`. + Objects on Path Move All widget: with one Objects on Path group selected whose objects have room to move, the Selection and Objects on Path tools show a diamond below its first object; dragging it along the path, round its bends, moves every object along the path together in one undo step, keeping the distances between them (`object.objectsOnPath.options {start}`). On an open path the widget shows only when the distance from the first object to the last is shorter than the path, so not for objects spread evenly from end to end, and the objects stop at the path's ends; on a closed path they go on round across its first anchor. The first object's distance along the path shows next to the pointer during the drag, in the document's units ([Rearrange and edit objects on a path](https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/rearrange-and-edit-objects-on-a-path.html), [Objects on Path](https://helpx.adobe.com/illustrator/using/objects-on-path.html)). Evidence: `objects_on_path::tests::{dragging_the_move_all_widget_moves_every_object_along_the_path, a_move_all_drag_on_a_closed_path_goes_round_across_the_first_anchor}` in `crates/tools`, `canvas::tests::a_selected_objects_on_path_group_shows_its_move_all_widget_when_it_has_room` in `crates/ui-egui`. Double-clicking the Objects on Path tool opens Objects on Path Tool Options ([Objects on Path](https://helpx.adobe.com/illustrator/using/objects-on-path.html)): the nine-point Pivot grid and the Rotate field set the attachment point and angle of the objects attached next, and groups already attached keep theirs; Reset puts the center and 0° back. Save keeps the options across tool switches and saves them with the preferences (`tool.setOption {tool: "objectsOnPath"}`). - **Paint and appearance (M3):** - **CSS swatch libraries:** fractional linear and radial gradient stop positions are preserved, so nearby stops such as 12.5% and 12.890625% remain distinct instead of collapsing to 13%. Reference: [CSS Images 3 color stops](https://www.w3.org/TR/css-images-3/#color-stop-syntax). The original synthetic regression is `palette_io::tests::css_preserves_fractional_gradient_stop_positions` in `crates/color/src/palette_io.rs`. Scores and hours are unchanged. From 1618686224669a104b3a971f86651122f0db0d16 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 14:57:19 -0800 Subject: [PATCH 13/38] Path ops: rejoining split curves tests only the input curves around the run exact_merge looked at every input curve on each merge attempt, so tidying the output of a sweep cost the number of input curves for each joint it tried to remove. It now takes its candidates from Tidy::curves_around, the bounds index that repair already uses, and tests only the curves whose bounds hold both ends of the run. A new test cuts one curve of a 1,000-curve row in three and checks that the merge rebuilds it while testing at most four curves; before the change it tested 1,002. --- crates/pathops/src/boolean.rs | 34 ++++++++++++++++++++++++++++++---- 1 file changed, 30 insertions(+), 4 deletions(-) diff --git a/crates/pathops/src/boolean.rs b/crates/pathops/src/boolean.rs index e12c9fb395..60c2a8b296 100644 --- a/crates/pathops/src/boolean.rs +++ b/crates/pathops/src/boolean.rs @@ -22,6 +22,8 @@ thread_local! { pub(crate) static CONTOUR_PASSES: std::cell::Cell = const { std::cell::Cell::new(0) }; /// The sweeps [`normalize_bez`] made on this thread. static NORMALIZE_SWEEPS: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// The input curves [`exact_merge`] tested on this thread. + static EXACT_MERGE_CURVES: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Default curve-refit tolerance (document points) used to merge split curve pieces back together. @@ -663,16 +665,17 @@ fn try_merge(run: &[Seg], tidy: &Tidy) -> Option { } /// If every piece of `run` lies on one input cubic, return the exact sub-curve spanning the run. +/// Only the input curves whose bounds hold both ends of the run are tested +/// ([`Tidy::curves_around`]). fn exact_merge(run: &[Seg], tidy: &Tidy) -> Option { use kurbo::{ParamCurve, ParamCurveNearest}; let a = run[0].c.p0; let b = run[run.len() - 1].c.p3; let scale = 1.0 + a.x.abs().max(a.y.abs()).max(b.x.abs()).max(b.y.abs()); let tol = 1e-6 * scale; - for (r, c) in &tidy.curves { - if !r.contains(a) || !r.contains(b) { - continue; - } + for c in tidy.curves_around(a, b) { + #[cfg(test)] + EXACT_MERGE_CURVES.with(|n| n.set(n.get() + 1)); let na = c.nearest(a, 1e-12); let nb = c.nearest(b, 1e-12); if na.distance_sq.sqrt() > tol || nb.distance_sq.sqrt() > tol { @@ -1366,6 +1369,29 @@ mod tests { assert_eq!(tidy.repair(&lens), lens); } + #[test] + fn rejoining_a_split_curve_tests_only_the_curves_around_it() { + // A row of 1,000 short curves; one of them is cut in three, as the sweep cuts a curve. + let mut row = BezPath::new(); + row.move_to((0.0, 0.0)); + for k in 0..1000 { + let x = f64::from(k); + row.curve_to((x + 0.3, 1.0), (x + 0.7, 1.0), (x + 1.0, 0.0)); + } + let tidy = Tidy::keeping(DEFAULT_PRECISION, [&row]); + let c = CubicBez::new((500.0, 0.0), (500.3, 1.0), (500.7, 1.0), (501.0, 0.0)); + let pieces: Vec = [0.0..0.3, 0.3..0.6, 0.6..1.0].into_iter().map(|t| Seg { c: c.subsegment(t), line: false }).collect(); + EXACT_MERGE_CURVES.with(|n| n.set(0)); + let merged = tidy_segments(pieces, false, &tidy); + let tested = EXACT_MERGE_CURVES.with(std::cell::Cell::get); + assert_eq!(merged.len(), 1); + for (got, want) in [(merged[0].c.p1, c.p1), (merged[0].c.p2, c.p2)] { + assert!(got.distance(want) < 1e-9, "{got:?} {want:?}"); + } + // Each merge attempt tests the curves whose bounds hold both ends of the run, not all 1,000. + assert!(tested <= 4, "{tested} curves tested"); + } + #[test] fn arrangement_new_budgeted_fails_on_complexity_and_open_paths() { let mut bp = BezPath::new(); From 7114de8ae5df8309d76469f7b689f65a9ee6637f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 15:23:08 -0800 Subject: [PATCH 14/38] Scripts: a missing file outside the script's folder is refused like an existing one A `File` or `Folder` for a missing path got "does not exist" even when the path led outside the script's folder, through a folder link or, on a file system where case matters, through a folder whose name differs from the script's folder only in case, while an existing file there was refused. A missing path is now refused unless the nearest folder above it that exists lies inside a granted folder. --- crates/engine/src/file_access.rs | 12 +++++++++++- crates/engine/src/tests/script_io.rs | 28 ++++++++++++++++++++++++++++ docs/mcp.md | 3 ++- 3 files changed, 41 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/file_access.rs b/crates/engine/src/file_access.rs index 27ebc9c40d..7114e6f13e 100644 --- a/crates/engine/src/file_access.rs +++ b/crates/engine/src/file_access.rs @@ -463,7 +463,10 @@ impl ScriptScope { let real = match std::fs::canonicalize(path) { Ok(real) => real, Err(e) if e.kind() == std::io::ErrorKind::NotFound => { - return Err(if std::fs::symlink_metadata(path).is_ok() { ScriptRead::Refused } else { ScriptRead::Missing }); + if std::fs::symlink_metadata(path).is_ok() || !self.missing_inside(path) { + return Err(ScriptRead::Refused); + } + return Err(ScriptRead::Missing); } Err(e) => return Err(ScriptRead::Failed(e.to_string())), }; @@ -473,6 +476,13 @@ impl ScriptScope { 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. + fn missing_inside(&self, path: &Path) -> bool { + path.ancestors().skip(1).find_map(|a| std::fs::canonicalize(a).ok()).is_some_and(|real| self.roots.iter().any(|r| inside(&real, r))) + } + /// What the file or folder at `path` is, located as [`ScriptScope::locate`] locates it. pub(crate) fn stat(&self, path: &Path) -> Result { let real = self.locate(path)?; diff --git a/crates/engine/src/tests/script_io.rs b/crates/engine/src/tests/script_io.rs index aae4810dad..7f3af701e0 100644 --- a/crates/engine/src/tests/script_io.rs +++ b/crates/engine/src/tests/script_io.rs @@ -153,6 +153,9 @@ fn script_file_link_escape_refused() { Folder.current.getFiles().map(function (f) { return f.name; }), new Folder('near').alias, new Folder('near').resolve().name]);", ); assert_eq!(log, json!([[false, null, DENIED, null, false, false, DENIED, ["inner", "main.jsx", "near", "own.txt"], true, "inner"]])); + // A missing file behind the link is refused like an existing one, so nothing tells them apart. + let log = logged(&base, "var n = new File('away/nope.txt'); vc.log([n.exists, n.open('r'), n.error]);"); + assert_eq!(log, json!([[false, false, DENIED]])); #[cfg(unix)] let made = |target: &Path, link: &Path| std::os::unix::fs::symlink(target, link).is_ok(); #[cfg(windows)] @@ -176,6 +179,31 @@ fn script_file_link_escape_refused() { let _ = std::fs::remove_dir_all(base); } +/// A path whose names differ from the script's folder only in case is that folder where case does +/// not matter, and outside it where case matters, whether or not the file is there. +#[test] +fn script_file_case_variant_folder() { + let base = folder("case"); + write(&base.join("main/own.txt"), b"own"); + let upper = base.join("MAIN"); + let source = |name: &str| { + let p = format!("{:?}", upper.join(name).to_string_lossy()); + format!("var f = new File({p}); vc.log([f.exists, f.open('r'), f.error]);") + }; + if upper.exists() { + // Case does not matter here: `MAIN` is the script's folder. + assert_eq!(logged(&base, &source("own.txt")), json!([[true, true, ""]])); + assert_eq!(logged(&base, &source("nope.txt")), json!([[false, false, "Script file does not exist"]])); + } else { + let denied = json!([[false, false, DENIED]]); + assert_eq!(logged(&base, &source("nope.txt")), denied, "MAIN does not exist"); + write(&upper.join("secret.txt"), b"secret"); + assert_eq!(logged(&base, &source("secret.txt")), denied); + assert_eq!(logged(&base, &source("nope.txt")), denied, "MAIN exists beside main"); + } + let _ = std::fs::remove_dir_all(base); +} + #[test] fn script_file_oversize_refused_before_read() { let base = folder("oversize"); diff --git a/docs/mcp.md b/docs/mcp.md index 5826c5c8c4..7f75de7c33 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -1837,7 +1837,8 @@ VectorCraft reads files by these rules of its own: line, the files must also be inside them. A path outside, a Windows network path (`\\host\share`) and a device path (`\\?\`, `\\.\`) are refused before anything is looked up: `exists` is `false`, the dates and `getFiles` give `null`, and `error` is `Script file access denied`. A path that leads out through a link or a junction is refused too, and - `getFiles` leaves such an entry out. + `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. - `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 files open at once; another `open` returns `false` with `Script has 256 files open` until one is closed. From aa73329a4039285b291f77d971cc1107cc21993c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 15:24:12 -0800 Subject: [PATCH 15/38] Document Info: Gradient Objects lists the objects painted with gradients The gradients category was titled Gradient Swatches and listed every gradient swatch, used or not. It is now Gradient Objects: one row per object filled or stroked with a gradient, named as the object is, with the gradients it uses (a linked swatch by name, else Linear gradient, Radial gradient or Freeform gradient). document.info adds gradientObjects and gradientNames, and Selection Only, Save and the Package report use the same rows. Gradient objects follow the rules Pattern Objects uses for paint that draws: hidden fills and strokes, strokes with no width, guides, compound path members' own paint, image paint without a shape and type that draws nothing are left out, and type whose characters carry a gradient is included. objects.gradients now counts the listed objects, so it no longer counts hidden or zero-width gradient paint and no longer misses type whose characters use a gradient. The duplicate Document Info Save line in docs/target-app-parity.md is removed. --- crates/engine/src/cmd/docinfo.rs | 268 ++++++++++++++++++++------ crates/engine/src/tests/package.rs | 2 +- crates/ui-egui/src/panels/doc_info.rs | 16 +- docs/mcp.md | 6 +- docs/target-app-parity.md | 2 +- 5 files changed, 226 insertions(+), 68 deletions(-) diff --git a/crates/engine/src/cmd/docinfo.rs b/crates/engine/src/cmd/docinfo.rs index cb1bb86fbd..7499e14943 100644 --- a/crates/engine/src/cmd/docinfo.rs +++ b/crates/engine/src/cmd/docinfo.rs @@ -18,7 +18,7 @@ pub fn specs() -> Vec { "Document Info", ["Window", "Document Info"], None, - "{selectionOnly?, category?: document|objects|graphicStyles|brushes|spotColors|patterns|gradients|symbols|fonts|fontDetails|linkedImages|embeddedImages|repeats (only that one in sections and the text), format?: \"text\" (→ {text}: the report Document Info › Save… and Package write)} → {document, objects: {paths, compoundPaths, groups, …}, pathLength: pt (the paths' total length, compound paths' included, guides left out), fonts, images, swatches, graphicStyleNames (with selectionOnly: the styles the selected objects are linked to), brushNames (the Brushes panel's brushes; with selectionOnly: the brushes the selected objects' strokes use), repeatObjects: [{id, name, type: radial|grid|mirror, instances, rows?, cols?}] (the Repeat objects, those in groups and other repeats included; with selectionOnly: those in the selection), patternObjects: [{id, name, patterns}] (the objects filled or stroked with a pattern, each once, those in groups and type whose drawn characters use one included, hidden fills and strokes, strokes with no width, guides, compound path members' own fills and strokes, images' fills and strokes without a shape and characters that draw nothing left out, with the patterns they use, which objects.patterns counts; with selectionOnly: those in the selection), patternNames (the patterns those objects use), …, sections: [{id, title, rows: [[label, value]]}] (the panel's categories; fontDetails: each font's file and whether its license lets it be embedded)}", + "{selectionOnly?, category?: document|objects|graphicStyles|brushes|spotColors|patterns|gradients|symbols|fonts|fontDetails|linkedImages|embeddedImages|repeats (only that one in sections and the text), format?: \"text\" (→ {text}: the report Document Info › Save… and Package write)} → {document, objects: {paths, compoundPaths, groups, …}, pathLength: pt (the paths' total length, compound paths' included, guides left out), fonts, images, swatches, graphicStyleNames (with selectionOnly: the styles the selected objects are linked to), brushNames (the Brushes panel's brushes; with selectionOnly: the brushes the selected objects' strokes use), repeatObjects: [{id, name, type: radial|grid|mirror, instances, rows?, cols?}] (the Repeat objects, those in groups and other repeats included; with selectionOnly: those in the selection), patternObjects: [{id, name, patterns}] (the objects filled or stroked with a pattern, each once, those in groups and type whose drawn characters use one included, hidden fills and strokes, strokes with no width, guides, compound path members' own fills and strokes, images' fills and strokes without a shape and characters that draw nothing left out, with the patterns they use, which objects.patterns counts; with selectionOnly: those in the selection), patternNames (the patterns those objects use), gradientObjects: [{id, name, gradients}] (the objects filled or stroked with a gradient, by the same rules, with the gradients they use: a linked gradient swatch's name, else Linear gradient, Radial gradient or Freeform gradient; objects.gradients counts them), gradientNames (the gradients those objects use), …, sections: [{id, title, rows: [[label, value]]}] (the panel's categories; fontDetails: each font's file and whether its license lets it be embedded)}", has_doc, info ), @@ -42,7 +42,7 @@ pub const CATEGORIES: [(&str, &str); 13] = [ ("brushes", "Brushes"), ("spotColors", "Spot Colors"), ("patterns", "Pattern Objects"), - ("gradients", "Gradient Swatches"), + ("gradients", "Gradient Objects"), ("symbols", "Symbols"), ("fonts", "Fonts"), ("fontDetails", "Font Details"), @@ -131,7 +131,8 @@ fn repeat_entry(d: &Document, n: &Node, spec: &RepeatSpec) -> (Value, (String, S /// The Document Info categories of `d` (only `category` when given) from `info` (what /// `document.info` reports), its fonts, its image objects, the rows of its Repeat objects and the -/// rows of its objects filled or stroked with a pattern. +/// rows of its objects filled or stroked with a pattern and with a gradient. +#[allow(clippy::too_many_arguments)] fn sections( d: &Document, info: &Value, @@ -139,6 +140,7 @@ fn sections( images: &[ImageRow], repeats: &[(String, String)], pattern_objects: &[(String, String)], + gradient_objects: &[(String, String)], category: Option<&str>, ) -> Vec
{ let names = |k: &str| -> Vec<(String, String)> { @@ -183,7 +185,7 @@ fn sections( "brushes" => names("brushNames"), "spotColors" => names("spotColors"), "patterns" => pattern_objects.to_vec(), - "gradients" => d.swatches_iter().filter(|s| matches!(s.paint, Paint::Gradient(_))).map(|s| (s.name.clone(), String::new())).collect(), + "gradients" => gradient_objects.to_vec(), "symbols" => names("symbols"), "fonts" => fonts.iter().map(|f| (super::fonts::font_label(f), String::new())).collect(), "fontDetails" => { @@ -254,19 +256,37 @@ pub fn report(s: &mut Session, selection_only: bool) -> Result { Ok(v["text"].as_str().unwrap_or_default().to_string()) } -/// The type object `n` holds and the runs its layout draws, when it uses a pattern: the runs with a -/// glyph outline (list markers and ruby included) or an underline or strikethrough bar. Spaces and -/// line breaks draw no outline. A type object's characters carry their own fill and stroke, and the -/// type object's own fills and strokes paint on its characters, so only those runs paint. The type -/// is laid out with its inline graphics' bounds resolved from `d`'s symbols, as the renderer lays it out. +/// The pattern paint `p` uses: the pattern's name. +fn pattern_label(p: &Paint) -> Option { + match p { + Paint::Pattern { pattern, .. } => Some(pattern.clone()), + _ => None, + } +} + +/// The gradient paint `p` uses: the name of the gradient swatch it is linked to, else its kind +/// ("Linear gradient", "Radial gradient" or "Freeform gradient"). +fn gradient_label(p: &Paint) -> Option { + match p { + Paint::Gradient(g) => Some(g.swatch.clone().filter(|s| !s.is_empty()).unwrap_or_else(|| format!("{} gradient", g.gradient.kind.label()))), + _ => None, + } +} + +/// The type object `n` holds and the runs its layout draws, when it uses a pattern or a gradient: +/// the runs with a glyph outline (list markers and ruby included) or an underline or strikethrough +/// bar. Spaces and line breaks draw no outline. A type object's characters carry their own fill and +/// stroke, and the type object's own fills and strokes paint on its characters, so only those runs +/// paint. The type is laid out with its inline graphics' bounds resolved from `d`'s symbols, as the +/// renderer lays it out. fn painted_runs<'a>(d: &Document, n: &'a Node) -> Option<(&'a vectorcraft_doc::TextObject, BTreeSet)> { let NodeKind::Text(t) = &n.kind else { return None }; - let is_pattern = |p: &Paint| matches!(p, Paint::Pattern { .. }); + let is_listed = |p: &Paint| matches!(p, Paint::Pattern { .. } | Paint::Gradient(_)); let own = n.appearance.items.iter().any(|i| match i { - vectorcraft_doc::AppearanceItem::Fill(f) => is_pattern(&f.paint), - vectorcraft_doc::AppearanceItem::Stroke(s) => is_pattern(&s.paint), + vectorcraft_doc::AppearanceItem::Fill(f) => is_listed(&f.paint), + vectorcraft_doc::AppearanceItem::Stroke(s) => is_listed(&s.paint), }); - if !own && !t.runs.iter().any(|r| is_pattern(&r.style.fill) || is_pattern(&r.style.stroke)) { + if !own && !t.runs.iter().any(|r| is_listed(&r.style.fill) || is_listed(&r.style.stroke)) { return None; } let db = vectorcraft_text::FontDb::global(); @@ -277,42 +297,38 @@ fn painted_runs<'a>(d: &Document, n: &'a Node) -> Option<(&'a vectorcraft_doc::T Some((t, painted)) } -/// The patterns `n`'s own fills and strokes paint, each once. A hidden fill or stroke and a stroke -/// with no width paint nothing, and neither does any fill or stroke of a guide (drawn in the guide -/// color), of a compound path's member (`members`: the compound path's own fills and strokes paint -/// it) or of type whose layout draws nothing (`painted_runs`). An image's fills and strokes paint -/// only where an effect gives them a shape. -fn own_patterns<'a>( +/// The patterns or gradients (`label`: [`pattern_label`] or [`gradient_label`]) that `n`'s own +/// fills and strokes paint, each once. A hidden fill or stroke and a stroke with no width paint +/// nothing, and neither does any fill or stroke of a guide (drawn in the guide color), of a compound +/// path's member (`members`: the compound path's own fills and strokes paint it) or of type whose +/// layout draws nothing (`painted_runs`). An image's fills and strokes paint only where an effect +/// gives them a shape. +fn own_paints( d: &Document, - n: &'a Node, + n: &Node, members: &HashSet<*const Node>, painted_runs: Option<&(&vectorcraft_doc::TextObject, BTreeSet)>, -) -> Vec<&'a str> { + label: fn(&Paint) -> Option, +) -> Vec { if matches!(n.kind, NodeKind::Path { guide: true, .. }) || members.contains(&std::ptr::from_ref(n)) || painted_runs.is_some_and(|(_, r)| r.is_empty()) + || !n.appearance.items.iter().any(|i| label(i.paint()).is_some()) { return vec![]; } - // The patterns an image's shaped fills and strokes paint (their effects can transform the - // pattern, so they are matched by name). - let shaped: Option> = matches!(n.kind, NodeKind::Image(_)).then(|| { - vectorcraft_render::effects::image_paint(Some(d), n) - .into_iter() - .filter_map(|(_, _, item)| match item.paint() { - Paint::Pattern { pattern, .. } => Some(pattern.clone()), - _ => None, - }) - .collect() - }); - let mut out: Vec<&str> = vec![]; + // The patterns or gradients an image's shaped fills and strokes paint (their effects can + // transform the paint, so they are matched by label). + let shaped: Option> = matches!(n.kind, NodeKind::Image(_)) + .then(|| vectorcraft_render::effects::image_paint(Some(d), n).into_iter().filter_map(|(_, _, item)| label(item.paint())).collect()); + let mut out: Vec = vec![]; for item in &n.appearance.items { - let Paint::Pattern { pattern, .. } = item.paint() else { continue }; + let Some(name) = label(item.paint()) else { continue }; let paints = item.visible() && !matches!(item, vectorcraft_doc::AppearanceItem::Stroke(s) if s.width <= 0.0) - && shaped.as_ref().is_none_or(|s| s.contains(pattern)); - if paints && !out.contains(&pattern.as_str()) { - out.push(pattern); + && shaped.as_ref().is_none_or(|s| s.contains(&name)); + if paints && !out.contains(&name) { + out.push(name); } } out @@ -354,6 +370,11 @@ fn info(s: &mut Session, p: &Value) -> Result { // `pattern_objects` and `pattern_rows` hold the `patternObjects` entries and the rows of the objects filled or stroked with a pattern, in walk order. let mut pattern_objects: Vec = vec![]; let mut pattern_rows: Vec<(String, String)> = vec![]; + // `gradient_objects`, `gradient_rows` and `gradients` hold the `gradientObjects` entries, the rows of the objects filled or stroked + // with a gradient, in walk order, and the gradients they use. + let mut gradient_objects: Vec = vec![]; + let mut gradient_rows: Vec<(String, String)> = vec![]; + let mut gradients = BTreeSet::new(); // The objects the walk has visited: a selection can hold a group and objects inside it, and each object counts once. // The set holds each object's address, so two objects that share an id (as a damaged file can hold) count as two. let mut seen: HashSet<*const Node> = HashSet::new(); @@ -412,27 +433,17 @@ fn info(s: &mut Session, p: &Value) -> Result { if let Some(k) = k { *counts.entry(k).or_default() += 1; } - // The paint kinds this object's fills and strokes use, each once. - let mut kinds = BTreeSet::new(); - // The patterns this object's fills and strokes use, each once. - let mut used_patterns: Vec<&str> = vec![]; - let painted_runs = painted_runs(d, n); - for pattern in own_patterns(d, n, &members, painted_runs.as_ref()) { - patterns.insert(pattern.to_string()); - used_patterns.push(pattern); - } for item in &n.appearance.items { - let paint = item.paint(); - // Objects counts an object with a pattern when Pattern Objects lists it, below. - if let Paint::Gradient(_) = paint { - kinds.insert("gradients"); - } - if let Paint::Solid { swatch: Some(name), .. } = paint + if let Paint::Solid { swatch: Some(name), .. } = item.paint() && d.swatch(name).is_some_and(|s| s.spot) { spot.insert(name.clone()); } } + // The patterns and the gradients this object's fills and strokes paint, each once. + let painted_runs = painted_runs(d, n); + let mut used_patterns = own_paints(d, n, &members, painted_runs.as_ref(), pattern_label); + let mut used_gradients = own_paints(d, n, &members, painted_runs.as_ref(), gradient_label); // The characters' own paints: an inline graphic draws no outline and does not take its // run's paint (a list marker set in its run does), and a stroke with no width paints // nothing. @@ -440,23 +451,32 @@ fn info(s: &mut Session, p: &Value) -> Result { for run in painted.iter().filter_map(|i| t.runs.get(*i)) { let stroke = (run.style.stroke_width > 0.0).then_some(&run.style.stroke); for paint in std::iter::once(&run.style.fill).chain(stroke) { - if let Paint::Pattern { pattern, .. } = paint { - patterns.insert(pattern.clone()); - if !used_patterns.contains(&pattern.as_str()) { - used_patterns.push(pattern); + for (used, label) in + [(&mut used_patterns, pattern_label as fn(&Paint) -> Option), (&mut used_gradients, gradient_label)] + { + if let Some(name) = label(paint) + && !used.contains(&name) + { + used.push(name); } } } } } + // Objects counts the objects that Pattern Objects and Gradient Objects list. if !used_patterns.is_empty() { let name = n.display_name(); + patterns.extend(used_patterns.iter().cloned()); + pattern_rows.push((name.clone(), used_patterns.join(", "))); pattern_objects.push(json!({ "id": n.id.0, "name": name, "patterns": used_patterns })); - pattern_rows.push((name, used_patterns.join(", "))); - kinds.insert("patterns"); + *counts.entry("patterns").or_default() += 1; } - for k in kinds { - *counts.entry(k).or_default() += 1; + if !used_gradients.is_empty() { + let name = n.display_name(); + gradients.extend(used_gradients.iter().cloned()); + gradient_rows.push((name.clone(), used_gradients.join(", "))); + gradient_objects.push(json!({ "id": n.id.0, "name": name, "gradients": used_gradients })); + *counts.entry("gradients").or_default() += 1; } if n.extras().mask.is_some() { *counts.entry("opacityMasks").or_default() += 1; @@ -506,10 +526,12 @@ fn info(s: &mut Session, p: &Value) -> Result { "patterns": d.patterns.len(), "patternNames": patterns, "patternObjects": pattern_objects, + "gradientNames": gradients, + "gradientObjects": gradient_objects, }); // The document's name: its file's, else its title. out["document"]["name"] = json!(st.title()); - let sections = sections(d, &out, &fonts, &image_rows, &repeat_rows, &pattern_rows, category); + let sections = sections(d, &out, &fonts, &image_rows, &repeat_rows, &pattern_rows, &gradient_rows, category); if text { return Ok(json!({ "text": report_text(&st.title(), selection_only, §ions) })); } @@ -583,12 +605,14 @@ mod tests { &json!({"gradient": {"kind": "linear", "stops": [{"offset": 0, "color": "#000"}, {"offset": 1, "color": "#fff"}]}}), ) .unwrap(); - s.execute("text.create", &json!({"x": 10, "y": 40, "text": "Hi"})).unwrap(); + let t = s.execute("text.create", &json!({"x": 10, "y": 40, "text": "Hi"})).unwrap()["id"].clone(); let i = s.execute("document.info", &json!({})).unwrap(); + // The type's characters take the current gradient fill, so it is a gradient object too. assert_eq!( (i["objects"]["paths"].as_u64(), i["objects"]["textObjects"].as_u64(), i["objects"]["gradients"].as_u64()), - (Some(1), Some(1), Some(1)) + (Some(1), Some(1), Some(2)) ); + assert_eq!((i["gradientObjects"][0]["id"].clone(), i["gradientObjects"][1]["id"].clone()), (r.clone(), t)); assert_eq!(i["fonts"][0], "Source Sans 3 Regular"); assert_eq!(i["document"]["artboards"][0]["width"], 200.0); s.execute("select.set", &json!({"ids": [r]})).unwrap(); @@ -842,6 +866,124 @@ mod tests { assert!(!text.contains("Unused"), "{text}"); } + /// Document Info › Gradient Objects lists each object filled or stroked with a gradient once, + /// with the gradients it uses (a linked swatch by name, else the gradient's kind), one in a + /// group and a type object whose characters use a gradient included; a gradient swatch no art + /// uses adds no row, paint that draws nothing is left out by the rules Pattern Objects follows, + /// and Objects counts the listed objects. With Selection Only it lists the objects in the + /// selection, each once, and the report writes the same rows. + #[test] + fn info_lists_the_gradient_objects() { + let mut s = Session::new(); + s.execute("file.new", &json!({"width": 400, "height": 400})).unwrap(); + let square = + |s: &mut Session, x: f64| s.execute("shape.rectangle", &json!({"x": x, "y": 0, "width": 10, "height": 10})).unwrap()["id"].clone(); + let ramp = |kind: &str| json!({"kind": kind, "stops": [{"offset": 0, "color": "#000"}, {"offset": 1, "color": "#fff"}]}); + s.execute("swatch.new", &json!({"name": "Ramp", "gradient": ramp("linear")})).unwrap(); + s.execute("swatch.new", &json!({"name": "Spare", "gradient": ramp("radial")})).unwrap(); + let (a, b, c, f) = (square(&mut s, 100.0), square(&mut s, 200.0), square(&mut s, 300.0), square(&mut s, 0.0)); + s.execute("paint.setFill", &json!({"ids": [a], "swatch": "Ramp"})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [a], "gradient": ramp("linear")})).unwrap(); + s.execute("layer.setProps", &json!({"id": a, "name": "Both"})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [b], "gradient": ramp("radial")})).unwrap(); + s.execute("paint.setFill", &json!({"ids": [f], "gradient": ramp("freeform")})).unwrap(); + s.execute("select.set", &json!({"ids": [b, c]})).unwrap(); + let group = s.execute("object.group", &json!({})).unwrap()["id"].clone(); + // A type object whose characters are filled with the gradient. + let t = s.execute("text.create", &json!({"x": 0, "y": 200, "text": "Hi"})).unwrap()["id"].clone(); + s.execute("paint.setFill", &json!({"ids": [t], "swatch": "Ramp"})).unwrap(); + s.execute("layer.setProps", &json!({"id": t, "name": "Type"})).unwrap(); + // A hidden gradient fill and a gradient stroke with no width paint nothing, so neither object is listed. + let (d, e) = (square(&mut s, 100.0), square(&mut s, 200.0)); + s.execute("paint.setStroke", &json!({"ids": [d], "none": true})).unwrap(); + s.execute("paint.setFill", &json!({"ids": [d], "swatch": "Ramp"})).unwrap(); + s.execute("appearance.setItem", &json!({"ids": [d], "index": 0, "visible": false})).unwrap(); + s.execute("paint.setFill", &json!({"ids": [e], "none": true})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [e], "gradient": ramp("linear")})).unwrap(); + s.execute("appearance.setItem", &json!({"ids": [e], "index": 1, "weight": 0})).unwrap(); + // Type with no characters, or of only spaces and a line break, paints nothing, and neither + // does a guide made from a path with a gradient. + let empty = s.execute("text.create", &json!({"x": 0, "y": 300, "text": ""})).unwrap()["id"].clone(); + s.execute("paint.setFill", &json!({"ids": [empty], "swatch": "Ramp"})).unwrap(); + s.execute("appearance.addFill", &json!({"ids": [empty]})).unwrap(); + let blank = s.execute("text.create", &json!({"x": 0, "y": 320, "text": " \n"})).unwrap()["id"].clone(); + s.execute("paint.setFill", &json!({"ids": [blank], "swatch": "Ramp"})).unwrap(); + let guide = square(&mut s, 300.0); + s.execute("paint.setFill", &json!({"ids": [guide], "swatch": "Ramp"})).unwrap(); + s.execute("select.set", &json!({"ids": [guide]})).unwrap(); + s.execute("view.guides.make", &json!({})).unwrap(); + // Nor does a compound path's member's own gradient fill, or an image's gradient fill + // without an effect that gives it a shape. + let (m1, m2) = (square(&mut s, 320.0), square(&mut s, 340.0)); + s.execute("select.set", &json!({"ids": [m1, m2]})).unwrap(); + let compound = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].clone(); + s.execute("paint.setFill", &json!({"ids": [compound], "color": "#000000"})).unwrap(); + s.execute("paint.setStroke", &json!({"ids": [compound], "none": true})).unwrap(); + let node = |s: &Session, id: &Value| s.doc().unwrap().doc.node(vectorcraft_doc::NodeId(id.as_u64().unwrap())).unwrap().clone(); + let (member, paint) = (node(&s, &compound).children().unwrap()[0].id, node(&s, &a).appearance); + let pic = square(&mut s, 360.0); + s.execute("select.set", &json!({"ids": [pic]})).unwrap(); + s.execute("object.rasterize", &json!({"ppi": 72})).unwrap(); + let image = s.doc().unwrap().selection.objects[0]; + s.edit("own paint", |d, _| { + d.node_mut(member).unwrap().appearance = paint.clone(); + d.node_mut(image).unwrap().appearance = paint; + Ok(()) + }) + .unwrap(); + // Underlined spaces draw a bar in the gradient, so that type object is listed. + let bar = s.execute("text.create", &json!({"x": 0, "y": 340, "text": " "})).unwrap()["id"].clone(); + s.execute("paint.setFill", &json!({"ids": [bar], "swatch": "Ramp"})).unwrap(); + s.execute("select.set", &json!({"ids": [bar]})).unwrap(); + s.execute("text.setFormat", &json!({"underline": true})).unwrap(); + s.execute("layer.setProps", &json!({"id": bar, "name": "Bar"})).unwrap(); + let i = s.execute("document.info", &json!({})).unwrap(); + assert_eq!( + i["gradientObjects"], + json!([ + {"id": a, "name": "Both", "gradients": ["Ramp", "Linear gradient"]}, + {"id": b, "name": "", "gradients": ["Radial gradient"]}, + {"id": f, "name": "", "gradients": ["Freeform gradient"]}, + {"id": t, "name": "Type", "gradients": ["Ramp"]}, + {"id": bar, "name": "Bar", "gradients": ["Ramp"]}, + ]) + ); + assert_eq!(i["gradientNames"], json!(["Freeform gradient", "Linear gradient", "Radial gradient", "Ramp"])); + // Objects counts the objects that Gradient Objects lists. + assert_eq!(i["objects"]["gradients"].as_u64(), Some(5), "{}", i["objects"]); + s.execute("select.set", &json!({"ids": [d, e, empty, blank, guide, compound, image.0]})).unwrap(); + let i = s.execute("document.info", &json!({"selectionOnly": true})).unwrap(); + assert!(i["objects"]["gradients"].is_null() && i["gradientObjects"] == json!([]), "{}", i["objects"]); + let i = s.execute("document.info", &json!({"category": "gradients"})).unwrap(); + assert_eq!((i["sections"][0]["id"].as_str(), i["sections"][0]["title"].as_str()), (Some("gradients"), Some("Gradient Objects"))); + assert_eq!( + i["sections"][0]["rows"], + json!([ + ["Both", "Ramp, Linear gradient"], + ["", "Radial gradient"], + ["", "Freeform gradient"], + ["Type", "Ramp"], + ["Bar", "Ramp"] + ]) + ); + // A selection that holds the group and the object inside it lists that object once. + for ids in [json!([group, b]), json!([b, group])] { + s.execute("select.set", &json!({"ids": ids})).unwrap(); + let i = s.execute("document.info", &json!({"selectionOnly": true, "category": "gradients"})).unwrap(); + assert_eq!(i["sections"][0]["rows"], json!([["", "Radial gradient"]]), "{ids}"); + assert_eq!(i["objects"]["gradients"].as_u64(), Some(1), "{ids}"); + } + s.execute("select.set", &json!({"ids": [t]})).unwrap(); + let i = s.execute("document.info", &json!({"selectionOnly": true, "category": "gradients"})).unwrap(); + assert_eq!((i["sections"][0]["rows"].clone(), i["gradientNames"].clone()), (json!([["Type", "Ramp"]]), json!(["Ramp"]))); + let text = s.execute("document.info", &json!({"category": "gradients", "format": "text"})).unwrap()["text"].as_str().unwrap().to_string(); + assert!( + text.contains("\nGRADIENT OBJECTS\nBoth: Ramp, Linear gradient\n: Radial gradient\n: Freeform gradient\nType: Ramp\nBar: Ramp\n"), + "{text}" + ); + assert!(!text.contains("Spare"), "{text}"); + } + /// Document Info › Objects counts an object with a gradient or a pattern on both its fill and /// its stroke once, and with Selection Only a selection that holds a group and an object inside /// it counts that object once. diff --git a/crates/engine/src/tests/package.rs b/crates/engine/src/tests/package.rs index e15258bec6..aeecc9fcc2 100644 --- a/crates/engine/src/tests/package.rs +++ b/crates/engine/src/tests/package.rs @@ -393,7 +393,7 @@ fn the_document_info_report_has_every_category() { "BRUSHES", "SPOT COLORS", "PATTERN OBJECTS", - "GRADIENT SWATCHES", + "GRADIENT OBJECTS", "SYMBOLS", "FONTS", "FONT DETAILS", diff --git a/crates/ui-egui/src/panels/doc_info.rs b/crates/ui-egui/src/panels/doc_info.rs index f6becb3911..4d6bf05ec1 100644 --- a/crates/ui-egui/src/panels/doc_info.rs +++ b/crates/ui-egui/src/panels/doc_info.rs @@ -1,6 +1,6 @@ //! Document Info panel: the document's setup and what it contains (objects by kind, graphic -//! styles, brushes, spot colors, patterns, gradients, symbols, fonts and their files, linked and embedded -//! images, repeat objects), for the whole document or the selection only. The flyout picks one category (or all) +//! styles, brushes, spot colors, objects painted with patterns and with gradients, symbols, fonts and their files, +//! linked and embedded images, repeat objects), for the whole document or the selection only. The flyout picks one category (or all) //! and saves the text report (`docInfo.save`, the report File → Package writes too). use egui::Ui; @@ -191,9 +191,20 @@ mod tests { menu_text.contains("Font Details") && menu_text.contains("Brushes") && menu_text.contains("Repeat Objects") + && menu_text.contains("Gradient Objects") && menu_text.contains("Save…"), "{menu_text}" ); + // Gradient Objects lists the objects painted with a gradient by name. + let r = app.session.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 30, "height": 20})).unwrap()["id"].clone(); + let ramp = json!({"kind": "radial", "stops": [{"offset": 0, "color": "#000"}, {"offset": 1, "color": "#fff"}]}); + app.session.execute("paint.setFill", &json!({"ids": [r], "gradient": ramp})).unwrap(); + app.session.execute("layer.setProps", &json!({"id": r, "name": "Glow"})).unwrap(); + let gradients = crate::tests_labels::painted_text(&mut app, |app, ui| { + set_pstate(ui.ctx(), "docinfo-category", "gradients".to_string()); + show(app, ui); + }); + assert!(gradients.contains("Gradient Objects (1)") && gradients.contains("Glow") && gradients.contains("Radial gradient"), "{gradients}"); let filtered = crate::tests_labels::painted_text(&mut app, |app, ui| { set_pstate(ui.ctx(), "docinfo-category", "fonts".to_string()); show(app, ui); @@ -210,6 +221,7 @@ mod tests { assert_eq!(r["path"], "/tmp/info.txt"); let report = String::from_utf8(written.borrow().clone()).unwrap(); assert!(report.starts_with("Document Info: ") && report.contains("\nFONT DETAILS\n") && report.contains("\nREPEAT OBJECTS\n"), "{report}"); + assert!(report.contains("\nGRADIENT OBJECTS\nGlow: Radial gradient\n"), "{report}"); } /// The report the panel menu's Save… writes with category `category` shown ("" for All diff --git a/docs/mcp.md b/docs/mcp.md index 5826c5c8c4..9604427327 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -5751,7 +5751,11 @@ whose drawn characters use a pattern included, hidden fills and strokes, strokes member's own fills and strokes, an image's fills and strokes that no Convert to Shape or Outline Object effect gives a shape, and characters that draw nothing (spaces and line breaks without an underline or strikethrough) left out, with the patterns it uses, which the patterns category lists as Pattern Objects and `objects.patterns` counts; with `selectionOnly`, those in the selection), -`patternNames` (the patterns those objects use) and `pathLength` (pt: the total length of the paths, compound paths' pieces included and guides left +`patternNames` (the patterns those objects use), `gradientObjects` (`[{id, name, gradients}]`: every object filled or +stroked with a gradient, by the same rules as `patternObjects`, with the gradients it uses: the name of the gradient +swatch a gradient is linked to, else `Linear gradient`, `Radial gradient` or `Freeform gradient`; the gradients category +lists them as Gradient Objects and `objects.gradients` counts them; gradient swatches no art uses are not listed; with +`selectionOnly`, those in the selection), `gradientNames` (the gradients those objects use) and `pathLength` (pt: the total length of the paths, compound paths' pieces included and guides left out, which objects lists as Path Length in the document's units, say for a cut line or an LED strip along the letters); `format: "text"` returns the plain-text report Document Info › Save… (`docInfo.save {path?, selectionOnly?, category?}`: only `category` when given, else every category) and the package report write. diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index b4c949f742..fdaf038e16 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1310,8 +1310,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Document Info has a Brushes category after Graphic Styles. It lists the Brushes panel's brushes, or with Selection Only it lists the brushes that the selected objects' strokes use. The Document Info report and Package's report list them too (`document.info {category: "brushes"}`, `brushNames`). Document Info has a Repeat Objects category after Embedded Images. It lists each radial, grid and mirror Repeat object by name with its kind and the number of instances it makes. For a grid it gives the rows and columns instead, followed by the number of instances it draws when that is fewer. With Selection Only it lists the Repeat objects in the selection. The Document Info report and Package's report list them too (`document.info {category: "repeats"}`, `repeatObjects`). Document Info's Pattern Objects category lists the objects whose fill or stroke is a pattern, the category the [Document Info panel](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/document-info-panel.html) page describes, each by name with the patterns it uses. With Selection Only it lists those in the selection, and the Document Info report and Package's report list them too (`document.info {category: "patterns"}`, `patternObjects`). Listing an object with a pattern fill and a pattern stroke once, listing objects inside groups and type objects whose characters use a pattern, and leaving out hidden fills and strokes, strokes with no width, guides, a compound path member's own fills and strokes, an image's fills and strokes without a shape, characters the type does not draw and patterns no art uses, and counting the listed objects in Objects, are VectorCraft's own rules. Test: `cmd::docinfo::tests::info_lists_the_pattern_objects` (vectorcraft-engine). + Document Info's Gradient Objects category lists the objects whose fill or stroke is a gradient, the category the [Document Info panel](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/document-info-panel.html) page describes as the count of objects with gradient fills or strokes. Each object is listed by name with the gradients it uses. With Selection Only it lists those in the selection, and the Document Info report and Package's report list them too (`document.info {category: "gradients"}`, `gradientObjects`). Naming a linked gradient by its swatch and any other gradient by its kind, and leaving out paint that draws nothing by the rules Pattern Objects follows, gradient swatches no art uses, gradient meshes and gradients drawn by effects, are VectorCraft's own rules. Objects counts the listed objects as Gradient Objects. Test: `cmd::docinfo::tests::info_lists_the_gradient_objects` (vectorcraft-engine). Document Info's Save… writes the category the panel shows, with Selection Only applied, as the [Document Info panel](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/document-info-panel.html) page describes ("Exports the selected category's visible information to a text file"). With All Categories shown it writes every category, which is VectorCraft's own rule (`docInfo.save {category}`). Test: `panels::doc_info::tests::save_writes_the_category_the_panel_shows`. - Document Info's Save… writes the category the panel shows, with Selection Only applied, as the [Document Info panel](https://helpx.adobe.com/illustrator/desktop/get-started/learn-the-basics/document-info-panel.html) page describes. With All Categories shown it writes every category, which is VectorCraft's own rule (`docInfo.save {category}`). Test: `panels::doc_info::tests::save_writes_the_category_the_panel_shows`. The Brushes panel menu's Select All Unused selects the brushes that are not used in the document, as the [Brushes](https://web.archive.org/web/20241230205225/https://helpx.adobe.com/illustrator/using/brushes.html) page (archived copy) describes. A brush counts as used when a stroke paints with it in the art (opacity masks included), in symbols, graph designs, pattern tiles or graphic styles, or in the art of a used brush (`brush.unused`). A rename in Brush Options and Delete Brush change every stroke that paints with the brush: in the layers and opacity masks, symbols, graph designs, pattern tiles, graphic styles and the art of other brushes. A rename gives those strokes the new name, and Delete Brush makes them plain strokes, in one undo step. In Pattern Brush Options, a menu below the Outer Corner Tile and the Inner Corner Tile sets each to the brush's own corner art (Original), None, or a tile made from the side tile: Auto-Centered stretches one side tile around the corner, Auto-Between bends a side tile on each side into the corner's diagonal, Auto-Sliced cuts a side tile on each side along the diagonal, and Auto-Overlap runs a side tile on each side past the corner. Auto-Sliced masks the tiles at the diagonal, so their outlines stay as drawn. Brushes saved without these choices draw their corners as before (`brush.options` `outer_source`, `inner_source`). Evidence: `tests::pattern_auto_corners_fill_each_corner_of_a_square`, `tests::pattern_corner_source_none_leaves_that_kind_of_corner_empty` (vectorcraft-brush), `dialogs::brush_options::tests::pattern_options_set_each_corner_tile_to_original_none_or_an_automatic_tile` (vectorcraft-ui-egui). From afe2a71e59a3d09942dcb6fa40241e2cb8ada9ff Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 15:03:07 -0800 Subject: [PATCH 16/38] Tests: the empty-params command sweeps leave plug-in caches alone every_command_survives_empty_params and read_only_commands_read_the_instance_of_a_picked_object run every command with {}. That includes plugin.clearCache, which without an id empties the cache of every plug-in installed in the process. When either sweep ran during plugin_storage_is_capped_and_survives_a_damaged_settings_file (called from plugins_keep_settings_and_a_cache_of_their_own_in_the_store), it deleted that test's cache entries Tile and tile. The test's st.clear_cache() == MAX_CACHE_BYTES + 3 assertion after the MAX_CACHE_SCAN folders then failed with 536870912 bytes freed. Both sweeps now leave plugin.clearCache out. tests/plugin_clear_cache.rs already runs it with {} in a test binary of its own. A new test runs the other plug-in commands with {} in the selection states that every_command_survives_empty_params uses, and checks that an installed plug-in's cache keeps its 3 bytes. --- crates/engine/src/lib.rs | 9 ++++++ crates/engine/src/tests.rs | 2 +- crates/engine/src/tests/dynamic_symbols.rs | 2 +- crates/engine/src/tests/plugins.rs | 34 ++++++++++++++++++++++ 4 files changed, 45 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 091348a6bd..c3eeaa2777 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -347,6 +347,15 @@ pub(crate) fn adding_fonts() -> std::sync::MutexGuard<'static, ()> { FONTS.lock().unwrap_or_else(std::sync::PoisonError::into_inner) } +/// Whether the tests that run every command with `{}` run command `id`. `plugin.clearCache` is +/// left out: without an id it empties the cache of every plug-in installed in the process, which +/// includes the caches that the plug-in storage tests check while they run. +/// `tests/plugin_clear_cache.rs` runs it with `{}` in a test binary of its own. +#[cfg(test)] +pub(crate) fn runs_with_empty_params(id: &str) -> bool { + id != "plugin.clearCache" +} + #[cfg(test)] use tests::{ adjust as tests_adjust, clip as tests_clip, colormgmt as tests_colormgmt, expand as tests_expand, large_edits as tests_large_edits, diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index ca0501c8f7..2cf0031a34 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -3160,7 +3160,7 @@ fn every_command_survives_empty_params() { // The view toggles among them flip the process-wide proof view. let _proof_view = crate::tests_colormgmt::GLOBAL.lock().unwrap_or_else(|e| e.into_inner()); for sel in [false, true] { - for c in command_specs() { + for c in command_specs().iter().filter(|c| crate::runs_with_empty_params(c.id)) { let mut s = session(); let a = rect(&mut s, 0.0, 0.0, 10.0, 10.0); rect(&mut s, 20.0, 0.0, 10.0, 10.0); diff --git a/crates/engine/src/tests/dynamic_symbols.rs b/crates/engine/src/tests/dynamic_symbols.rs index f4ae97bb14..278d979ef5 100644 --- a/crates/engine/src/tests/dynamic_symbols.rs +++ b/crates/engine/src/tests/dynamic_symbols.rs @@ -1309,7 +1309,7 @@ fn a_lent_selection_tool_moves_the_instance_of_a_picked_object() { #[test] fn read_only_commands_read_the_instance_of_a_picked_object() { let mut failures = Vec::new(); - for spec in crate::cmd::command_specs().iter().filter(|c| !c.journal) { + for spec in crate::cmd::command_specs().iter().filter(|c| !c.journal && crate::runs_with_empty_params(c.id)) { let mut s = session(); let inst = pair(&mut s, "dynamic"); s.execute("symbol.instance.selectPart", &json!({"id": inst.0, "path": [1]})).unwrap(); diff --git a/crates/engine/src/tests/plugins.rs b/crates/engine/src/tests/plugins.rs index a4be6e554f..dc52243e3a 100644 --- a/crates/engine/src/tests/plugins.rs +++ b/crates/engine/src/tests/plugins.rs @@ -3242,6 +3242,40 @@ fn removing_an_id_that_is_not_installed_deletes_its_storage() { assert!(s.execute("plugin.remove", &json!({"id": id})).is_err(), "nothing left to remove"); } +/// The `plugin.*` commands that the tests running every command with `{}` run +/// ([`crate::runs_with_empty_params`]) leave the cache of an installed plug-in as it is, so +/// those tests can run beside the ones here that check a cache. Each command runs with `{}` in a +/// document with two rectangles, one or both selected, as `every_command_survives_empty_params` +/// runs it. +#[test] +fn plugin_commands_run_with_empty_params_keep_other_plugins_caches() { + let folder = crate::tests_links::Folder::new("plugin-storage-empty-params"); + let id = "test.engine.storageemptyparams"; + let mut s = session(); + s.attach_plugin_store(folder.0.clone()); + install_storing(&mut s, id, WRITES); + run(&mut s, "plugin.run", json!({"id": id, "ids": []})); + assert_eq!(run(&mut s, "plugin.info", json!({"id": id}))["cacheBytes"], json!(3)); + let mut ran = vec![]; + for all in [false, true] { + for c in crate::cmd::command_specs().iter().filter(|c| c.id.starts_with("plugin.") && crate::runs_with_empty_params(c.id)) { + let mut other = session(); + let a = rect(&mut other, 10.0, "#ff0000"); + rect(&mut other, 40.0, "#0000ff"); + if all { + run(&mut other, "select.all", json!({})); + } else { + run(&mut other, "select.set", json!({"ids": [a.0]})); + } + let _ = other.execute(c.id, &json!({})); + ran.push(c.id); + assert_eq!(run(&mut s, "plugin.info", json!({"id": id}))["cacheBytes"], json!(3), "after {}", c.id); + } + } + assert!(ran.contains(&"plugin.list"), "{ran:?}"); + run(&mut s, "plugin.remove", json!({"id": id})); +} + /// The settings file and the cache are checked: a file that doesn't read is moved aside and the /// settings start empty; a write past a cap fails and changes nothing; cache entries whose names /// differ only in case are two files; a removed plug-in's storage takes no more writes. From e6add18663a01ce563f19e2698e6084eff6840b4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 15:02:23 -0800 Subject: [PATCH 17/38] Fix #6634: Pen closing drag no longer gives the first anchor symmetric handles Closing a path by dragging on its first anchor made that anchor smooth with symmetric handles, so the first segment bent along with the closing one. The drag now sets the first anchor's incoming handle to the mirror of the pointer. Its outgoing handle stays where it is on a corner, so the first segment keeps its shape, and on a smooth anchor it turns to stay in line at its own length. Alt makes the anchor a corner and leaves the outgoing handle where it was when Alt went down. A click on the first anchor closes the path with the incoming handle retracted and the anchor a corner, so the closing segment comes in straight. The Smart Pen's closing drag follows the same rule. path.close's `in` now places the handle as path.setHandle does, and a new `out` param places the outgoing handle and makes the anchor a corner. --- crates/engine/src/cmd/addons/pen/tests.rs | 51 ++++++++++ crates/engine/src/cmd/path.rs | 26 +++-- crates/engine/src/tests/draw2.rs | 110 ++++++++++++++++++++- crates/tools/src/addons/smart_pen.rs | 19 ++-- crates/tools/src/addons/smart_pen/tests.rs | 8 +- crates/tools/src/pen.rs | 64 +++++++++--- crates/tools/src/pen/tests.rs | 73 +++++++++----- docs/mcp.md | 11 ++- docs/target-app-parity.md | 2 +- 9 files changed, 305 insertions(+), 59 deletions(-) diff --git a/crates/engine/src/cmd/addons/pen/tests.rs b/crates/engine/src/cmd/addons/pen/tests.rs index 1bb9f3345e..b314b8db32 100644 --- a/crates/engine/src/cmd/addons/pen/tests.rs +++ b/crates/engine/src/cmd/addons/pen/tests.rs @@ -285,3 +285,54 @@ fn the_tool_draws_a_path_one_step_per_anchor_and_closes_it() { assert_eq!(path(&s, id).subpaths[0].anchors.len(), 3); assert_eq!(steps(&s), n + 8); } + +/// #6634: the tool's closing drag on the first anchor sets that anchor's incoming handle to the +/// mirror of the pointer and does not give it symmetric handles: a corner keeps its outgoing +/// handle, a smooth anchor turns it to stay in line at its own length, and Alt pressed mid-drag +/// keeps it where the drag had turned it. +#[test] +fn the_tools_closing_drag_does_not_make_the_first_anchor_symmetric() { + // An open path whose first anchor, at (50, 50), has the handles `first`, drawn on from its last + // anchor; the closing gesture is then up to the caller. + let draw = |first: Value| { + let mut s = session(); + let mut a = json!({"x": 50, "y": 50}); + a.as_object_mut().unwrap().extend(first.as_object().unwrap().clone()); + let anchors = json!([a, {"x": 150, "y": 50}, {"x": 150, "y": 150}]); + let id = NodeId(s.execute("path.create", &json!({"anchors": anchors})).unwrap()["id"].as_u64().unwrap()); + s.select_tool("smartPen", view()).unwrap(); + gesture(&mut s, &[(150.0, 150.0)], Mods::default()); + (s, id) + }; + let first = |s: &Session, id: NodeId| { + let sp = &path(s, id).subpaths[0]; + assert!(sp.closed, "{sp:?}"); + sp.anchors[0] + }; + let near = |a: Point, b: Point| a.distance(b) < 1e-6; + + // A corner: the first segment keeps its shape. + let (mut s, id) = draw(json!({"out": [80, 30]})); + gesture(&mut s, &[(50.0, 50.0), (50.0, 100.0)], Mods::default()); + let a = first(&s, id); + assert_eq!((a.h_in, a.h_out, a.kind), (Point::new(50.0, 0.0), Point::new(80.0, 30.0), AnchorKind::Corner), "{a:?}"); + + // A smooth anchor: the outgoing handle turns opposite the incoming one, keeping its length 30. + let (mut s, id) = draw(json!({"in": [20, 50], "out": [80, 50]})); + assert_eq!(path(&s, id).subpaths[0].anchors[0].kind, AnchorKind::Smooth); + gesture(&mut s, &[(50.0, 50.0), (50.0, 100.0)], Mods::default()); + let a = first(&s, id); + assert_eq!((a.h_in, a.kind), (Point::new(50.0, 0.0), AnchorKind::Smooth), "{a:?}"); + assert!(near(a.h_out, Point::new(50.0, 80.0)), "{a:?}"); + + // Alt pressed mid-drag: a corner, its outgoing handle where the drag had turned it. + let (mut s, id) = draw(json!({"in": [20, 50], "out": [80, 50]})); + let alt = Mods { alt: true, ..Mods::default() }; + s.pointer(&PointerEvent::new(PointerKind::Down, 50.0, 50.0), view()).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 50.0, 100.0), view()).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 80.0, 100.0).with_mods(alt), view()).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 80.0, 100.0).with_mods(alt), view()).unwrap(); + let a = first(&s, id); + assert_eq!((a.h_in, a.kind), (Point::new(20.0, 0.0), AnchorKind::Corner), "{a:?}"); + assert!(near(a.h_out, Point::new(50.0, 80.0)), "{a:?}"); +} diff --git a/crates/engine/src/cmd/path.rs b/crates/engine/src/cmd/path.rs index 712ca8a179..91da35e51b 100644 --- a/crates/engine/src/cmd/path.rs +++ b/crates/engine/src/cmd/path.rs @@ -32,7 +32,7 @@ pub fn specs() -> Vec { "Close Path", [], None, - "{id, subpath?: usize (the open subpath to close, 0 included; default: the last open one), in?: [x,y] (handle into the first anchor), independent?: bool}", + "{id, subpath?: usize (the open subpath to close, 0 included; default: the last open one), in?: [x,y] (handle into the first anchor, placed as path.setHandle places it: a smooth first anchor keeps its outgoing handle in line at its own length, a corner keeps it where it is), out?: [x,y] (the first anchor's outgoing handle, placed after `in`; the anchor becomes a corner), independent?: bool (`in` makes the first anchor a corner and leaves its outgoing handle)}", has_doc, close ), @@ -202,14 +202,18 @@ fn append_anchor(s: &mut Session, p: &Value) -> Result { ok() } -/// Close the active open subpath of `id`, optionally setting the incoming handle of the first anchor. +/// Close the active open subpath of `id`, optionally setting the handles of the first anchor. The +/// incoming handle moves as Move Direction Handle moves it: the outgoing handle turns with it only +/// on a smooth anchor, so the first segment of a path that starts at a corner keeps its shape. fn close(s: &mut Session, p: &Value) -> Result { let id = id_param(p, "id").ok_or_else(|| bad("path.close", "missing id"))?; let subpath = p.get("subpath").and_then(Value::as_u64).map(|u| u as usize); - let h_in = match p.get("in").filter(|h| !h.is_null()) { - None => None, - Some(h) => Some(finite_numbers(h).map(|[x, y]| Point::new(x, y)).ok_or_else(|| bad("path.close", "`in` must be [x, y]"))?), + let handle = |key: &str| match p.get(key).filter(|h| !h.is_null()) { + None => Ok(None), + Some(h) => finite_numbers(h).map(|[x, y]| Some(Point::new(x, y))).ok_or_else(|| bad("path.close", format!("`{key}` must be [x, y]"))), }; + let h_in = handle("in")?; + let h_out = handle("out")?; let independent = switch_or(p, "independent", false, "path.close")?; s.edit("Close Path", |d, sel| { let path = path_mut(d, id)?; @@ -218,11 +222,13 @@ fn close(s: &mut Session, p: &Value) -> Result { None => path.subpaths.iter_mut().rev().find(|s| !s.closed).ok_or_else(|| EngineError::Other("path is already closed".into()))?, }; sp.closed = true; - if let (Some(h), Some(first)) = (h_in, sp.anchors.first_mut()) { - first.h_in = h; - if !independent { - first.h_out = first.p - (h - first.p); - first.kind = AnchorKind::Smooth; + if let Some(first) = sp.anchors.first_mut() { + if let Some(h) = h_in { + first.set_handle(false, h, independent); + } + if let Some(h) = h_out { + first.h_out = h; + first.kind = AnchorKind::Corner; } } let top = compound_or_self(d, id); diff --git a/crates/engine/src/tests/draw2.rs b/crates/engine/src/tests/draw2.rs index fcf9b63636..ea10df64b5 100644 --- a/crates/engine/src/tests/draw2.rs +++ b/crates/engine/src/tests/draw2.rs @@ -3146,7 +3146,7 @@ fn shift_reshapes_the_closing_segment_of_a_rotated_square_and_undoes() { fn pen_drag_from_the_first_anchor_closes_the_path() { // #501: closing a path by dragging out of its first anchor flickered between a close and a new // path, and released at the wrong moment left the shape open. The press decides: the drag - // shapes the closing curve, symmetric, and the release closes the path wherever it ends. + // shapes the closing curve, and the release closes the path wherever it ends. let none = Mods::default(); let v = view(); let mut s = session(); @@ -3167,13 +3167,119 @@ fn pen_drag_from_the_first_anchor_closes_the_path() { let sp = &path(&s, id).subpaths[0]; assert!(sp.closed && sp.anchors.len() == 3, "{sp:?}"); let a = sp.anchors[0]; - assert_eq!((a.h_in, a.h_out), (Point::new(40.0, 348.0), Point::new(160.0, 252.0)), "symmetric"); + assert_eq!((a.h_in, a.h_out), (Point::new(40.0, 348.0), Point::new(100.0, 300.0)), "only the closing segment curves"); assert_eq!(paths(&s).len(), 1); // The next click starts a new path. gesture(&mut s, &[(500.0, 500.0)], none); assert_eq!(paths(&s).len(), 2); } +/// #6634: closing a path by dragging on its first anchor does not give that anchor symmetric +/// handles. Its incoming handle mirrors the pointer; its outgoing handle stays where it is on a +/// corner, so the first segment keeps its shape, and on a smooth anchor turns to stay in line at +/// its own length. Alt keeps the outgoing handle where it was when Alt went down, Shift keeps the +/// drag to 45° steps, and a click leaves the anchor a corner with the closing segment straight +/// into it. Each close is one undo step. +#[test] +fn pen_closing_drag_does_not_make_the_first_anchor_symmetric() { + use vectorcraft_geom::AnchorKind; + let (none, alt, shift) = (Mods::default(), Mods { alt: true, ..Mods::default() }, Mods { shift: true, ..Mods::default() }); + let v = view(); + // Draws a path from (100, 300), dragged out to `start` when given (a smooth anchor), through + // (200, 200) and (300, 300), and returns it with its first anchor as drawn. + let draw = |s: &mut Session, start: Option<(f64, f64)>| { + s.select_tool("pen", v).unwrap(); + let first = match start { + Some(out) => vec![(100.0, 300.0), out], + None => vec![(100.0, 300.0)], + }; + gesture(s, &first, none); + gesture(s, &[(200.0, 200.0)], none); + gesture(s, &[(300.0, 300.0)], none); + let id = s.doc().unwrap().selection.objects[0]; + let anchor = path(s, id).subpaths[0].anchors[0]; + (id, anchor) + }; + let first = |s: &Session, id: NodeId| { + let sp = &path(s, id).subpaths[0]; + assert!(sp.closed, "{sp:?}"); + sp.anchors[0] + }; + + // A corner: the first segment stays straight however the drag turns. + let mut s = session(); + let (id, before) = draw(&mut s, None); + assert_eq!(gesture(&mut s, &[(100.0, 300.0), (80.0, 250.0), (60.0, 200.0)], none), 1, "one undo step"); + let a = first(&s, id); + assert_eq!((a.h_in, a.h_out, a.kind), (Point::new(140.0, 400.0), before.h_out, AnchorKind::Corner), "{a:?}"); + s.execute("edit.undo", &json!({})).unwrap(); + assert!(!path(&s, id).subpaths[0].closed, "the undo opens the path again"); + + // A smooth anchor: the outgoing handle turns opposite the incoming one, keeping its length 50. + let mut s = session(); + let (id, before) = draw(&mut s, Some((150.0, 300.0))); + assert_eq!((before.h_out, before.kind), (Point::new(150.0, 300.0), AnchorKind::Smooth)); + gesture(&mut s, &[(100.0, 300.0), (100.0, 250.0), (100.0, 200.0)], none); + let a = first(&s, id); + assert_eq!((a.h_in, a.kind), (Point::new(100.0, 400.0), AnchorKind::Smooth), "{a:?}"); + assert!(near(a.h_out, Point::new(100.0, 250.0)), "in line, at its own length: {a:?}"); + + // Alt held from the press: a corner, its outgoing handle where it was. + let mut s = session(); + let (id, before) = draw(&mut s, Some((150.0, 300.0))); + gesture(&mut s, &[(100.0, 300.0), (100.0, 250.0), (100.0, 200.0)], alt); + let a = first(&s, id); + assert_eq!((a.h_in, a.h_out, a.kind), (Point::new(100.0, 400.0), before.h_out, AnchorKind::Corner), "{a:?}"); + + // Alt pressed mid-drag: the outgoing handle stays where the drag had turned it. + let mut s = session(); + let (id, _) = draw(&mut s, Some((150.0, 300.0))); + s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 300.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 100.0, 200.0), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Drag, 130.0, 200.0).with_mods(alt), v).unwrap(); + s.pointer(&PointerEvent::new(PointerKind::Up, 130.0, 200.0).with_mods(alt), v).unwrap(); + let a = first(&s, id); + assert_eq!((a.h_in, a.kind), (Point::new(70.0, 400.0), AnchorKind::Corner), "{a:?}"); + assert!(near(a.h_out, Point::new(100.0, 250.0)), "{a:?}"); + + // Shift: the drag keeps to 45° steps (straight up here), at the pointer's distance from the + // anchor, mirrored into the incoming handle. + let mut s = session(); + let (id, before) = draw(&mut s, None); + gesture(&mut s, &[(100.0, 300.0), (95.0, 250.0), (90.0, 200.0)], shift); + let a = first(&s, id); + assert!(near(a.h_in, Point::new(100.0, 300.0 + 10f64.hypot(100.0))) && a.h_out == before.h_out, "{a:?}"); + + // A click: the closing segment comes straight in, and a smooth anchor keeps its outgoing + // handle and becomes a corner. + let mut s = session(); + let (id, before) = draw(&mut s, Some((150.0, 300.0))); + assert_eq!(gesture(&mut s, &[(100.0, 300.0)], none), 1); + let a = first(&s, id); + assert_eq!((a.h_in, a.h_out, a.kind), (Point::new(100.0, 300.0), before.h_out, AnchorKind::Corner), "{a:?}"); +} + +/// Close Path's `in` moves the first anchor's incoming handle as Move Direction Handle does, and +/// `out` places its outgoing handle, making it a corner; `out` that is not [x, y] is refused. +#[test] +fn close_path_places_the_first_anchors_handles() { + use vectorcraft_geom::AnchorKind; + let mut s = session(); + let id = curve(&mut s); + let a = path(&s, id).subpaths[0].anchors[0]; + assert!(a.has_out() && a.kind == AnchorKind::Corner, "{a:?}"); + for h in [json!("1, 2"), json!([1]), json!([1, "2"])] { + refuses_with(&mut s, "path.close", &json!({"id": id.0, "out": h}), "`out` must be [x, y]"); + } + s.execute("path.close", &json!({"id": id.0, "in": [60.0, 140.0]})).unwrap(); + let b = path(&s, id).subpaths[0].anchors[0]; + assert_eq!((b.h_in, b.h_out, b.kind), (Point::new(60.0, 140.0), a.h_out, AnchorKind::Corner), "a corner keeps its outgoing handle"); + s.execute("edit.undo", &json!({})).unwrap(); + s.execute("path.close", &json!({"id": id.0, "in": [60.0, 140.0], "out": [120.0, 60.0]})).unwrap(); + let b = path(&s, id).subpaths[0].anchors[0]; + assert_eq!((b.h_in, b.h_out, b.kind), (Point::new(60.0, 140.0), Point::new(120.0, 60.0), AnchorKind::Corner)); +} + #[test] fn pen_with_alt_converts_the_anchors_of_the_path_being_drawn() { // #504: while drawing, Alt-click on a smooth anchor of the path makes it a corner and Alt-drag diff --git a/crates/tools/src/addons/smart_pen.rs b/crates/tools/src/addons/smart_pen.rs index 68c19cc676..ee7440dde6 100644 --- a/crates/tools/src/addons/smart_pen.rs +++ b/crates/tools/src/addons/smart_pen.rs @@ -6,7 +6,8 @@ //! tangent); a drag makes a smooth anchor (Alt held breaks the outgoing handle off, Shift keeps it //! to 45° steps, Space moves the anchor); Tab switches the segment into the anchor being placed, or //! the last one drawn, between straight and curved. A rubber band shows the next segment. A click -//! on the first anchor closes the path, on an end of another open path joins the two, and away +//! on the first anchor closes the path (a drag from it shapes the closing segment as the Pen's +//! closing drag does), on an end of another open path joins the two, and away //! from paths, with no path being drawn, starts a new one. Enter or Esc ends the path. //! //! Editing the shown paths' points: a click selects a point (an end of an open path is then drawn @@ -30,7 +31,7 @@ use vectorcraft_pathops::addons::pen::{leave_handle, straighten_segment}; use crate::direct::hit_handle; use crate::draw2::{anchor_in, hit_segment, segment_in, shown_paths}; use crate::guides::{DrawSnap, Leave}; -use crate::pen::{active_path, continue_from, open_end_at}; +use crate::pen::{active_path, close_drag, continue_from, first_anchor, open_end_at}; use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey}; /// The tool's id. @@ -82,11 +83,13 @@ struct Place { #[derive(Clone, Copy, Debug, PartialEq)] enum Target { Place(Place), - /// Closing the path being drawn on its first anchor, at `first`. + /// Closing the path being drawn on its first anchor, at `first`; `anchor` holds that anchor as + /// the press found it and its outgoing handle as the drag last left it. Close { id: NodeId, si: usize, first: Point, + anchor: Option<(Anchor, Point)>, }, /// An anchor of a shown path at `p`; `n` anchors in its subpath, `closed` or not. Point { @@ -285,7 +288,8 @@ impl SmartPenTool { let press = |what| Press { at: ev.pos, mods: ev.mods, dragged: false, begun: false, what }; match self.hit(cx, ev.pos) { Hit::Close(id, si, first) => { - self.press = Some(Press { begun: true, ..press(Target::Close { id, si, first }) }); + let anchor = first_anchor(cx, id, si).map(|a| (a, a.h_out)); + self.press = Some(Press { begun: true, ..press(Target::Close { id, si, first, anchor }) }); let seg = if self.curved { "curved" } else { "straight" }; vec![ Action::Begin("Close Path".into()), @@ -362,10 +366,11 @@ impl SmartPenTool { pr.what = Target::Place(pl); ("", self.place_preview(&pl, true)) } - Target::Close { id, si, first } => { + Target::Close { id, si, first, mut anchor } => { let out = Self::handle_to(cx, first, ev.pos, first, shift, false); - let h_in = first - (out - first); - ("", Action::Preview("path.close".into(), json!({"id": id.0, "subpath": si, "in": xy(h_in), "independent": alt}))) + let act = close_drag(id, Some(si), first - (out - first), alt, anchor.as_mut()); + pr.what = Target::Close { id, si, first, anchor }; + ("", act) } Target::Point { id, si, ai, p, .. } if pr.mods.alt => { let h = Self::handle_to(cx, p, ev.pos, p, shift, false); diff --git a/crates/tools/src/addons/smart_pen/tests.rs b/crates/tools/src/addons/smart_pen/tests.rs index 0f6bd5c912..a7f792c22f 100644 --- a/crates/tools/src/addons/smart_pen/tests.rs +++ b/crates/tools/src/addons/smart_pen/tests.rs @@ -157,7 +157,13 @@ fn a_press_on_the_first_anchor_closes_the_path() { // A drag shapes the closing curve. let (c, params) = preview(&t.pointer(&cx, &ev(PointerKind::Drag, 130.0, 100.0, NO))); assert_eq!((c.as_str(), params["in"].clone()), ("path.close", json!([70.0, 100.0]))); - assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, 130.0, 100.0, NO)), vec![Action::Commit]); + // Alt pressed mid-drag makes the anchor a corner and keeps its outgoing handle where it was. + let (_, params) = preview(&t.pointer(&cx, &ev(PointerKind::Drag, 130.0, 120.0, ALT))); + assert_eq!( + (params["in"].clone(), params["out"].clone(), params["independent"].clone()), + (json!([70.0, 80.0]), json!([100.0, 100.0]), json!(true)) + ); + assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, 130.0, 120.0, ALT)), vec![Action::Commit]); assert!(!t.drawing, "the path is finished"); } diff --git a/crates/tools/src/pen.rs b/crates/tools/src/pen.rs index b70a160d8a..31aabfb38f 100644 --- a/crates/tools/src/pen.rs +++ b/crates/tools/src/pen.rs @@ -3,7 +3,11 @@ //! Click adds a corner anchor; click-drag adds a smooth anchor with symmetric handles (Alt breaks //! them: the incoming handle stays where it was when Alt went down and only the outgoing one //! follows the pointer; Space held moves the anchor, handles and all); Shift constrains to 45°. -//! A press on the first anchor closes the path, the drag shaping the closing curve. Clicking the +//! A press on the first anchor closes the path, the drag shaping the closing curve: the anchor's +//! incoming handle mirrors the pointer (a click leaves it retracted and the anchor a corner, so the +//! closing segment comes in straight). Its outgoing handle stays where it is on a corner, so the first segment keeps its +//! shape, and on a smooth anchor turns to stay in line at its own length; Alt makes the anchor a +//! corner, leaving the outgoing handle where it was when Alt went down. Clicking the //! last one retracts its outgoing handle, so the next segment leaves it as a corner; dragging from //! it pulls a new one out on its own. //! Alt held over a handle end, an anchor or a segment of a selected path (the one being drawn too) @@ -27,7 +31,7 @@ use serde_json::json; use vectorcraft_doc::{NodeId, NodeKind}; -use vectorcraft_geom::{BezPath, Point, Vec2}; +use vectorcraft_geom::{Anchor, BezPath, Point, Vec2}; use crate::direct::hit_handle; use crate::draw2::{AnchorTool, editable_paths, shown_paths}; @@ -47,6 +51,9 @@ pub struct PenTool { hover: Option, /// The incoming handle of the anchor being dragged out, as last previewed. in_h: Point, + /// The first anchor, as it was when a press on it began closing the path, and its outgoing + /// handle as the closing drag last left it: Alt pressed mid-drag keeps the handle there. + first: Option<(Anchor, Point)>, /// The pointer at the last button-down or drag: Space held moves the anchor as far as it moves. last: Point, /// Where the button went down: the drag threshold is measured from it. @@ -289,9 +296,7 @@ impl Tool for PenTool { // Pick at the raw pointer before snapping or constraining a new point. // A one-anchor path doesn't close on itself: its anchor is the last one too. if picked == Some(Endpoint::First) { - self.drag = Some(Place { at: first, path: Some(id), subpath: Some(si), closing: true }); - let params = json!({"id": id.0, "subpath": si}); - return vec![Action::Begin("Close Path".into()), Action::Preview("path.close".into(), params)]; + return self.begin_close(cx, id, si, first); } // Alt uses Anchor Point behavior at the terminal anchor too. if let Some(acts) = self.alt_convert(cx, ev) { @@ -307,9 +312,7 @@ impl Tool for PenTool { if raw_other.is_none() && p != ev.pos { let snapped = pick_endpoint(closing_end, last, p, tol, Endpoint::First); if snapped == Some(Endpoint::First) { - self.drag = Some(Place { at: first, path: Some(id), subpath: Some(si), closing: true }); - let params = json!({"id": id.0, "subpath": si}); - return vec![Action::Begin("Close Path".into()), Action::Preview("path.close".into(), params)]; + return self.begin_close(cx, id, si, first); } if snapped == Some(Endpoint::Last) && let Some((si, ai)) = end @@ -410,11 +413,7 @@ impl Tool for PenTool { )]; }; if closing { - let mut params = json!({"id": id.0, "in": [2.0 * a.x - out_h.x, 2.0 * a.y - out_h.y], "independent": alt}); - if let Some(si) = subpath { - params["subpath"] = json!(si); - } - return vec![Action::Preview("path.close".into(), params)]; + return vec![close_drag(id, subpath, a - (out_h - a), alt, self.first.as_mut())]; } // Alt pressed mid-drag keeps the curve already shaped into the anchor: only the // outgoing handle follows. Held from the start, the incoming handle stays retracted. @@ -436,6 +435,7 @@ impl Tool for PenTool { } let Some(place) = self.drag.take() else { return vec![] }; if place.closing { + self.first = None; self.stop(); } vec![Action::Commit] @@ -453,6 +453,7 @@ impl Tool for PenTool { /// close it was making: the path being drawn goes on with the next click. fn drop_press(&mut self, _cx: &ToolContext) -> Vec { self.drag = None; + self.first = None; self.handle = None; self.convert = None; self.snap.clear(); @@ -464,6 +465,7 @@ impl Tool for PenTool { self.stop(); self.snap.clear(); let placing = self.drag.take().is_some(); + self.first = None; let handling = self.handle.take().is_some(); // 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(); @@ -577,6 +579,16 @@ impl PenTool { (self.drawing, self.path, self.subpath) = (false, None, None); } + /// A press on the first anchor (at `at`) of subpath `si` of the path being drawn: close it, the + /// anchor a corner with its incoming handle retracted until a drag pulls it out, as a click on + /// the last anchor retracts its outgoing one ([`set_out_handle`]). + fn begin_close(&mut self, cx: &ToolContext, id: NodeId, si: usize, at: Point) -> Vec { + self.drag = Some(Place { at, path: Some(id), subpath: Some(si), closing: true }); + self.first = first_anchor(cx, id, si).map(|a| (a, a.h_out)); + let params = json!({"id": id.0, "subpath": si, "in": [at.x, at.y], "independent": true}); + vec![Action::Begin("Close Path".into()), Action::Preview("path.close".into(), params)] + } + /// Hand an Alt press on a selected path's handle, anchor or segment to the Anchor Point tool. fn alt_convert(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Option> { if !alt_converts(cx, ev.pos, ev.mods) { @@ -592,6 +604,32 @@ impl PenTool { } } +/// The first anchor of subpath `si` of path `id`. +pub(crate) fn first_anchor(cx: &ToolContext, id: NodeId, si: usize) -> Option { + cx.doc.node(id)?.path_data()?.subpaths.get(si)?.anchors.first().copied() +} + +/// The preview of a closing drag that puts the first anchor's incoming handle at `in_h`. `first` +/// holds that anchor as it was when the press began closing the path, and its outgoing handle as +/// the drag last left it: a smooth anchor turns that handle to stay in line, and Alt (`alt`), which +/// makes the anchor a corner, keeps it there. +pub(crate) fn close_drag(id: NodeId, subpath: Option, in_h: Point, alt: bool, first: Option<&mut (Anchor, Point)>) -> Action { + let mut params = json!({"id": id.0, "in": [in_h.x, in_h.y], "independent": alt}); + if let Some((anchor, out)) = first { + if alt { + params["out"] = json!([out.x, out.y]); + } else { + let mut a = *anchor; + a.set_handle(false, in_h, false); + *out = a.h_out; + } + } + if let Some(si) = subpath { + params["subpath"] = json!(si); + } + Action::Preview("path.close".into(), params) +} + /// Go on drawing subpath `si` of open path `id` from its last anchor, or from its first /// (`at_first`, the subpath reversed so that it is the last): the path (its compound path) is /// selected. diff --git a/crates/tools/src/pen/tests.rs b/crates/tools/src/pen/tests.rs index 340a2ea6ed..984f34646a 100644 --- a/crates/tools/src/pen/tests.rs +++ b/crates/tools/src/pen/tests.rs @@ -2,6 +2,13 @@ use super::*; use crate::testutil::*; use vectorcraft_doc::Selection; +/// What a press on the first anchor, at `first`, of subpath 0 of `id` does: the path closes with +/// the anchor a corner with its incoming handle retracted. +fn close_press(id: NodeId, first: Point) -> Vec { + let params = json!({"id": id.0, "subpath": 0, "in": [first.x, first.y], "independent": true}); + vec![Action::Begin("Close Path".into()), Action::Preview("path.close".into(), params)] +} + #[test] fn press_inside_drag_threshold_places_a_corner() { let (d, s) = (vectorcraft_doc::Document::new(500.0, 500.0), Selection::default()); @@ -131,10 +138,7 @@ fn snapped_first_endpoint_closes_active_path_after_raw_miss() { assert!(open_end_at(&cx, raw, tol, Some((id, 0))).is_none()); assert!(open_end_at(&cx, first, tol, Some((id, 0))).is_none()); - assert_eq!( - pen.pointer(&cx, &PointerEvent::new(PointerKind::Down, raw.x, raw.y)), - vec![Action::Begin("Close Path".into()), Action::Preview("path.close".into(), json!({"id": id.0, "subpath": 0}))] - ); + assert_eq!(pen.pointer(&cx, &PointerEvent::new(PointerKind::Down, raw.x, raw.y)), close_press(id, first)); let place = pen.drag.unwrap(); assert!(place.closing); assert_eq!((place.path, place.at), (Some(id), first)); @@ -349,10 +353,7 @@ fn terminal_anchor_conversion_precedes_grid_snapping() { assert_eq!(t.cursor(&cx, Point::new(63.0, 303.0), Mods::default()), Cursor::PenContinue); assert!(click(&mut t, &cx, 63.0, 303.0, Mods::default()).is_empty()); assert_eq!(t.active(&cx).map(|a| a.0), Some(id)); - assert_eq!( - t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 13.0, 303.0)), - vec![Action::Begin("Close Path".into()), Action::Preview("path.close".into(), json!({"id": id.0, "subpath": 0}))] - ); + assert_eq!(t.pointer(&cx, &PointerEvent::new(PointerKind::Down, 13.0, 303.0)), close_press(id, Point::new(13.0, 303.0))); } #[test] @@ -401,7 +402,7 @@ fn overlapping_endpoint_tolerances_pick_the_nearest_end() { let cursor = if first_end { Cursor::PenClose } else { Cursor::PenConvert }; let actual_cursor = pen.cursor(&cx, at, mods); let expected = if first_end { - vec![Action::Begin("Close Path".into()), Action::Preview("path.close".into(), json!({"id": id.0, "subpath": 0}))] + close_press(id, first) } else { vec![Action::Begin("Convert Anchor Point".into()), set_out(id, 1, last.x, last.y)] }; @@ -459,10 +460,7 @@ fn coincident_endpoints_keep_the_prior_tie_choice() { let cx = ToolContext { zoom, smart_guides: false, snap_to_point: false, ..cx(&d, &selection, &paint) }; let mut drawing = PenTool { drawing: true, ..PenTool::default() }; assert_eq!(drawing.cursor(&cx, at, Mods::default()), Cursor::PenClose); - assert_eq!( - click(&mut drawing, &cx, at.x, at.y, Mods::default()), - vec![Action::Begin("Close Path".into()), Action::Preview("path.close".into(), json!({"id": id.0, "subpath": 0}))] - ); + assert_eq!(click(&mut drawing, &cx, at.x, at.y, Mods::default()), close_press(id, at)); let mut resuming = PenTool::default(); assert_eq!(resuming.cursor(&cx, at, Mods::default()), Cursor::PenContinue); assert!(click(&mut resuming, &cx, at.x, at.y, Mods::default()).is_empty()); @@ -516,10 +514,7 @@ fn enlarged_anchor_radius_is_used_for_endpoints_and_alt_conversion() { let mut closing = PenTool { drawing: true, ..PenTool::default() }; let first = Point::new(10.0 - 6.0 / zoom, 300.0); assert_eq!(closing.cursor(&cx, first, Mods::default()), Cursor::PenClose); - assert_eq!( - click(&mut closing, &cx, first.x, first.y, Mods::default()), - vec![Action::Begin("Close Path".into()), Action::Preview("path.close".into(), json!({"id": id.0, "subpath": 0}))] - ); + assert_eq!(click(&mut closing, &cx, first.x, first.y, Mods::default()), close_press(id, Point::new(10.0, 300.0))); let mut alt_pen = PenTool { drawing: true, ..PenTool::default() }; let alt = Mods { alt: true, ..Mods::default() }; assert!(alt_pen.pointer(&cx, &PointerEvent::new(PointerKind::Down, at.x, at.y).with_mods(alt)).is_empty()); @@ -577,7 +572,8 @@ fn ending_during_a_pen_gesture_commits_and_clears_it() { /// #501: a press on the first anchor closes the path, however far the drag then goes: the /// closing preview leaves the path closed (so not one the pen extends), and each move still -/// previews the close with symmetric handles (Alt breaks them), released as a close. +/// previews the close with the incoming handle mirroring the pointer (Alt keeps the outgoing one +/// where it is), released as a close. #[test] fn a_drag_from_the_first_anchor_always_closes() { let pts = [Point::new(100.0, 300.0), Point::new(200.0, 300.0), Point::new(200.0, 400.0)]; @@ -585,22 +581,53 @@ fn a_drag_from_the_first_anchor_always_closes() { let p = paint(); let mut t = PenTool { drawing: true, ..PenTool::default() }; let a = t.pointer(&cx(&d, &s, &p), &PointerEvent::new(PointerKind::Down, 101.0, 301.0)); - assert_eq!(a, vec![Action::Begin("Close Path".into()), Action::Preview("path.close".into(), json!({"id": id.0, "subpath": 0}))]); + assert_eq!(a, close_press(id, pts[0])); // What the tool sees once the preview applied: the path closed. d.node_mut(id).unwrap().path_data_mut().unwrap().subpaths[0].closed = true; let c = cx(&d, &s, &p); - let close = |x: f64, y: f64, alt: bool| { - vec![Action::Preview("path.close".into(), json!({"id": id.0, "in": [200.0 - x, 600.0 - y], "independent": alt, "subpath": 0}))] + let close = |x: f64, y: f64| { + vec![Action::Preview("path.close".into(), json!({"id": id.0, "in": [200.0 - x, 600.0 - y], "independent": false, "subpath": 0}))] }; for (x, y) in [(105.0, 290.0), (130.0, 260.0), (160.0, 240.0)] { - assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Drag, x, y)), close(x, y, false), "at ({x}, {y})"); + assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Drag, x, y)), close(x, y), "at ({x}, {y})"); } let alt = Mods { alt: true, ..Mods::default() }; - assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 170.0, 250.0).with_mods(alt)), close(170.0, 250.0, true)); + let alt_close = json!({"id": id.0, "in": [30.0, 350.0], "out": [100.0, 300.0], "independent": true, "subpath": 0}); + assert_eq!( + t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 170.0, 250.0).with_mods(alt)), + vec![Action::Preview("path.close".into(), alt_close)] + ); assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Up, 170.0, 250.0)), vec![Action::Commit]); assert!(!t.busy() && t.active(&c).is_none(), "the path is done"); } +/// #6634: on a smooth first anchor the closing drag turns the outgoing handle in line with the +/// incoming one; Alt pressed mid-drag sends the outgoing handle where the drag had turned it. +#[test] +fn alt_mid_close_keeps_the_turned_outgoing_handle() { + use vectorcraft_geom::{Anchor, SubPath}; + let anchors = vec![Anchor::smooth(Point::new(100.0, 300.0), Point::new(150.0, 300.0)), Anchor::corner(Point::new(200.0, 200.0))]; + let (mut d, id, s) = drawing(SubPath { anchors, closed: false }); + let p = paint(); + let mut t = PenTool { drawing: true, ..PenTool::default() }; + assert_eq!(t.pointer(&cx(&d, &s, &p), &PointerEvent::new(PointerKind::Down, 100.0, 300.0)), close_press(id, Point::new(100.0, 300.0))); + d.node_mut(id).unwrap().path_data_mut().unwrap().subpaths[0].closed = true; + let c = cx(&d, &s, &p); + assert_eq!( + t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 100.0, 200.0)), + vec![Action::Preview("path.close".into(), json!({"id": id.0, "in": [100.0, 400.0], "independent": false, "subpath": 0}))] + ); + let alt = Mods { alt: true, ..Mods::default() }; + assert_eq!( + t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 130.0, 200.0).with_mods(alt)), + vec![Action::Preview( + "path.close".into(), + json!({"id": id.0, "in": [70.0, 400.0], "out": [100.0, 250.0], "independent": true, "subpath": 0}) + )] + ); + assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Up, 130.0, 200.0)), vec![Action::Commit]); +} + #[test] fn a_one_anchor_path_does_not_close_on_itself() { let (d, id, s) = drawing(vectorcraft_geom::SubPath::polyline(&[Point::new(10.0, 300.0)], false)); diff --git a/docs/mcp.md b/docs/mcp.md index 5826c5c8c4..938ecce098 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -3987,6 +3987,13 @@ an `anchor` or `segment` in the same way. The document does not change and no un after the new anchor on its subpath are numbered one higher, and a selected segment that the new anchor splits stays selected as its two halves, with the new anchor as an end of both that moves with them. Undo restores the path and the selection in one step. +`path.close {id, subpath?, in?, out?, independent?}` closes an open subpath (by default the last open one). `in` places +the first anchor's incoming handle as `path.setHandle` places a handle: a smooth anchor turns its outgoing handle to +stay in line and keeps that handle's length, and a corner keeps its outgoing handle where it is. With +`independent: true` the anchor becomes a corner first, so its outgoing handle does not move. `out`, placed after `in`, +is the first anchor's outgoing handle, and makes the anchor a corner. A Pen press on the first anchor sends `in` at +the anchor with `independent: true`. The Pen's and the Smart Pen's closing drags send the mirror of the pointer as +`in`, and once Alt is held they also send `out` at the outgoing handle's position when Alt went down. `path.reshape {id, x, y, dx, dy, tol?, focal?, radius?}` (a Reshape tool drag) grabs the path at `x`, `y`, adding an anchor there unless one lies within `tol` (3 by default), and moves that point by `dx`, `dy`. @@ -4035,8 +4042,8 @@ an `x` without a `y`, or a `y` without an `x`, with "x and y must be given toget `path.blob` refuse a point in `points` whose x or y is not a number, such as `["10", 10]` or a point written as a string, with "x and y must both be numbers". All of them except `path.curvature` refuse a pen pressure, tilt or rotation that is neither a number nor null with `` `pressure` must be a number, not "0.5" ``, naming the key -(`pressure`, `tiltX`, `tiltY` or `rotation`). `path.close` refuses an `in` that is not `[x, y]` -with `` `in` must be [x, y] ``. +(`pressure`, `tiltX`, `tiltY` or `rotation`). `path.close` refuses an `in` or `out` that is not `[x, y]` +with `` `in` must be [x, y] ``, naming the key. These commands refuse a string, a number or another value that is not true or false with `` `closed` must be true or false ``, naming the key; the document does not change and no undo step is recorded: diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index b4c949f742..296ba0cff0 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -956,7 +956,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur Align, Distribute, Distribute Spacing, Reflect and Shear return an error for any `horizontal`, `vertical`, `to`, `axis`, `bounds` or `spacing` value they don't take, listing the choices, and Align returns one when a call gives neither `horizontal` nor `vertical`; nothing moves and no undo step is recorded. Align and Distribute act on the anchor points selected with Direct Selection: the points of one path align to each other, not to the artboard, and Distribute spaces them (#1641, fixes #1636; aligning to a key anchor is still missing). Transform Each opens on the scale, move, rotate, reflect, Random, reference point, Transform Objects and Preview it was last confirmed with (kept with the UI state; Copy never is), and its Copy button, left of Cancel, transforms a copy of each object as the [Scale multiple objects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/scale-multiple-objects.html) help page has it; the Copy checkbox is gone (#1732; the remembered values follow a maintainer comment on the issue, not the help page). Its Scale section has the Relative and Absolute radio buttons the same page describes: percentages of each object's size, or the width and height it becomes (`object.transformEach` `relative`, which Transform Again repeats); Absolute measures each object's own box, and the scales act along its axes about that box's reference point, so a turned shape keeps its shape and objects of different sizes come out alike; the fields show the width and height the selected objects share and read "Mixed" when they differ or a side is 0 (a line's), each object measured by its own box, rotated with it, as the Transform panel and the Control bar show it (sizes they show alike count as the same), and a size typed into them sets every object to it (a side left Mixed keeps its size), our choices where the page leaves them open; a live Repeat scales its spacing by the geometric mean of the two factors, so its Absolute size is approximate. The link beside the two scales keeps them in proportion, as the shape dialogs' Width and Height link does (`__constrain`, kept with the dialog's values; where it sits is our choice, the public pages don't establish it). The panel lists Scale, Move and Rotate, then the Options in two columns (Transform Objects, Transform Patterns, Scale Strokes & Effects, Scale Corners; Reflect X, Reflect Y, Random), the Reference Point, and Preview at the left of the button row, level with Copy, Cancel and OK. Transform Again uses the Copy, Transform Patterns, Scale Strokes & Effects and Scale Corners choices of the transform it repeats; after a bounding-box handle drag on area type, it resizes the type area again and the type keeps its size (`object.transformAgain`). With anchors selected with Direct Selection, Move, Rotate, Scale, Reflect, Shear and Transform Again (the commands, their dialogs and the four tools' drags) transform only those anchors, their handles with them, about the centre of the box around them unless a point was clicked; a copy still copies the whole object (#1408; behaviour reference: [adjust path segments](https://helpx.adobe.com/illustrator/using/adjust-path-segments.html); the default reference point and the copy are our choices). The Move, Rotate, Scale, Reflect and Shear dialogs have a Preview checkbox, off when they open: while it is on the canvas follows the values, Cancel rolls it back and OK is still one undo step; Up/Down step the Rotate and Shear angles and the Scale percentages by 1, Shift by 10 (#1412). The five dialogs and Transform Each have Transform Objects beside Transform Patterns: off, the art stays and only its pattern tiles transform (`objects` on the transform commands), and Transform Again repeats the choice (#1448; behaviour reference: [scale objects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/scale-objects.html); the checkboxes are always enabled and the Scale page's pair is applied to all of them, our choices). Reflect's axis is Horizontal, Vertical or an angle (#1460; [reflect objects along an axis](https://helpx.adobe.com/illustrator/desktop/manage-objects/arrange-objects/reflect-objects-along-an-axis.html)). - - **Pen:** Alt pressed in the middle of dragging out an anchor splits its handles and keeps the curve already shaped into it (only the outgoing handle follows the pointer); Space held while dragging out an anchor moves it, handles and all. A press on the first anchor of the path being drawn closes it whatever the drag then does: the drag shapes the closing curve (symmetric handles, Alt breaks them) and the release closes the path wherever it ends (#501). Clicking the last anchor of the path being drawn retracts its outgoing handle (convert cursor), and dragging from it pulls out a new one on its own. Auto Add/Delete: over a selected path, a click on a segment adds an anchor and a click on an anchor deletes it (add and delete cursors); Shift held, or Preferences › General › Disable Auto Add/Delete, starts a new path instead. Alt held over a handle end or an anchor of a selected path (the one being drawn too) works as the Anchor Point tool, with its convert cursor: dragging a handle moves it alone, clicking a smooth anchor makes it a corner, dragging an anchor pulls out new symmetric handles, dragging a segment reshapes it; drawing then goes on. Cmd (Ctrl) held drags with the selection tool chosen last, Direct Selection until one is (handles, anchors and segments of the path being drawn or another), and the Pen then goes on drawing its path while that stays selected; the pointer shows that tool's while Cmd is held. The same holds for agents (`pointer_gesture` with `mods.cmd`), as the borrowing now lives in the engine (#494). A drag's preview (the Pen's, the Anchor Point tool's, Direct Selection's handles and anchors) follows every position the pointer is seen at (#834): the canvas sends the tool a drag whenever the pointer's document position differs from the last one it sent, not only when egui's frame delta is non-zero (zero when a compositor coalesces motion and in the frame the pointer comes back into the window after leaving it), and a move that arrives in the release's own frame shapes the preview before the release commits it, once the press has dragged. With the Pen, a press that moves under 3 screen pixels is a click (a corner without handles), and a Precise Cursors command toggles the existing preference and can take a shortcut (#1663). + - **Pen:** Alt pressed in the middle of dragging out an anchor splits its handles and keeps the curve already shaped into it (only the outgoing handle follows the pointer); Space held while dragging out an anchor moves it, handles and all. A press on the first anchor of the path being drawn closes it whatever the drag then does: the drag shapes the closing curve and the release closes the path wherever it ends (#501). The first anchor's incoming handle mirrors the pointer, and a click leaves it retracted and the anchor a corner. Its outgoing handle stays where it is on a corner, so the first segment keeps its shape, and on a smooth anchor it turns to stay in line at its own length; Alt makes the anchor a corner and leaves the outgoing handle where it was when Alt went down. The Smart Pen's closing drag does the same (fixes #6634; `path.close`'s `in` and `out`; behavior reference: [draw with the Pen, Curvature, or Pencil tool](https://web.archive.org/web/20220614224656/https://helpx.adobe.com/illustrator/using/drawing-pen-curvature-or-pencil.html), where a click or drag on the first anchor closes the path and Alt breaks the pairing of the closing anchor's handles; which handles the drag sets are our choices). Moving the closing anchor with Space held, which that page also describes, is still missing. Clicking the last anchor of the path being drawn retracts its outgoing handle (convert cursor), and dragging from it pulls out a new one on its own. Auto Add/Delete: over a selected path, a click on a segment adds an anchor and a click on an anchor deletes it (add and delete cursors); Shift held, or Preferences › General › Disable Auto Add/Delete, starts a new path instead. Alt held over a handle end or an anchor of a selected path (the one being drawn too) works as the Anchor Point tool, with its convert cursor: dragging a handle moves it alone, clicking a smooth anchor makes it a corner, dragging an anchor pulls out new symmetric handles, dragging a segment reshapes it; drawing then goes on. Cmd (Ctrl) held drags with the selection tool chosen last, Direct Selection until one is (handles, anchors and segments of the path being drawn or another), and the Pen then goes on drawing its path while that stays selected; the pointer shows that tool's while Cmd is held. The same holds for agents (`pointer_gesture` with `mods.cmd`), as the borrowing now lives in the engine (#494). A drag's preview (the Pen's, the Anchor Point tool's, Direct Selection's handles and anchors) follows every position the pointer is seen at (#834): the canvas sends the tool a drag whenever the pointer's document position differs from the last one it sent, not only when egui's frame delta is non-zero (zero when a compositor coalesces motion and in the frame the pointer comes back into the window after leaving it), and a move that arrives in the release's own frame shapes the preview before the release commits it, once the press has dragged. With the Pen, a press that moves under 3 screen pixels is a click (a corner without handles), and a Precise Cursors command toggles the existing preference and can take a shortcut (#1663). - **Direct Selection (#1278):** clicking a segment picks its connection, with hollow endpoint anchors and only that curve's direction handles. Delete leaves the neighboring curves and appearance intact, opens/splits contours in one undo step, and another Delete removes the remaining selected path. A whole-path drag and deliberate anchor selection keep their existing behavior; egui frames and native control/art checked, OS mouse/visual QA pending. Where anchors of overlapping objects coincide, a click or drag takes the anchor of the selected object, also when another object lies over it (#1509, fixes #1508). Delete removes every selected anchor of a closed path (it used to remove the wrong ones), removes objects selected whole along with the selected anchors of others, and keeps the remainder selected so a second Delete removes it (#1674). In isolation mode Direct Selection and Group Selection pick only inside the isolated object (#1666). Escape cancels a Direct Selection drag (#1803, #1743). Double-clicking type (including type nested inside a group) switches to the Type tool and puts the caret at the clicked character. With Direct Selection and Group Selection, a drag that starts on an object while the selection also holds direct-selected anchors or segments moves those anchors and the objects selected whole in one undo step (`path.moveAnchors`), as a drag of a selected anchor does, and the other anchors of a partly selected path stay in place. While Alt is held during the drag, it copies the selected objects instead (`object.transform`). When direct-selected anchors are moved or transformed together with objects selected whole (such a drag, an anchor drag, an arrow key, or Move, Rotate, Scale, Reflect and Shear without a copy), a path inside a selected group is transformed once, with the group. A path segment with a control point whose x or y is infinite or larger in size than `f64::MAX / 16` is measured by its control points, so its bounds hold the whole curve and the canvas check refuses an edit that leaves such a path selected (`path.create` included). From 019ff2b278881e76e804caa158d749ad9e30dd7f Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 15:34:17 -0800 Subject: [PATCH 18/38] i18n: Hindi and Turkish messages keep the command ids they name MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Seventeen @msg rows in hi.tsv and one in tr.tsv translated or dropped the command id the English names outside backticks. For example, "missing `id` (see plugin.list)" read "(information.list)" in Hindi, and flattener.presets.list became "düzleştirici.presets.list" in Turkish. The rows now keep each id as written. Several of the Hindi rows also said the opposite of the English ("a profile is called" for "no profile is called") and are corrected. A new test checks every catalog: each command id a status or error message names (dot-separated lowercase words outside backticks) appears unchanged in its translation. --- crates/ui-egui/src/i18n/hi.tsv | 34 ++++++++++---------- crates/ui-egui/src/i18n/tests.rs | 55 ++++++++++++++++++++++++++++++++ crates/ui-egui/src/i18n/tr.tsv | 2 +- 3 files changed, 73 insertions(+), 18 deletions(-) diff --git a/crates/ui-egui/src/i18n/hi.tsv b/crates/ui-egui/src/i18n/hi.tsv index 572a19779f..710767b0e1 100644 --- a/crates/ui-egui/src/i18n/hi.tsv +++ b/crates/ui-egui/src/i18n/hi.tsv @@ -5577,7 +5577,7 @@ antiAlias Sharp शार्प @msg `{key}` must be a whole number between {min} and {max} (got {x}) `{key}` को {min} और {max} ({x}) के बीच पूरी संख्या होना चाहिए। @msg `{key}` must be a whole number of at least 0, not {n} `{key}` को कम से कम 0 की पूरी संख्या होना चाहिए, नहीं {n} @msg `{key}` must be an appearance item index (paint order) or null `{key}` एक उपस्थिति आइटम सूचकांक (पेंट ऑर्डर) या null होना चाहिए -@msg `{key}` must be an array of asset ids (see assets.list) `{key}` को परिसंपत्ति ids की एक सरणी होना चाहिए (देखें परिसंपत्तियों.list) +@msg `{key}` must be an array of asset ids (see assets.list) `{key}` को परिसंपत्ति ids की एक सरणी होना चाहिए (assets.list देखें) @msg `{key}` must be an array of these names: {_1} `{key}` इन नामों की एक सरणी होना चाहिए: {_1} @msg `{key}` must be between {min} and {max} (got {x}) `{key}` को {min} और {max} ({x}) के बीच होना चाहिए। @msg `{key}` must be from {_1} to {shift_max} `{key}` को {_1} से {shift_max} होना चाहिए @@ -5649,7 +5649,7 @@ antiAlias Sharp शार्प @msg `artboards` must be a list of artboard indices `artboards` को आर्टबोर्ड इंडेक्स की सूची होना चाहिए @msg `artboards`: all or a range such as 1, 3-5, not {v} `artboards`: all या 1, 3-5 जैसी सीमा दें, {v} नहीं @msg `aspect` must be a number (%) `aspect` को संख्या (%) होना चाहिए -@msg `asset` is the asset id (see assets.list) `asset` परिसंपत्ति आईडी है (aset.list देखें) +@msg `asset` is the asset id (see assets.list) `asset` परिसंपत्ति आईडी है (assets.list देखें) @msg `at` must be [x, y] `at` होना चाहिए [x, y] @msg `at` must be a byte offset `at` to be a byte ऑफसेट @msg `autoLeading` must be a number `autoLeading` को संख्या होना चाहिए @@ -6169,7 +6169,7 @@ antiAlias Sharp शार्प @msg closed must be a boolean closed: बंद होना चाहिए एक boolean @msg closing needs three anchors closing: बंद करने की जरूरत है तीन एंकर @msg collapsed must be true or false collapsed को true या false होना चाहिए -@msg color.profile: no RGB or CMYK profile is called “{profile}” Color.profile: कोई RGB या CMYK प्रोफ़ाइल को "{profile}" कहा जाता है। +@msg color.profile: no RGB or CMYK profile is called “{profile}” color.profile: "{profile}" नाम की कोई RGB या CMYK प्रोफ़ाइल नहीं है @msg colorMode must be rgb or cmyk, not `{m}` colorMode को rgb या cmyk होना चाहिए, `{m}` नहीं @msg colorModel must be {own} (the document's mode), grayscale or bitmap colorModel को {own} (डॉक्यूमेंट का मोड), grayscale या bitmap होना चाहिए @msg colorTable.{what}: `{h}` is not a colour such as "#ff8800" colorTable.{what}: `{h}`, "#ff8800" जैसा रंग नहीं है @@ -6497,11 +6497,11 @@ antiAlias Sharp शार्प @msg highlight two or more rows in one layer or group एक लेयर या समूह में दो या अधिक पंक्तियों को हाइलाइट करें @msg highlight two or more rows to merge दो या अधिक पंक्तियों को मर्ज करने के लिए हाइलाइट करें @msg HTML Text applies to object slices of type only एचटीएमएल टेक्स्ट केवल टाइप के ऑब्जेक्ट स्लाइस पर लागू होता है -@msg icon docks a panel in the icon column: use window.panel.dock आइकन कॉलम में एक पैनल डॉक करता है: विंडो का उपयोग करें.पैनल.dock +@msg icon docks a panel in the icon column: use window.panel.dock icon पैनल को आइकन कॉलम में डॉक करता है: window.panel.dock का उपयोग करें @msg icon must be true or false icon को true या false होना चाहिए @msg icon only docks a panel in the icon column, with no anchor आइकन केवल आइकन कॉलम में एक पैनल को डॉक करता है, जिसमें कोई एंकर नहीं होता है @msg id {value} is a layer, not an object Id {value} एक लेयर है, कोई ऑब्जेक्ट नहीं है -@msg id {value} is a layer, not an object; move layers with layer.move Id {value} एक लेयर है, कोई ऑब्जेक्ट नहीं है; लेयर के साथ लेयर्स को स्थानांतरित करें। +@msg id {value} is a layer, not an object; move layers with layer.move id {value} एक लेयर है, ऑब्जेक्ट नहीं; लेयर्स को layer.move से स्थानांतरित करें @msg id must be a dimension id id: आईडी एक आयाम आईडी होना चाहिए @msg Identify Objects By is XML ID: the name must be a valid XML ID (start with a letter, underscore or colon; no spaces) ऑब्जेक्ट्स को XML ID से पहचानें: नाम एक वैध XML ID होना चाहिए (एक पत्र, अंडरस्कोर या कॉलोन के साथ शुरू; कोई स्थान नहीं) @msg ids must contain 1–10000 object ids ids में 1–10000 ऑब्जेक्ट ids होना चाहिए @@ -6610,7 +6610,7 @@ antiAlias Sharp शार्प @msg kerning must be a number, "auto", or "optical" kerning एक संख्या, "auto", या "optical" होना चाहिए @msg keywords must be a list of words or a comma-separated string keywords: कीवर्ड शब्दों की एक सूची होना चाहिए या एक अल्पसंख्यक स्ट्रिंग होना चाहिए @msg keywords must be at most {MAX_KEYWORD} characters, without control characters keywords: कीवर्ड नियंत्रण वर्णों के बिना, अधिकांश {MAX_KEYWORD} वर्णों पर होना चाहिए -@msg kind must be 1, 2 or 3, or give a preset `name` (see perspective.presets.list) kind: टाइप 1, 2 या 3 होना चाहिए, या प्रीसेट `name` देना चाहिए (see पर्सपेक्टिव.presets.list) +@msg kind must be 1, 2 or 3, or give a preset `name` (see perspective.presets.list) kind 1, 2 या 3 होना चाहिए, या प्रीसेट `name` दें (perspective.presets.list देखें) @msg kind must be graphic, fillColor, strokeColor, fillGradient, strokeGradient, fillPattern, strokePattern, charStyle or paraStyle kind को graphic, fillColor, strokeColor, fillGradient, strokeGradient, fillPattern, strokePattern, charStyle या paraStyle होना चाहिए @msg knockout must be "on", "off", "neutral" or a bool, not {v} knockout: नॉकआउट को "on", "off", "neutral" या एक बोल, न {v} होना चाहिए @msg lang must be one of {_1} lang: लैंग को {_1} में से एक होना चाहिए @@ -6675,7 +6675,7 @@ antiAlias Sharp शार्प @msg missing `gid` (a glyph id, or null for the default glyph) लापता `gid` (a glyph id, या डिफ़ॉल्ट glyph के लिए null) @msg missing `group` लापता `group` @msg missing `id` लापता `id` -@msg missing `id` (see plugin.list) अनुपलब्ध `id` (information.list) +@msg missing `id` (see plugin.list) अनुपलब्ध `id` (plugin.list देखें) @msg missing `id`: give one, or select one type object लापता `id`: एक देना, या एक प्रकार का ऑब्जेक्ट चुनें @msg missing `index` (a point index, or null to clear) लापता `index` (a बिंदु सूचकांक, या स्पष्ट करने के लिए null) @msg missing `index` (a stop index, or null to clear) लापता `index` (a स्टॉप इंडेक्स, या स्पष्ट करने के लिए null) @@ -6790,7 +6790,7 @@ antiAlias Sharp शार्प @msg no artboards named नामित कोई आर्टबोर्ड नहीं @msg no artwork कोई आर्टवर्क नहीं @msg no asset {id} कोई परिसंपत्ति {id} -@msg no asset {id} (see assets.list) कोई परिसंपत्ति {id} (Ession.list) नहीं है। +@msg no asset {id} (see assets.list) कोई परिसंपत्ति {id} नहीं है (assets.list देखें) @msg no assets to export निर्यात करने के लिए कोई संपत्ति नहीं @msg no assets yet: collect art for export first (assets.add) अभी तक कोई संपत्ति नहीं: पहले निर्यात के लिए कला इकट्ठा (assets.add) @msg no blend options कोई मिश्रण ऑप्शन्स नहीं @@ -6887,7 +6887,7 @@ antiAlias Sharp शार्प @msg no pattern named `{choice}` `{choice}` नाम का कोई पैटर्न नहीं @msg no pattern swatch `{name}` कोई पैटर्न नहीं `{name}` @msg no PDF preset named `{n}` कोई PDF प्रीसेट नहीं है जिसका नाम `{n}` है -@msg no perspective grid preset named `{b}` (see perspective.presets.list) कोई पर्सपेक्टिव ग्रिड प्रीसेट जिसका नाम `{b}` है (see पर्सपेक्टिव.presets.list) +@msg no perspective grid preset named `{b}` (see perspective.presets.list) `{b}` नाम का कोई पर्सपेक्टिव ग्रिड प्रीसेट नहीं है (perspective.presets.list देखें) @msg no perspective grid preset named `{n}` कोई पर्सपेक्टिव ग्रिड प्रीसेट जिसका नाम `{n}` है @msg no perspective grid preset named `{name}` कोई पर्सपेक्टिव ग्रिड प्रीसेट जिसका नाम `{name}` है @msg no plug-in {0} is installed कोई प्लग-इन {0} स्थापित नहीं है @@ -6940,7 +6940,7 @@ antiAlias Sharp शार्प @msg no selection bounds कोई सिलेक्शन सीमा नहीं @msg no series {i} कोई श्रृंखला {i} @msg no similar objects found (rotated or reflected copies are not matched); change the Global Edit Options and try again कोई समान ऑब्जेक्ट नहीं पाया (घूर्णित या परिलक्षित प्रतियां मिलान नहीं की जाती हैं); वैश्विक संपादन ऑप्शन्स बदलें और फिर से प्रयास करें -@msg no slice {n} in the image (see slice.list) इमेज में कोई स्लाइस {n} नहीं ( स्लाइसलिस्ट देखें) +@msg no slice {n} in the image (see slice.list) इमेज में कोई स्लाइस {n} नहीं है (slice.list देखें) @msg no slice selected सिलेक्टेड कोई स्लाइस नहीं @msg no source art कोई स्रोत कला @msg no stop {i} (the gradient has {n}) नहीं रोक {i} (ग्रेडेंट {n} है) @@ -6950,7 +6950,7 @@ antiAlias Sharp शार्प @msg no such action step ऐसी कोई कार्रवाई नहीं @msg no such anchor ऐसा कोई एंकर नहीं @msg no such artboard ऐसा कोई आर्टबोर्ड नहीं -@msg no such assets (see assets.list) ऐसी कोई संपत्ति नहीं (देखें परिसंपत्तियां)। +@msg no such assets (see assets.list) ऐसी कोई परिसंपत्ति नहीं है (assets.list देखें) @msg no such color ऐसा कोई रंग नहीं @msg no such document ऐसा कोई डॉक्यूमेंट नहीं @msg no such frame anchor, or the frame would reach past the canvas इस तरह के फ्रेम एंकर नहीं, या फ्रेम कैनवास तक पहुंच जाएगा @@ -7130,7 +7130,7 @@ antiAlias Sharp शार्प @msg only this Affinity file's embedded preview could be read: use File › Open to see it with its warning, or export SVG or PDF from Affinity first केवल इस Affinity फ़ाइल के एम्बेडेड प्रीव्यू को पढ़ा जा सकता है: फ़ाइल का उपयोग करें > इसे अपनी चेतावनी के साथ देखने के लिए ओपन करें, या पहले Affinity से SVG या PDF निर्यात करें @msg onto must name a floating panel onto: पर एक फ्लोटिंग पैनल का नाम होना चाहिए @msg onto must name a panel floating in another group onto: किसी अन्य समूह में फ्लोटिंग पैनल का नाम होना चाहिए -@msg onto, above, below, icon and a column place belong to window.panel.float and window.panel.dock ऊपर, नीचे, आइकन और एक स्तंभ स्थान खिड़की से संबंधित है। पैनल.फ्लोट और विंडो.पैनल.डॉक +@msg onto, above, below, icon and a column place belong to window.panel.float and window.panel.dock onto, above, below, icon और column स्थान window.panel.float और window.panel.dock के लिए हैं @msg onto, above, below, icon and a column place take no anchor, side, zone or before ऊपर, नीचे, आइकन और एक स्तंभ स्थान पर कोई एंकर, साइड, जोन या पहले नहीं होता है @msg onto, above, below, icon and a column place take no x, y, width or height ऊपर, नीचे, आइकन और एक स्तंभ स्थान पर कोई एक्स, वाई, चौड़ाई या ऊंचाई नहीं होती है @msg open a document to look for its linked files अपनी लिंक्ड फ़ाइलों को देखने के लिए एक डॉक्यूमेंट ओपन करें @@ -7144,10 +7144,10 @@ antiAlias Sharp शार्प @msg outlineText {v}: true or false outlineText {v}: true या false @msg output intent profile: {e} उत्पादन आशय प्रोफ़ाइल: {e} @msg output size ({what} is {len} bytes, limit {max}) उत्पादन का आकार ({what} {len} बाइट्स है, {max} को सीमित करें) -@msg output.destination: {_1} files are CMYK, and “{name}” is an RGB profile उत्पादन: {_1} फ़ाइलें CMYK हैं, और "{name}" एक RGB प्रोफ़ाइल है -@msg output.destination: {e} उत्पादन.destination: {e} -@msg output.destination: no RGB or CMYK profile is called “{name}” आउटपुट: कोई RGB या CMYK प्रोफ़ाइल को "{name}" कहा जाता है। -@msg output.inks: no ink is set to print आउटपुट.ink: प्रिंट करने के लिए कोई स्याही सेट नहीं है +@msg output.destination: {_1} files are CMYK, and “{name}” is an RGB profile output.destination: {_1} फ़ाइलें CMYK हैं, और "{name}" एक RGB प्रोफ़ाइल है +@msg output.destination: {e} output.destination: {e} +@msg output.destination: no RGB or CMYK profile is called “{name}” output.destination: "{name}" नाम की कोई RGB या CMYK प्रोफ़ाइल नहीं है +@msg output.inks: no ink is set to print output.inks: प्रिंट करने के लिए कोई स्याही सेट नहीं है @msg output.outputIntent: “{name}” is a grey profile, which can't be a {std} output intent output.outputIntent: “{name}” ग्रे प्रोफ़ाइल है, जो {std} आउटपुट इंटेंट नहीं हो सकती @msg output.outputIntent: {std} files print in CMYK, and “{name}” is an RGB profile output.outputIntent: {std} फ़ाइलें CMYK में प्रिंट होती हैं और “{name}” RGB प्रोफ़ाइल है @msg output.outputIntent: no profile is called “{name}”, and a {std} output intent embeds its profile output.outputIntent: “{name}” नाम की प्रोफ़ाइल नहीं है और {std} आउटपुट इंटेंट अपनी प्रोफ़ाइल एम्बेड करता है @@ -7483,7 +7483,7 @@ antiAlias Sharp शार्प @msg text.{key} `{v}`: use "{_1}" or "{_2}" Text.{key} `{v}`: "{_1}" या "{_2}" का उपयोग करें। @msg text.replaceSpaces must be a whole number from 2 to 100 text.replaceSpaces को 2 से 100 के बीच पूर्णांक होना चाहिए @msg textureImage: {e} textureImage: {e} -@msg textureImage: give {path} or {name, dataBase64} of an image file, or a texture as effect.list gives it textureImage: एक इमेज फ़ाइल के {path} या {name, dataBase64}, या इफ़ेक्ट के रूप में बनावट देते हैं। +@msg textureImage: give {path} or {name, dataBase64} of an image file, or a texture as effect.list gives it textureImage: किसी इमेज फ़ाइल का {path} या {name, dataBase64} दें, या effect.list द्वारा दिया गया टेक्सचर दें @msg that anchor can't slide: an end of an open path has nowhere to go कि एंकर स्लाइड नहीं कर सकते: एक खुले रास्ते का अंत कहीं नहीं जाना है @msg that document is no longer open यह डॉक्यूमेंट अब खुला नहीं है @msg that makes more than {MAX_PIECES} slices जो {MAX_PIECES} स्लाइस से अधिक बनाता है diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 79cbd7a648..baca06cacf 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -2510,6 +2510,61 @@ fn translated_messages_keep_the_keys_and_values_their_english_names() { assert!(missing.is_empty(), "{} rows drop a key or value their English names:\n{}", missing.len(), missing.join("\n")); } +/// The command ids that `s` names outside its backticked spans, such as `assets.list` or +/// `window.panel.dock`: words of two or more dot-separated parts, each an ASCII letter or digit +/// run that starts with a lowercase letter. +fn command_ids(s: &str) -> Vec<&str> { + let mut ids = Vec::new(); + for part in s.split('`').step_by(2) { + for word in part.split(|c: char| !(c.is_ascii_alphanumeric() || c == '.' || c == '_')) { + let word = word.trim_end_matches('.'); + let segments: Vec<&str> = word.split('.').collect(); + let dotted = segments.len() > 1 + && segments + .iter() + .all(|seg| seg.chars().next().is_some_and(|c| c.is_ascii_lowercase()) && seg.chars().all(|c| c.is_ascii_alphanumeric())); + if dotted && word != "e.g" && word != "i.e" { + ids.push(word); + } + } + } + ids +} + +#[test] +fn command_ids_finds_dotted_ids_outside_backticks() { + assert_eq!(command_ids("no slice {n} in the image (see slice.list)"), ["slice.list"]); + assert_eq!(command_ids("use window.panel.dock."), ["window.panel.dock"]); + assert_eq!(command_ids("output.destination: {e}"), ["output.destination"]); + assert_eq!(command_ids("(assets.list.old देखें)"), ["assets.list.old"]); + assert_eq!(command_ids("see `plugin.list`, e.g. 1.5 or {name}.svg"), Vec::<&str>::new()); +} + +/// A translated status or error message keeps each command id its English text names without +/// backticks, spelled as the English spells it, since that is the id a script or the command +/// palette runs. +#[test] +fn translated_messages_keep_the_command_ids_their_english_names() { + let mut missing = Vec::new(); + for l in &LANGUAGES { + let (entries, _) = parse_entries(l.source); + for (ctx, src, tr) in entries.iter().filter(|(ctx, _, _)| ctx == "@msg" || ctx == "@msgplural") { + let plural = ctx == "@msgplural"; + let english = if plural { src.rsplit('|').next().unwrap_or(src) } else { src.as_str() }; + let forms: Vec<&str> = if plural { tr.split('|').collect() } else { vec![tr.as_str()] }; + for form in forms { + let kept: Vec<&str> = command_ids(form).into_iter().chain(backticked(form)).collect(); + for id in command_ids(english) { + if !kept.contains(&id) { + missing.push(format!("{}: {id} in {src:?} -> {form:?}", l.code)); + } + } + } + } + } + assert!(missing.is_empty(), "{} rows drop a command id their English names:\n{}", missing.len(), missing.join("\n")); +} + /// Languages whose catalogs translate status and error messages; [`untranslated_report`] lists /// the messages each one lacks. const COMPLETE_MESSAGES: &[&str] = &[ diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index d45a171cc6..a9736063fe 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -4471,7 +4471,7 @@ axis Both Her İkisi @msg `prefs.import` runs on its own, not as a batch step `prefs.import` tek başına çalışır, toplu iş adımı olarak değil @msg unknown preset (one of {_1}) bilinmeyen ön ayar ({_1}'den biri) @msg unknown preset `{name}` (high, medium, low or a saved one: see flattener.presets.list) bilinmeyen ön ayar `{name}` (yüksek, orta, düşük veya kaydedilmiş bir ayar: bkz. flattener.presets.list) -@msg unknown preset `{name}` (see flattener.presets.list) bilinmeyen ön ayar `{name}` (bkz. düzleştirici.presets.list) +@msg unknown preset `{name}` (see flattener.presets.list) bilinmeyen ön ayar `{name}` (bkz. flattener.presets.list) @msg unknown preset `{name}` (see webExport.presets.list) bilinmeyen ön ayar `{name}` (bkz. webExport.presets.list) @msg unknown preset `{name}`: not a built-in or saved preset (see imageTrace.presets) bilinmeyen ön ayar `{name}`: yerleşik ya da kayıtlı bir ön ayar değil (bkz. imageTrace.presets) @msg unknown side `{other}` (left|right|top|bottom) bilinmeyen taraf `{other}` (sol|sağ|üst|alt) From b967408a09acdb7d15142bcfe7b46a338017336d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 15:39:28 -0800 Subject: [PATCH 19/38] Vector Halftone: a parameter of the wrong type is refused object.vectorHalftone read frequency, angle, invert, clip and keepOriginal with readers that fall back to the default for a value of the wrong type, so {"frequency": "60"} drew a 20 lpi screen. shape and mode given as a non-string also fell back to circle and mono. Each of these is now an error and the document is left as it was. A null value, color included, still stands for the default. --- crates/engine/src/cmd/halftone.rs | 14 +++++++------- crates/engine/src/tests/halftone.rs | 26 ++++++++++++++++++++++++++ 2 files changed, 33 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/cmd/halftone.rs b/crates/engine/src/cmd/halftone.rs index 0c1d36d35d..b54e92932c 100644 --- a/crates/engine/src/cmd/halftone.rs +++ b/crates/engine/src/cmd/halftone.rs @@ -11,7 +11,7 @@ use vectorcraft_doc::Node; use vectorcraft_render::effects::addons::halftone::{DotShape, Halftone, art_outline, dot_nodes}; use super::edit::selected_roots; -use super::{CommandSpec, EngineError, Result, Session, bad, bool_or, cmd, color_value, f64_or, has_selection, str_param}; +use super::{CommandSpec, EngineError, Result, Session, bad, cmd, color_value, has_selection, number_or, switch_or, text_param}; pub fn specs() -> Vec { vec![cmd!( @@ -27,28 +27,28 @@ pub fn specs() -> Vec { fn halftone(s: &mut Session, p: &Value) -> Result { const C: &str = "object.vectorHalftone"; - let shape = match str_param(p, "shape") { + let shape = match text_param(p, "shape", C)? { Some(v) => DotShape::parse(v).ok_or_else(|| bad(C, format!("unknown shape `{v}` (circle|ellipse|square|diamond|line)")))?, None => DotShape::Circle, }; - let frequency = f64_or(p, "frequency", 20.0); + let frequency = number_or(p, "frequency", 20.0, C)?; if !(1.0..=300.0).contains(&frequency) { return Err(bad(C, "frequency must be between 1 and 300 lines per inch")); } - let angle = f64_or(p, "angle", 45.0); + let angle = number_or(p, "angle", 45.0, C)?; if !angle.is_finite() { return Err(bad(C, "invalid angle")); } - let mono = match str_param(p, "mode").unwrap_or("mono") { + let mono = match text_param(p, "mode", C)?.unwrap_or("mono") { "mono" => true, "cmyk" => false, other => return Err(bad(C, format!("unknown mode `{other}` (mono|cmyk)"))), }; let color = match p.get("color") { + None | Some(Value::Null) => Color::BLACK, Some(v) => color_value(v).ok_or_else(|| bad(C, "invalid color"))?, - None => Color::BLACK, }; - let (invert, clip, keep) = (bool_or(p, "invert", false), bool_or(p, "clip", true), bool_or(p, "keepOriginal", false)); + let (invert, clip, keep) = (switch_or(p, "invert", false, C)?, switch_or(p, "clip", true, C)?, switch_or(p, "keepOriginal", false, C)?); let ht = Halftone { shape, frequency, angle, mono, color, from_art: false, invert, clip }; let roots = selected_roots(s)?; diff --git a/crates/engine/src/tests/halftone.rs b/crates/engine/src/tests/halftone.rs index caef57ddb4..d836502baa 100644 --- a/crates/engine/src/tests/halftone.rs +++ b/crates/engine/src/tests/halftone.rs @@ -65,3 +65,29 @@ fn halftone_options() { assert!(s.execute("object.vectorHalftone", &bad).is_err(), "{bad}"); } } + +#[test] +fn halftone_refuses_a_param_of_the_wrong_type() { + for bad in [ + json!({"frequency": "60"}), + json!({"angle": "30"}), + json!({"shape": 1}), + json!({"mode": true}), + json!({"invert": "true"}), + json!({"clip": "false"}), + json!({"keepOriginal": 1}), + json!({"color": 0}), + ] { + let mut s = session(); + let id = red_rect(&mut s); + let before = s.doc().unwrap().doc.clone(); + assert!(s.execute("object.vectorHalftone", &bad).is_err(), "{bad}"); + assert_eq!(s.doc().unwrap().doc, before, "{bad} changed the document"); + assert!(s.doc().unwrap().doc.node(id).is_some()); + } + // Null stands for an omitted value. + let mut s = session(); + red_rect(&mut s); + let p = json!({"frequency": null, "angle": null, "shape": null, "mode": null, "color": null, "invert": null, "clip": null, "keepOriginal": null}); + assert!(s.execute("object.vectorHalftone", &p).is_ok()); +} From b33c004fb02cec0859648b6af2029daae329c6cf Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 15:47:06 -0800 Subject: [PATCH 20/38] Tabs: indent drags on threaded frames follow the story's order and set a split paragraph once With the Selection tool on several frames of one threaded story, the Tabs panel listed the paragraphs to change in the order the frames were selected, and listed each frame's paragraphs separately. A marker drag over mixed indents then ran its per-paragraph steps out of story order, so a step that made text reflow could move a later step's paragraph, and a paragraph that runs on from one frame into the next got two steps. After Type tool Select All the split paragraph also got two. The panel now lists each paragraph of a story once, in story order, by its last piece with text in a selected frame. With the Selection tool only the paragraphs with text in a selected frame change, so a frame selected alone that starts or ends inside a paragraph sets it. Docs: docs/target-app-parity.md. --- crates/ui-egui/src/panels/tabs.rs | 87 +++++++++++++--- crates/ui-egui/src/panels/tabs/tests.rs | 133 ++++++++++++++++++++++++ docs/target-app-parity.md | 1 + 3 files changed, 206 insertions(+), 15 deletions(-) diff --git a/crates/ui-egui/src/panels/tabs.rs b/crates/ui-egui/src/panels/tabs.rs index 57a99e433b..7e58a218a5 100644 --- a/crates/ui-egui/src/panels/tabs.rs +++ b/crates/ui-egui/src/panels/tabs.rs @@ -4,9 +4,11 @@ //! same distance. A stop placed or dragged on the ruler lands on the nearest whole point. With Snap //! to Unit on, or Shift held, it lands on the ruler's nearest tick. +use std::collections::HashSet; + use egui::{Sense, Stroke, Ui, vec2}; use serde_json::{Value, json}; -use vectorcraft_doc::{Node, NodeKind, ParaStyle, TabAlign, TabStop, TextKind}; +use vectorcraft_doc::{Document, Node, NodeId, NodeKind, ParaStyle, TabAlign, TabStop, TextKind, TextObject}; use super::{first_selected, pstate, set_pstate}; use crate::VectorcraftApp; @@ -64,40 +66,95 @@ struct IndentTarget { level: f64, } +fn indent_target(id: NodeId, text: &TextObject, i: usize, start: usize) -> IndentTarget { + let para = text.para_at(i); + let left = para.laid_out_left_indent(); + IndentTarget { id: id.0, start, left, first_line: para.first_line_indent, level: left - para.left_indent } +} + fn append_indent_targets(node: &Node, range: std::ops::Range, targets: &mut Vec) { let NodeKind::Text(text) = &node.kind else { return }; let plain = text.plain_text(); let mut starts = vec![0]; starts.extend(plain.bytes().enumerate().filter_map(|(i, c)| (c == b'\n').then_some(i + 1))); - targets.extend(range.filter_map(|i| { - let para = text.para_at(i); - let left = para.laid_out_left_indent(); - Some(IndentTarget { id: node.id.0, start: *starts.get(i)?, left, first_line: para.first_line_indent, level: left - para.left_indent }) - })); + targets.extend(range.filter_map(|i| Some(indent_target(node.id, text, i, *starts.get(i)?)))); } -/// Paragraphs touched by the Type selection (every paragraph of every frame after Select All in -/// threaded text), or all paragraphs of selected text objects. +/// One target for each paragraph of `story` (its frames in thread order), in story order. Where +/// one frame ends and the next begins, the last paragraph of the one and the first of the next are +/// pieces of one story paragraph: a paragraph that runs on into the next frame, or an empty piece +/// after a frame's last paragraph break. Such a paragraph is targeted once, by its last piece with +/// text in a frame that `selected` takes, the piece whose style the story keeps when it flows again. +/// A paragraph whose text lies only in frames that `selected` leaves out is not targeted. An empty +/// paragraph takes its style from its last piece when the story flows again, so it is targeted by +/// that piece when `selected` takes its frame, and otherwise not. +fn append_story_targets(doc: &Document, story: &[NodeId], selected: impl Fn(NodeId) -> bool, targets: &mut Vec) { + /// The part of a story paragraph in one frame: paragraph `index` there, starting at byte `start`. + struct Piece<'a> { + id: NodeId, + text: &'a TextObject, + index: usize, + start: usize, + has_text: bool, + } + // Each story paragraph's pieces, in thread order. + let mut paragraphs: Vec>> = vec![]; + for frame in story.iter().filter_map(|id| doc.node(*id)) { + let NodeKind::Text(text) = &frame.kind else { continue }; + let plain = text.plain_text(); + let mut start = 0; + for (index, part) in plain.split('\n').enumerate() { + let piece = Piece { id: frame.id, text, index, start, has_text: !part.is_empty() }; + start += part.len() + 1; + match paragraphs.last_mut() { + Some(last) if index == 0 => last.push(piece), + _ => paragraphs.push(vec![piece]), + } + } + } + for pieces in ¶graphs { + let pick = if pieces.iter().any(|p| p.has_text) { + pieces.iter().rev().find(|p| p.has_text && selected(p.id)) + } else { + pieces.last().filter(|p| selected(p.id)) + }; + if let Some(p) = pick { + targets.push(indent_target(p.id, p.text, p.index, p.start)); + } + } +} + +/// Paragraphs touched by the Type selection (every paragraph of the story after Select All in +/// threaded text), or all paragraphs of selected text objects. Each paragraph of a threaded story +/// is listed once, in story order ([`append_story_targets`]). fn indent_targets(app: &VectorcraftApp, node: &Node) -> Vec { let mut targets = Vec::new(); if let Some((_, a, b)) = super::character::text_editing(app) { if let (Some(story), Some(st)) = (super::character::text_story(app), app.session.active()) { - for frame in story.iter().filter_map(|id| st.doc.node(*id)) { - if let NodeKind::Text(text) = &frame.kind { - append_indent_targets(frame, 0..text.paragraph_count(), &mut targets); - } - } + append_story_targets(&st.doc, &story, |_| true, &mut targets); } else if let NodeKind::Text(text) = &node.kind { append_indent_targets(node, text.paragraphs_in(a, b), &mut targets); } } else if let Some(st) = app.session.active() { + // The selected text objects and the text in selected groups, each once. + let mut frames = Vec::new(); + let mut taken = HashSet::new(); for selected in st.selection.objects.iter().filter_map(|id| st.doc.node(*id)) { selected.walk(&mut |child| { - if let NodeKind::Text(text) = &child.kind { - append_indent_targets(child, 0..text.paragraph_count(), &mut targets); + if matches!(child.kind, NodeKind::Text(_)) && taken.insert(child.id) { + frames.push(child.id); } }); } + let mut done = HashSet::new(); + for id in frames { + if done.contains(&id) { + continue; + } + let story = st.doc.story_of(id); + done.extend(story.iter().copied()); + append_story_targets(&st.doc, &story, |f| taken.contains(&f), &mut targets); + } } targets } diff --git a/crates/ui-egui/src/panels/tabs/tests.rs b/crates/ui-egui/src/panels/tabs/tests.rs index bc71e34080..9e96866ab2 100644 --- a/crates/ui-egui/src/panels/tabs/tests.rs +++ b/crates/ui-egui/src/panels/tabs/tests.rs @@ -538,6 +538,139 @@ fn indent_markers_after_select_all_follow_text_that_reflows_into_the_next_frame( } } +/// A story of twelve paragraphs that wrap, threaded through three frames: the first two frames each +/// end inside a paragraph, which runs on into the next frame. → the app and the frames in thread +/// order. +fn split_story_app() -> (VectorcraftApp, [u64; 3]) { + let mut app = VectorcraftApp::new(Session::new(), Default::default()); + app.run("file.new", json!({"width": 900, "height": 1000})).unwrap(); + // Each paragraph takes more lines than a short frame holds. + let words = "aaa bbb ccc ddd eee fff ggg hhh iii jjj ".repeat(3); + let story = (1..=12).map(|i| format!("p{i} {}", words.trim_end())).collect::>().join("\n"); + let a = app.run("text.create", json!({"x": 10, "y": 10, "text": story, "size": 12, "area": {"width": 150, "height": 50}})).unwrap()["id"] + .as_u64() + .unwrap(); + let b = app.run("text.thread.add", json!({"from": a, "rect": [300, 10, 150, 50]})).unwrap()["id"].as_u64().unwrap(); + let c = app.run("text.thread.add", json!({"from": b, "rect": [600, 10, 250, 950]})).unwrap()["id"].as_u64().unwrap(); + for id in [b, c] { + assert!(text_of(&app, id).first_para_continues, "frame {id} starts inside a paragraph: {:?}", text_of(&app, id).plain_text()); + } + (app, [a, b, c]) +} + +fn text_of(app: &VectorcraftApp, id: u64) -> vectorcraft_doc::TextObject { + match &app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(id)).unwrap().kind { + NodeKind::Text(t) => (**t).clone(), + _ => panic!("not text"), + } +} + +/// Each paragraph of the story of `frames` by its first word, with its left indent and first-line +/// position, counted once; each piece of a paragraph split between frames has the same values. +fn story_paragraphs(app: &VectorcraftApp, frames: &[u64]) -> Vec<(String, f64, f64)> { + let mut out: Vec<(String, f64, f64)> = vec![]; + for (k, id) in frames.iter().enumerate() { + let t = text_of(app, *id); + for (i, text) in t.plain_text().split('\n').enumerate() { + let p = t.para_at(i); + let values = (p.left_indent, p.left_indent + p.first_line_indent); + if i == 0 && k > 0 && t.first_para_continues { + let last = out.last().unwrap(); + assert_eq!((last.1, last.2), values, "both pieces of {} agree", last.0); + } else if !text.is_empty() { + out.push((text.split(' ').next().unwrap_or_default().to_string(), values.0, values.1)); + } + } + } + out +} + +/// Where each target is in the story: its frame's place in `frames` and its start there. +fn story_positions(targets: &[IndentTarget], frames: &[u64]) -> Vec<(usize, usize)> { + targets.iter().map(|p| (frames.iter().position(|f| *f == p.id).unwrap(), p.start)).collect() +} + +/// With the Selection tool on every frame of a threaded story, selected last frame first, the +/// indent markers list each paragraph of the story once, in the story's order, and a marker drag +/// over mixed indents sets every paragraph in one undo step, the two split paragraphs included. +#[test] +fn indent_markers_on_selected_threaded_frames_follow_the_story_and_set_a_split_paragraph_once() { + let (mut app, [a, b, c]) = split_story_app(); + app.run("text.setFormat", json!({"ids": [c], "leftIndent": 10})).unwrap(); + app.run("select.set", json!({"ids": [c, b, a]})).unwrap(); + assert_eq!(app.session.active().unwrap().selection.objects.iter().map(|id| id.0).collect::>(), vec![c, b, a]); + let before = story_paragraphs(&app, &[a, b, c]); + assert_eq!(before.len(), 12, "{before:?}"); + assert!(before.iter().any(|p| p.1 == 0.0) && before.iter().any(|p| p.1 == 10.0), "{before:?}"); + let (node, para, span) = current_para(&app).unwrap(); + let targets = indent_targets(&app, &node); + let positions = story_positions(&targets, &[a, b, c]); + assert_eq!(positions.len(), 12, "one target for each paragraph of the story: {positions:?}"); + assert!(positions.windows(2).all(|w| w[0] < w[1]), "the targets follow the story: {positions:?}"); + let undo = app.session.active().unwrap().history.undo.len(); + set_marker(&mut app, IndentMarker::Upper, 60.0, ¶, span, &targets, false); + assert_eq!(app.session.active().unwrap().history.undo.len(), undo + 1); + let after = story_paragraphs(&app, &[a, b, c]); + assert_eq!(after.iter().map(|p| &p.0).collect::>(), before.iter().map(|p| &p.0).collect::>()); + for (was, now) in before.iter().zip(&after) { + assert_eq!((now.1, now.2), (was.1, 60.0), "{} keeps its left indent and starts at 60 pt: {after:?}", now.0); + } +} + +/// After Select All in threaded text, a paragraph split between two frames is one target. +#[test] +fn indent_markers_after_select_all_list_a_split_paragraph_once() { + let (mut app, [a, b, c]) = split_story_app(); + app.run("select.set", json!({"ids": [a]})).unwrap(); + app.session.select_tool("type", Default::default()).unwrap(); + app.session.set_tool_option("textSelection", &json!({"editing": a, "anchor": 0, "caret": 0})); + app.run("select.all", json!({})).unwrap(); + let ids = [a, b, c].map(vectorcraft_doc::NodeId); + assert_eq!(super::super::character::text_story(&app), Some(ids.to_vec())); + let (node, _, _) = current_para(&app).unwrap(); + let positions = story_positions(&indent_targets(&app, &node), &[a, b, c]); + assert_eq!(positions.len(), 12, "{positions:?}"); + assert!(positions.windows(2).all(|w| w[0] < w[1]), "{positions:?}"); +} + +/// With the Selection tool on some frames of a threaded story, only the paragraphs with text in +/// those frames are listed, each once: a selected frame that starts inside a paragraph lists that +/// paragraph, and so does a selected frame that ends inside one. Text in a selected group is +/// listed with the story's frames, and an empty text object keeps its one paragraph. +#[test] +fn indent_markers_on_some_threaded_frames_list_their_paragraphs_once() { + let (mut app, [a, b, c]) = split_story_app(); + let count = |app: &VectorcraftApp, id: u64| text_of(app, id).paragraph_count(); + let targets_of = |app: &mut VectorcraftApp, ids: Vec| { + app.run("select.set", json!({"ids": ids})).unwrap(); + let (node, _, _) = current_para(app).unwrap(); + story_positions(&indent_targets(app, &node), &[a, b, c]) + }; + // The continuing frame alone: its first paragraph is the one the frame before ends inside. + let only_b = targets_of(&mut app, vec![b]); + assert_eq!(only_b.len(), count(&app, b), "{only_b:?}"); + assert_eq!(only_b.first(), Some(&(1, 0)), "{only_b:?}"); + let only_a = targets_of(&mut app, vec![a]); + assert_eq!(only_a.len(), count(&app, a), "{only_a:?}"); + // Two frames that share a paragraph list it once, by the later frame's piece. + let both = targets_of(&mut app, vec![c, a, b]); + assert_eq!(both.len(), count(&app, a) + count(&app, b) + count(&app, c) - 2, "{both:?}"); + assert!(both.windows(2).all(|w| w[0] < w[1]), "{both:?}"); + // The first and last frames of the story, and a grouped empty text object besides. + let empty = app.run("text.create", json!({"x": 10, "y": 900, "text": "", "area": {"width": 100, "height": 40}})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [empty, c]})).unwrap(); + let group = app.run("object.group", json!({})).unwrap()["id"].as_u64().unwrap(); + app.run("select.set", json!({"ids": [group, a]})).unwrap(); + let node = app.session.active().unwrap().doc.node(vectorcraft_doc::NodeId(a)).unwrap().clone(); + let targets = indent_targets(&app, &node); + let ids: Vec = targets.iter().map(|p| p.id).collect(); + assert_eq!(ids.iter().filter(|id| **id == empty).count(), 1, "{ids:?}"); + let story: Vec = targets.into_iter().filter(|p| p.id != empty).collect(); + let positions = story_positions(&story, &[a, b, c]); + assert_eq!(positions.len(), count(&app, a) + count(&app, c), "{positions:?}"); + assert!(positions.windows(2).all(|w| w[0] < w[1]), "{positions:?}"); +} + #[test] fn lower_marker_bounds_cover_each_touched_first_line() { let targets = [ diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index b4c949f742..fc81643b62 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -640,6 +640,7 @@ since 2026-10-01. - **Names of new styles and symbols:** `charStyle.new` and `paraStyle.new` trim the white space around the name they are given, as `charStyle.rename` and `paraStyle.rename` do, and refuse a name that is then empty; Duplicate names its copy from the trimmed name. `symbol.new` and `symbol.duplicate` trim the name as Symbol Options does, and `library.use` adds a library's text style under its trimmed name. Public reference: [Character and paragraph styles](https://web.archive.org/web/20260825113735/https://helpx.adobe.com/illustrator/using/character-paragraph-styles.html). - **Naming a new text style first:** Alt-click on New in the Character Styles or Paragraph Styles panel opens New Character Style or New Paragraph Style (`ui.newCharStyle`, `ui.newParaStyle`) with the name a plain click's style gets; OK makes the style from the text selected when the dialog opened, and Cancel adds none. Tests `panels::text_styles::tests::alt_clicking_new_character_style_asks_for_its_name` and `alt_clicking_new_paragraph_style_asks_for_its_name`. Public reference: [Default keyboard shortcuts](https://web.archive.org/web/20260726060015/https://helpx.adobe.com/illustrator/using/default-keyboard-shortcuts.html), which lists Alt-click for opening panel options and names Actions, Brushes, Swatches and Symbols as exceptions. - **Moving all tab stops:** in the Tabs panel, a stop dragged on the ruler with Ctrl held (Command on macOS) moves every stop by the same distance, in one `text.tabs.set` and one undo step; the stops keep their order, alignment and leaders, the ruler shows them moving during the drag, and a drag that would take the leftmost stop below 0 leaves it at 0, or the rightmost past 100,000 pt leaves it at 100,000 pt, with the other stops at their spacing from it. A drag that leaves every stop where it was records no undo step. Ctrl must be held when the drag starts. Tests `panels::tabs::tests::command_drag_moves_all_the_stops_together`, `command_drag_stops_at_zero_and_keeps_the_spacing`, `command_drag_stops_at_the_largest_position_and_keeps_the_spacing` and `a_drag_that_moves_no_stop_records_no_undo_step`. Public reference: [Manage tab stops](https://helpx.adobe.com/illustrator/desktop/measure-and-align/grids-and-guides/manage-tab-stops.html), which says that a Ctrl-drag (Windows) or Command-drag (macOS) of a tab moves all the tab stops at the same time. +- **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` for each paragraph of the story, from its last paragraph to its first, whatever order the frames were selected in with the Selection tool; a paragraph that runs on from one frame into the next gets one step, after Type tool Select All too. With the Selection tool only the paragraphs with text in a selected frame change, so a frame selected alone that starts or ends inside a paragraph sets that paragraph. Tests `panels::tabs::tests::indent_markers_on_selected_threaded_frames_follow_the_story_and_set_a_split_paragraph_once`, `indent_markers_after_select_all_list_a_split_paragraph_once` and `indent_markers_on_some_threaded_frames_list_their_paragraphs_once`. 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). Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a feature lands. From b89a6e8ba153d01a4b8a9f98d43033a3d06528eb Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 15:49:16 -0800 Subject: [PATCH 21/38] Type: Block's word gap leaves the paragraphs' word spacing as set The word gap is now the Desired word spacing the layout uses for area type with Block on (TextObject::layout_justification), with Minimum and Maximum moved out to it when it lies outside them. The paragraphs keep their own Justification values, so a wide gap no longer leaves a 1,000 % Maximum behind, and turning Block off brings back the paragraph's own Desired value. The SVG writer reads the same values. - The Contextual Task Bar offers Dynamic Text for area type outside a thread, beside Convert To Point Type. - type.dynamicText with wordGap or lineGap and no area type in the selection is an error instead of being ignored. - Docs: docs/mcp.md, params text, docs/target-app-parity.md. --- crates/doc/src/text/area.rs | 5 ++- crates/doc/src/text/object.rs | 15 ++++++- crates/engine/src/cmd/typecmd/block.rs | 33 +++++++-------- crates/engine/src/cmd/typecmd/block_tests.rs | 42 +++++++++++++++++++- crates/engine/src/cmd/typemenu.rs | 5 ++- crates/svg/src/export/text.rs | 4 +- crates/text/src/layout/flow.rs | 5 ++- crates/ui-egui/src/canvas/task_bar.rs | 15 ++++--- crates/ui-egui/src/tests/taskbar.rs | 24 +++++++++++ docs/mcp.md | 9 +++-- docs/target-app-parity.md | 2 +- 11 files changed, 119 insertions(+), 40 deletions(-) diff --git a/crates/doc/src/text/area.rs b/crates/doc/src/text/area.rs index 1901a23c8a..848add8f53 100644 --- a/crates/doc/src/text/area.rs +++ b/crates/doc/src/text/area.rs @@ -167,8 +167,9 @@ pub struct AreaOptions { /// How the frame and its text fit each other (Auto Size, Shrink Text to Fit). #[serde(skip_serializing_if = "crate::skip::is_default")] pub fit: AreaFit, - /// Dynamic Text's Block ([`super::TextObject::dynamic_text`] on area type): every paragraph's - /// Desired word spacing, in percent of a word space (100, the default, is left out when saved). + /// Dynamic Text's Block ([`super::TextObject::dynamic_text`] on area type): the Desired word + /// spacing the layout sets every paragraph with ([`super::TextObject::layout_justification`]), in + /// percent of a word space (100, the default, is left out when saved). #[serde(skip_serializing_if = "AreaOptions::is_default_word_gap")] pub word_gap: f64, /// Dynamic Text's Block: the points added to each character's size to give its leading (0, the diff --git a/crates/doc/src/text/object.rs b/crates/doc/src/text/object.rs index 1092b871f2..d46b45b1f7 100644 --- a/crates/doc/src/text/object.rs +++ b/crates/doc/src/text/object.rs @@ -1,6 +1,6 @@ use super::area::{AreaOptions, PathAlign, PathEffect}; use super::char_style::CharStyle; -use super::para_style::ParaStyle; +use super::para_style::{JustificationOptions, ParaStyle}; use super::runs::{RubySpan, TextKind, TextRun, TypeAntiAlias, move_anchors, reverse_from_end}; use super::tabs_lists::{ListCounts, ParaList}; use super::{Affine, PathData, Point, Rect, TextObject, TextStyleScale, Vec2}; @@ -170,6 +170,19 @@ impl TextObject { pub fn para_at(&self, i: usize) -> &ParaStyle { self.paras.get(i).or(self.paras.last()).unwrap_or(&self.para) } + /// The Justification… options the layout sets `para` with: its own, except that with Dynamic + /// Text's Block on area type ([`Self::dynamic_text`]) the Desired word spacing is the word gap + /// ([`AreaOptions::block_gaps`]), and Minimum and Maximum move out to it when it lies outside + /// them. The paragraph keeps its own values, which apply again when Block is off. + pub fn layout_justification(&self, para: &ParaStyle) -> JustificationOptions { + let mut j = para.justification.clone(); + if self.dynamic_text && matches!(self.kind, TextKind::Area { .. }) { + let gap = self.area.block_gaps().0; + let [min, _, max] = j.word_spacing; + j.word_spacing = [min.min(gap), gap, max.max(gap)]; + } + j + } /// Every paragraph's attributes, one per paragraph. pub fn paragraph_styles(&self) -> Vec { (0..self.paragraph_count()).map(|i| self.para_at(i).clone()).collect() diff --git a/crates/engine/src/cmd/typecmd/block.rs b/crates/engine/src/cmd/typecmd/block.rs index a78f5254cb..06453f4983 100644 --- a/crates/engine/src/cmd/typecmd/block.rs +++ b/crates/engine/src/cmd/typecmd/block.rs @@ -8,7 +8,8 @@ use vectorcraft_doc::{TextKind, TextObject, TextRun}; /// Character panel's). const SIZES: (f64, f64) = (0.1, 1296.0); -/// Most area layouts a refit runs to correct lines that still wrap after the first fit. +/// Most passes a refit runs to correct lines that still wrap after the first fit; each pass measures +/// the lines and runs at most one more area layout. pub(crate) const BLOCK_PASSES: usize = 4; /// One line as typed: `start..content` is its text, `content..end` the `\n` or U+2028 that ends it @@ -73,9 +74,12 @@ fn first_sizes(runs: &[TextRun], lines: &[TypedLine]) -> Vec { } /// Each line's content width (trailing spaces left out) by its first byte, with `t` laid out as -/// point type, where no line wraps. +/// point type, where no line wraps, with the word spacing `t`'s layout uses. fn line_widths(db: &vectorcraft_text::FontDb, t: &TextObject) -> std::collections::HashMap { let mut probe = t.clone(); + for p in probe.para_styles_mut() { + p.justification = t.layout_justification(p); + } probe.kind = TextKind::Point; let laid = vectorcraft_text::layout(db, &probe); let mut out = std::collections::HashMap::with_capacity(laid.lines.len()); @@ -103,33 +107,24 @@ fn tenths(points: f64) -> f64 { ((points * 10.0 + 1e-6).floor() / 10.0).clamp(SIZES.0, SIZES.1) } -/// Fit area type with Dynamic Text (Block) on: every paragraph's Desired word spacing becomes the word gap, -/// then each line as typed gets the size (its first character's, in steps of 0.1 pt within 0.1 to +/// Fit area type with Dynamic Text (Block) on: with the word gap as every paragraph's Desired word +/// spacing ([`TextObject::layout_justification`]; the paragraphs keep their own values), each line +/// as typed gets the size (its first character's, in steps of 0.1 pt within 0.1 to /// 1,296 pt, the line's other characters keeping their proportions to it) at which its width /// equals the frame's width less the inset, the gutters and the paragraph's indents, and each /// character's leading is its size plus the line gap. An empty line or one of only spaces keeps /// its size. Nothing changes when the frame has no width along the lines or the type's transform /// has no size. A line that still wraps at its first fit is made smaller, in at most -/// [`BLOCK_PASSES`] more layouts. True when the text changed. +/// [`BLOCK_PASSES`] more passes. True when the text changed. pub(crate) fn block_fit(t: &mut TextObject) -> bool { if !t.dynamic_text { return false; } let TextKind::Area { frame } = &t.kind else { return false }; - let (word_gap, line_gap) = t.area.block_gaps(); + let (_, line_gap) = t.area.block_gaps(); let Some(b) = frame.bounds().filter(|b| [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite())) else { return false }; let Some(points) = t.style_scale().map(|s| s.points).filter(|p| p.is_finite() && *p > 1e-12) else { return false }; - let before = (t.runs.clone(), t.para.clone(), t.paras.clone()); - - // The word gap first: it changes the lines' widths. - let mut paras = t.paragraph_styles(); - for p in &mut paras { - let [min, _, max] = p.justification.word_spacing; - p.justification.word_spacing = [min.min(word_gap), word_gap, max.max(word_gap)]; - } - if paras != t.paragraph_styles() { - t.set_paragraph_styles(paras); - } + let before = t.runs.clone(); // The room along a line in one cell of the frame, before indents. let a = &t.area; @@ -137,7 +132,7 @@ pub(crate) fn block_fit(t: &mut TextObject) -> bool { let cells = cells.max(1) as f64; let cell = (along - 2.0 * a.inset.max(0.0) - gutter.max(0.0) * (cells - 1.0)) / cells; if !(cell.is_finite() && cell > 1e-9) { - return (t.runs.clone(), t.para.clone(), t.paras.clone()) != before; + return t.runs != before; } let db = vectorcraft_text::FontDb::global(); @@ -273,7 +268,7 @@ pub(crate) fn block_fit(t: &mut TextObject) -> bool { } apply(t, &start, &fits); } - (t.runs.clone(), t.para.clone(), t.paras.clone()) != before + t.runs != before } #[cfg(test)] diff --git a/crates/engine/src/cmd/typecmd/block_tests.rs b/crates/engine/src/cmd/typecmd/block_tests.rs index 1028fc0017..2dda356146 100644 --- a/crates/engine/src/cmd/typecmd/block_tests.rs +++ b/crates/engine/src/cmd/typecmd/block_tests.rs @@ -166,6 +166,17 @@ fn bad_params_and_other_type_are_refused() { let r = s.execute("type.dynamicText", &json!({})).unwrap(); assert_eq!(r["ids"], json!([id])); assert!(text(&s, id).dynamic_text && !text(&s, point).dynamic_text); + // A gap with only type on a path selected is an error, and nothing changes. + let path = s.execute("path.create", &json!({"d": "M60 550 L340 550"})).unwrap()["id"].as_u64().unwrap(); + let along = s.execute("text.createInPath", &json!({"path": path, "mode": "onPath", "text": "Along"})).unwrap()["id"].as_u64().unwrap(); + s.execute("select.set", &json!({"ids": [along]})).unwrap(); + let n = undo_len(&s); + for gap in [json!({"wordGap": 300}), json!({"on": false, "lineGap": 2})] { + let e = s.execute("type.dynamicText", &gap).unwrap_err().to_string(); + assert!(e.contains("need area type"), "{e}"); + } + assert_eq!(undo_len(&s), n); + assert!(!text(&s, along).dynamic_text); } #[test] @@ -179,10 +190,39 @@ fn gaps_set_word_spacing_and_leading() { let t = text(&s, id); assert!(t.dynamic_text); assert_eq!((t.area.word_gap, t.area.line_gap), (300.0, 6.0)); - assert_eq!(t.para_at(0).justification.word_spacing, [80.0, 300.0, 300.0]); + // The layout uses the gap as the Desired word spacing; the paragraph keeps its own. + assert_eq!(t.para_at(0).justification.word_spacing, [80.0, 100.0, 133.0]); + assert_eq!(t.layout_justification(t.para_at(0)).word_spacing, [80.0, 300.0, 300.0]); assert!(t.runs.iter().all(|r| (r.style.leading.unwrap() - r.style.size - 6.0).abs() < 1e-9), "{:?}", t.runs); assert_block(&t); assert!(size_at(&t, 0) < size_at(&plain, 0), "wider word spaces leave the letters less room"); + // (own, used by the layout) word spacing of the first paragraph. + let spacing = |s: &Session| { + let t = text(s, id); + (t.para_at(0).justification.word_spacing, t.layout_justification(t.para_at(0)).word_spacing) + }; + // Minimum and Maximum move out only as far as the current gap needs, and the paragraph's own + // values apply again when Block is off. + s.execute("type.dynamicText", &json!({"wordGap": 1000})).unwrap(); + assert_eq!(spacing(&s), ([80.0, 100.0, 133.0], [80.0, 1000.0, 1000.0])); + s.execute("type.dynamicText", &json!({"wordGap": 100})).unwrap(); + assert_eq!(spacing(&s), ([80.0, 100.0, 133.0], [80.0, 100.0, 133.0])); + s.execute("type.dynamicText", &json!({"wordGap": 0})).unwrap(); + assert_eq!(spacing(&s), ([80.0, 100.0, 133.0], [0.0, 0.0, 133.0])); + s.execute("type.dynamicText", &json!({"on": false})).unwrap(); + assert_eq!(spacing(&s), ([80.0, 100.0, 133.0], [80.0, 100.0, 133.0])); + // A paragraph's own values, outside the default range and equal to Desired too, stay through + // gap changes and refits after edits. + s.execute("text.setFormat", &json!({"wordSpacing": [20, 20, 150]})).unwrap(); + s.execute("type.dynamicText", &json!({"on": true, "wordGap": 20})).unwrap(); + assert_eq!(spacing(&s), ([20.0, 20.0, 150.0], [20.0, 20.0, 150.0])); + s.execute("type.dynamicText", &json!({"wordGap": 1000})).unwrap(); + assert_eq!(spacing(&s), ([20.0, 20.0, 150.0], [20.0, 1000.0, 1000.0])); + s.execute("type.dynamicText", &json!({"wordGap": 100})).unwrap(); + s.execute("text.editRange", &json!({"id": id, "start": 0, "end": 0, "insert": "a "})).unwrap(); + assert_eq!(spacing(&s), ([20.0, 20.0, 150.0], [20.0, 100.0, 150.0])); + s.execute("type.dynamicText", &json!({"on": false})).unwrap(); + assert_eq!(spacing(&s), ([20.0, 20.0, 150.0], [20.0, 20.0, 150.0])); // A gap alone on a frame without Block turns it on. let other = area(&mut s, 200.0, 200.0, "x y"); let r = s.execute("type.dynamicText", &json!({"lineGap": -2})).unwrap(); diff --git a/crates/engine/src/cmd/typemenu.rs b/crates/engine/src/cmd/typemenu.rs index c3db479332..03681c556a 100644 --- a/crates/engine/src/cmd/typemenu.rs +++ b/crates/engine/src/cmd/typemenu.rs @@ -65,7 +65,7 @@ pub fn specs() -> Vec { "Dynamic Text", ["Type"], None, - "{ids?|id?, on?: bool, wordGap?: % of a word space 0..1000 (100), lineGap?: pt -1296..1296 (0)} turn Dynamic Text on or off for the selected type on a path and area type (on omitted: the opposite of the first object's setting, or on when a gap is given). On type on a path, the layout scales the text by one factor (every character's size, leading and baseline shift; Type on a Path Options › Spacing stays) so that it fills the span between its start and end brackets, larger or smaller, and fits it again after every edit to the text, the path or the brackets; the first character's size moves in steps of 0.1 pt within 0.1 to 1,296 pt, and at 0.1 pt text that still runs past the end bracket overflows. The stored sizes keep their proportions. On area type it is Block: each line as typed (each paragraph, and each forced line break in one; lines are not broken again) is set to the frame's width, less the inset, the gutters and the paragraph's indents, by changing its font size only: its first character's size, in steps of 0.1 pt within 0.1 to 1,296 pt, the line's other characters keeping their proportions to it, with baseline shifts following. Every character's leading is its size plus lineGap, and every paragraph's Desired word spacing is wordGap (the gaps are area type's, and are kept while Block is off). The sizes are written into the characters and fitted again after every edit to the text or the frame, in the same undo step; at a size limit a line can be narrower than the frame or wrap. An empty line keeps its size. Block replaces Auto Size and Shrink Text to Fit (Area Type Options › Block is the same setting). Off, the text keeps the sizes it was drawn at. Point type in the selection is left as it is; a selection holding type in a thread is refused (threading type turns Dynamic Text off, keeping its drawn sizes). When nothing changes, no undo step is recorded → {on, ids, fitScale (the first object's factor; 1 when off and for area type), wordGap?, lineGap? (the first area type's; left out without area type)}", + "{ids?|id?, on?: bool, wordGap?: % of a word space 0..1000 (100), lineGap?: pt -1296..1296 (0)} turn Dynamic Text on or off for the selected type on a path and area type (on omitted: the opposite of the first object's setting, or on when a gap is given). On type on a path, the layout scales the text by one factor (every character's size, leading and baseline shift; Type on a Path Options › Spacing stays) so that it fills the span between its start and end brackets, larger or smaller, and fits it again after every edit to the text, the path or the brackets; the first character's size moves in steps of 0.1 pt within 0.1 to 1,296 pt, and at 0.1 pt text that still runs past the end bracket overflows. The stored sizes keep their proportions. On area type it is Block: each line as typed (each paragraph, and each forced line break in one; lines are not broken again) is set to the frame's width, less the inset, the gutters and the paragraph's indents, by changing its font size only: its first character's size, in steps of 0.1 pt within 0.1 to 1,296 pt, the line's other characters keeping their proportions to it, with baseline shifts following. Every character's leading is its size plus lineGap, and the layout sets every paragraph with wordGap as its Desired word spacing, its Minimum or Maximum moving out to wordGap when wordGap lies outside it (the paragraphs keep their own Justification… values, which apply again when Block is off; the gaps are area type's, and are kept while Block is off; a gap with no area type in the selection is an error). The sizes are written into the characters and fitted again after every edit to the text or the frame, in the same undo step; at a size limit a line can be narrower than the frame or wrap. An empty line keeps its size. Block replaces Auto Size and Shrink Text to Fit (Area Type Options › Block is the same setting). Off, the text keeps the sizes it was drawn at. Point type in the selection is left as it is; a selection holding type in a thread is refused (threading type turns Dynamic Text off, keeping its drawn sizes). When nothing changes, no undo step is recorded → {on, ids, fitScale (the first object's factor; 1 when off and for area type), wordGap?, lineGap? (the first area type's; left out without area type)}", has_dynamic_type, dynamic_text ), @@ -576,6 +576,9 @@ fn dynamic_text(s: &mut Session, p: &Value) -> Result { return Err(bad(C, why)); } let gap_given = word_gap.is_some() || line_gap.is_some(); + if gap_given && !ids.iter().any(|id| area_text(d.node(*id)).is_some()) { + return Err(bad(C, "wordGap and lineGap need area type in the selection")); + } let on = switch_or(p, "on", gap_given || !dynamic_type(d.node(first)).is_some_and(|t| t.dynamic_text), C)?; // Each object as the command leaves it, and only those it changes. let mut planned: Vec<(NodeId, TextObject)> = vec![]; diff --git a/crates/svg/src/export/text.rs b/crates/svg/src/export/text.rs index b12811338b..645ba3d751 100644 --- a/crates/svg/src/export/text.rs +++ b/crates/svg/src/export/text.rs @@ -693,8 +693,8 @@ fn text_lines(t: &TextObject, lay: &vectorcraft_text::TextLayout, fewer: bool) - let split_words = !fewer && !matches!(style.justify, Justify::Auto | Justify::Left | Justify::Center | Justify::Right); // Each cluster's advance and drawing offset as a reader gives them, by its byte offset. // Justification…'s Desired word and letter spacing and glyph scaling move characters from - // where a reader draws them, on every line. - let spaced = !fewer && !style.justification.desired_is_default(); + // where a reader draws them, on every line (Block's word gap among them). + let spaced = !fewer && !t.layout_justification(style).desired_is_default(); let reader = if split_words || spaced || (!fewer && !style.mojikumi.is_none()) { Some(&*kerned.get_or_insert_with(|| reader_advances(t, lay, true))) } else { diff --git a/crates/text/src/layout/flow.rs b/crates/text/src/layout/flow.rs index 56c71c2f4b..e3bddbac93 100644 --- a/crates/text/src/layout/flow.rs +++ b/crates/text/src/layout/flow.rs @@ -217,8 +217,9 @@ fn prepare_paragraph<'a, 'text>( // …and a quarter em between Japanese and Latin text. let mut wakan = if para.mojikumi == Mojikumi::LineEndHalf { space_japanese_and_latin(&mut sg) } else { vec![] }; // Justification…: the glyphs at Desired word and letter spacing and glyph scaling, and how - // far a justified line may move each one from it. - let mut flex = apply_desired(&mut sg, ¶.justification, !cx.vertical); + // far a justified line may move each one from it (Dynamic Text's Block on area type sets the + // Desired word spacing to its word gap). + let mut flex = apply_desired(&mut sg, &t.layout_justification(para), !cx.vertical); // Threaded text: a first paragraph that continues from the frame before has its first // line, first-line indent and list marker there. let continued = pi == 0 && t.first_para_continues; diff --git a/crates/ui-egui/src/canvas/task_bar.rs b/crates/ui-egui/src/canvas/task_bar.rs index eb038f0790..a7a7f0a45c 100644 --- a/crates/ui-egui/src/canvas/task_bar.rs +++ b/crates/ui-egui/src/canvas/task_bar.rs @@ -151,14 +151,13 @@ pub(super) fn task_bar(app: &mut VectorcraftApp, ui: &mut Ui, xf: &Xf) { match kind { TextKind::Area { .. } => items.push((tl!("Convert To Point Type"), "type", "type.convertToPointType", none())), TextKind::Point => items.push((tl!("Convert To Area Type"), "dc-type-area", "type.convertToAreaType", none())), - TextKind::OnPath { .. } => { - items.push((tl!("Type on a Path Options"), "dc-type-path", "type.pathOptions", none())); - // Dynamic Text turns on or off, as the Type menu's item does; left out for type in a thread - // (). - if crate::menus::enabled(app, "type.dynamicText") { - items.push((tl!("Dynamic Text"), "maximize-2", "type.dynamicText", none())); - } - } + TextKind::OnPath { .. } => items.push((tl!("Type on a Path Options"), "dc-type-path", "type.pathOptions", none())), + } + // Dynamic Text turns on or off for type on a path and area type (Block), as the Type menu's item does; + // left out for point type and type in a thread + // (). + if crate::menus::enabled(app, "type.dynamicText") { + items.push((tl!("Dynamic Text"), "maximize-2", "type.dynamicText", none())); } } else if is_image { // Offset Path and Simplify don't apply to an image. diff --git a/crates/ui-egui/src/tests/taskbar.rs b/crates/ui-egui/src/tests/taskbar.rs index 53042baa69..d42be49ff9 100644 --- a/crates/ui-egui/src/tests/taskbar.rs +++ b/crates/ui-egui/src/tests/taskbar.rs @@ -208,6 +208,30 @@ fn type_on_a_path_offers_dynamic_text() { assert!(!has(&texts, "Dynamic Text"), "{texts:?}"); } +/// Area type offers Dynamic Text beside Convert To Point Type, which turns Block on and off; area +/// type in a thread does not. +#[test] +fn area_type_offers_dynamic_text() { + let mut app = app(); + let t = id(app.run("text.create", json!({"x": 60, "y": 80, "area": {"width": 200, "height": 100}, "text": "Fit me"})).unwrap()); + app.run("tool.select", json!({"tool": "selection"})).unwrap(); + select(&mut app, &[t]); + let dynamic = |app: &VectorcraftApp| matches!(kind(app, t), NodeKind::Text(ref t) if t.dynamic_text); + let (_, texts) = bar(&mut app); + assert!(has(&texts, "Convert To Point Type") && has(&texts, "Dynamic Text"), "{texts:?}"); + click(&mut app, "Dynamic Text"); + assert!(dynamic(&app)); + click(&mut app, "Dynamic Text"); + assert!(!dynamic(&app)); + // Threaded, it is not offered. + let frame = id(app.run("shape.rectangle", json!({"x": 60, "y": 300, "width": 200, "height": 100})).unwrap()); + select(&mut app, &[t, frame]); + app.run("text.thread.create", json!({})).unwrap(); + select(&mut app, &[t]); + let (_, texts) = bar(&mut app); + assert!(has(&texts, "Convert To Point Type") && !has(&texts, "Dynamic Text"), "{texts:?}"); +} + /// The path's anchors (its first subpath). fn anchors(app: &VectorcraftApp, id: u64) -> Vec { match kind(app, id) { diff --git a/docs/mcp.md b/docs/mcp.md index 44da10f748..c2bd7bbb64 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -6514,7 +6514,8 @@ chosen artboards draw all of them. A PDF leaves out the layers that don't print ### Dynamic Text: Block -`type.dynamicText {ids?|id?, on?: bool, wordGap?, lineGap?}` (Type › Dynamic Text) turns Block on or off for the +`type.dynamicText {ids?|id?, on?: bool, wordGap?, lineGap?}` (Type › Dynamic Text, and the Contextual Task Bar for +area type outside a thread) turns Block on or off for the selected area type, as it turns Dynamic Text on or off for type on a path ([Dynamic Text](#dynamic-text)). Area Type Options › Block is the same setting, and the Properties panel's Paragraph section has a Dynamic Text checkbox, which shows Word Gap and Line Gap while it is on. The [Dynamic Text overview](https://helpx.adobe.com/photoshop/desktop/text-typography/work-with-dynamic-text/dynamic-text-overview.html) @@ -6526,8 +6527,10 @@ lines. The rest are VectorCraft's own rules: left, right and first-line indents, by its font size only (tracking and scaling stay): the first character's size in steps of 0.1 pt within 0.1 to 1,296 pt, the line's other characters keeping their proportions to it and their baseline shifts following. Vertical type sets each line to the frame's height (less the gutters between rows). -- `wordGap` is every paragraph's Desired word spacing (Justification…), and each character's leading is its size - plus `lineGap`. +- The layout sets every paragraph with `wordGap` as its Desired word spacing (Justification…), and its Minimum or + Maximum word spacing moves out to `wordGap` when `wordGap` lies outside it. The paragraphs keep their own + Justification… values, which apply again when Block is off. Each character's leading is its size plus `lineGap`. A + gap given with no area type in the selection is an error. - The sizes are written into the characters, so every export and the Character panel see them. After every edit to the text or the frame (typing, `text.editRange`, character and paragraph changes, `text.areaOptions {width}`, a frame resize) the lines are fitted again, in the edit's own undo step. The lines are then measured again, in at diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index cd3f49ef69..bab61d841a 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1159,7 +1159,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur With Optical Margin Alignment on, or Roman Hanging Punctuation on in the first paragraph, the glyphs at the ends of left-to-right type on a path hang outside its brackets, measured along the path. The type hangs at the start bracket when its line is placed there, hangs at the end bracket when the line is placed there, and hangs at both when it is centered. Glyphs that hang past the end bracket do not make the type overflow, and a hang stops at an open path's end. SVG export writes such type as outlines. Type on a Path Options › Align to Path (option names as in [Create type on a path](https://helpx.adobe.com/illustrator/desktop/design-with-text/edit-format-text/create-type-on-a-path.html)) moves each character by its own font, size and vertical scale: Ascender runs the top of the font's em box along the path (the ideographic em box that its `BASE` table, its typographic or `hhea` box or its ideographs give, else an em box centered on the cap height), Descender runs the bottom of the font's bounding box along it, and Center runs a line at half the height of the top of the font's H above the baseline along it. In vertical type, Ascender and Descender move the characters half an em, and Center leaves them on the path. These distances are VectorCraft's own values (`tests::on_path_align_runs_each_glyph_by_its_own_metrics`, `tests::on_path_align_finds_the_em_box_of_each_kind_of_face`, `tests::on_path_align_in_vertical_type_moves_half_an_em`). Type › Dynamic Text (`type.dynamicText`, also on the Contextual Task Bar for type on a path) sizes type on a path to fill the span between its start and end brackets and fits it again after each edit to the text, the path or a bracket ([Dynamic Text overview](https://helpx.adobe.com/photoshop/desktop/text-typography/work-with-dynamic-text/dynamic-text-overview.html), [start and end points](https://helpx.adobe.com/photoshop/desktop/text-typography/work-with-dynamic-text/reposition-start-and-end-points.html)). VectorCraft's own rules: one factor scales every size, leading and baseline shift; the first character's size moves in 0.1 pt steps within 0.1 to 1,296 pt; turning it off or threading the type keeps the drawn sizes; SVG, EPS and the editing data write the drawn sizes (`crates/text/src/tests/fit.rs`, `crates/engine/src/tests/dynamic_text.rs`). - Dynamic Text on area type is Block (Type › Dynamic Text, Area Type Options › Block, the Properties panel's Dynamic Text checkbox with Word Gap and Line Gap; [Dynamic Text overview](https://helpx.adobe.com/photoshop/desktop/text-typography/work-with-dynamic-text/dynamic-text-overview.html)): each line as typed is set to the frame's width by its font size, again after every edit to the text or the frame. VectorCraft's own rules: lines are not broken again, the first character's size moves in 0.1 pt steps within 0.1 to 1,296 pt, Word Gap (0 to 1,000 %, default 100) is the Desired word spacing and Line Gap (-1,296 to 1,296 pt, default 0) is added to each size for the leading, the sizes are written into the characters, and threaded frames cannot use it (`crates/engine/src/cmd/typecmd/block_tests.rs`). + Dynamic Text on area type is Block (Type › Dynamic Text, the Contextual Task Bar, Area Type Options › Block, the Properties panel's Dynamic Text checkbox with Word Gap and Line Gap; [Dynamic Text overview](https://helpx.adobe.com/photoshop/desktop/text-typography/work-with-dynamic-text/dynamic-text-overview.html)): each line as typed is set to the frame's width by its font size, again after every edit to the text or the frame. VectorCraft's own rules: lines are not broken again, the first character's size moves in 0.1 pt steps within 0.1 to 1,296 pt, Word Gap (0 to 1,000 %, default 100) is the Desired word spacing and Line Gap (-1,296 to 1,296 pt, default 0) is added to each size for the leading, the sizes are written into the characters, and threaded frames cannot use it (`crates/engine/src/cmd/typecmd/block_tests.rs`). The frames of threaded text share one Optical Margin Alignment setting: turning it on or off in one frame sets it in every frame, threading frames gives the thread its first frame's setting, and frames taken out of a thread keep it. The frames of threaded text share one writing direction: Type › Type Orientation (`type.orientation.vertical`, `type.orientation.horizontal`) in one frame sets every frame, threading frames gives the thread its first frame's direction, frames taken out of a thread keep theirs, and the story flows through every frame in the thread's direction. Type › Optical Margin Alignment (`type.opticalMarginAlignment`) hangs the punctuation and letter edges at the ends of a type object's lines outside its margins: at the left of left-aligned lines, at the right of right-aligned lines, and at both ends of centered and justified lines, in point and area type of left-to-right paragraphs. Quotation marks, hyphens, full stops and commas hang wholly; asterisks, tildes, ellipses, en and em dashes, colons and semicolons hang by half; and A, V, W, Y, v, w and y hang by a tenth of their width. It is off by default and saved with the type object. Justification's Glyph Scaling leaves the glyphs that hang at their width, so they hang exactly their share, and Standard burasagari counts what hangs at a line's start as room before hanging a comma; `crates/text/src/tests/hang.rs` checks whole paragraphs with both composers, ragged, centred and justified, with Line-end Punctuation Half Width and bidirectional lines. From ef7fbaac31e14b59a1597324488f37fdb3175fcf Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 11 Nov 2026 15:51:11 -0800 Subject: [PATCH 22/38] Plug-ins: a failed rename back of a removed plug-in's settings is reported and undone later When plugin.remove could not remove the grant and then could not rename the plug-in's settings folder back from .removed, the failure was only logged: the plug-in got empty settings, and the next removal deleted the .removed folder with the settings in it. - The error now names the .removed folder, the plug-in folder and the reason, and the plug-in gets no storage until the settings are back. - The next load, install or plugin.remove of the plug-in renames a kept folder back while the plug-in has no folder of its own. When it has one, that folder is used and the kept one stays until plugin.remove deletes both. A removal while a kept .removed folder exists renames the plug-in folder to .removing. - Before deleting a renamed folder, the store writes an empty .removed.delete file and removes it once the folder is gone, so what a failed deletion leaves is not moved back. When that file can't be written, nothing is deleted. - A .removed folder without a .delete file, including one an earlier version left, counts as kept settings: a new install of the id needs replace: true, and plugin.remove of the id deletes it. --- crates/engine/src/cmd/plugin.rs | 2 +- crates/engine/src/store.rs | 178 +++++++++++++++++++++++++---- crates/engine/src/tests/plugins.rs | 119 +++++++++++++++++++ docs/mcp.md | 8 +- docs/plugins.md | 17 ++- docs/target-app-parity.md | 1 + 6 files changed, 291 insertions(+), 34 deletions(-) diff --git a/crates/engine/src/cmd/plugin.rs b/crates/engine/src/cmd/plugin.rs index a5b71d538b..e8e57301e8 100644 --- a/crates/engine/src/cmd/plugin.rs +++ b/crates/engine/src/cmd/plugin.rs @@ -1096,7 +1096,7 @@ pub fn specs() -> Vec { "Remove Plug-in", [], None, - "{id} uninstall a plug-in (its live effects then leave the geometry as it is) and delete the settings and cache it kept (when their folder can't be moved aside, or its grant can't be removed from the plug-in store, the command fails and the plug-in stays installed); for an id that isn't installed, deletes the settings and cache the plug-in store still keeps for it → {removed}", + "{id} uninstall a plug-in (its live effects then leave the geometry as it is) and delete the settings and cache it kept (when their folder can't be moved aside, or its grant can't be removed from the plug-in store, the command fails and the plug-in stays installed; when the settings can't be moved back either, the error names the folder they stay in, and the next load, install or removal of the plug-in moves them back); for an id that isn't installed, deletes the settings and cache the plug-in store still keeps for it → {removed}", always, remove ), diff --git a/crates/engine/src/store.rs b/crates/engine/src/store.rs index 01ebc46526..9a96f96212 100644 --- a/crates/engine/src/store.rs +++ b/crates/engine/src/store.rs @@ -190,6 +190,12 @@ fn lock_disabled(_: &Path) -> Option { thread_local! { /// Tests: [`Session::put_back_plugin`] fails on this thread, as on a full volume. pub(crate) static PUT_BACK_FAILS: std::cell::Cell = const { std::cell::Cell::new(false) }; + /// Tests: moving a plug-in's settings and cache back from `.removed` ([`move_back`]) + /// fails on this thread, as when another program holds a file in the folder. + pub(crate) static MOVE_BACK_FAILS: std::cell::Cell = const { std::cell::Cell::new(false) }; + /// Tests: writing the `.delete` file beside a folder about to be deleted ([`delete_aside`]) + /// fails on this thread, as on a full volume. + pub(crate) static MARKER_WRITE_FAILS: std::cell::Cell = const { std::cell::Cell::new(false) }; } /// Remove `dir/file` → whether it is gone; a file that isn't there is what was wanted. @@ -590,26 +596,34 @@ impl Session { } /// Keep the settings and cache of plug-in `id` in the attached plug-in store from now on; without - /// one, nowhere (its storage calls then fail as unavailable). + /// one, nowhere (its storage calls then fail as unavailable). Settings and cache that a removal + /// kept are moved back first ([`plugin_storage`]). pub(crate) fn attach_plugin_storage(&self, id: &str) { vectorcraft_plugins::registry::set_storage(id, plugin_storage(self.plugin_dir.as_deref(), id)); } - /// Does the attached plug-in store have a folder of settings and cache for plug-in `id`? A - /// folder behind a `storage` folder that is a link is not counted: the plug-in's storage calls - /// can't reach it and removing the plug-in leaves it. + /// Does the attached plug-in store have a folder of settings and cache for plug-in `id`, or one + /// that a removal kept ([`aside_paths`], [`is_kept`])? A folder behind a `storage` folder + /// that is a link is not counted: the plug-in's storage calls can't reach it and removing the + /// plug-in leaves it. pub(crate) fn has_plugin_storage(&self, id: &str) -> bool { - self.plugin_dir - .as_deref() - .is_some_and(|dir| !is_link(&dir.join(PLUGIN_DATA_DIR)) && std::fs::symlink_metadata(plugin_data_dir(dir, id)).is_ok()) + self.plugin_dir.as_deref().is_some_and(|dir| { + let path = plugin_data_dir(dir, id); + !is_link(&dir.join(PLUGIN_DATA_DIR)) && (std::fs::symlink_metadata(&path).is_ok() || aside_paths(&path).iter().any(|a| is_kept(a))) + }) } /// Delete the settings and cache of plug-in `id` from the store, and stop keeping any for it. - /// The folder is first renamed out of the way (`.removed`), and that fails, leaving it - /// as it was, when the rename does; what the deletion then leaves stays under that name, with a - /// log record. A later call for the id tries to delete it again. `forget` runs once the folder is - /// out of the way, before anything is deleted: when it returns `false`, the folder is renamed - /// back and this fails. + /// Settings and cache that an earlier removal kept ([`is_kept`]) are first moved back when the + /// folder is missing ([`restore_removed`]); what earlier deletions left is deleted. The folder is + /// then renamed out of the way ([`aside_paths`]: `.removed`, or `.removing` while + /// `.removed` holds kept settings), and that fails, leaving it as it was, when the rename + /// does. `forget` runs once the folder is out of the way, before anything is deleted: when it + /// returns `false`, the folder is renamed back and this fails, and the kept settings stay. When + /// that rename fails too, the error also names both paths and the reason, and the next attach or + /// removal for the id moves the folder back. Once `forget` returns `true`, the folder and the + /// kept settings are deleted ([`delete_aside`]); what that deletion leaves stays, with a log + /// record, and a later call for the id tries to delete it again. pub(crate) fn remove_plugin_storage(&self, id: &str, forget: impl FnOnce() -> bool) -> Result<(), StorageError> { let not_forgotten = || StorageError::Io(GRANT_NOT_REMOVED.to_string()); vectorcraft_plugins::registry::set_storage(id, None); @@ -636,28 +650,45 @@ impl Session { close(); return Ok(()); } - let mut aside = path.clone().into_os_string(); - aside.push(".removed"); - let aside = PathBuf::from(aside); - let _ = std::fs::remove_dir_all(&aside); - match std::fs::rename(&path, &aside) { + let asides = aside_paths(&path); + if std::fs::symlink_metadata(&path).is_err() + && let Err(e) = restore_removed(&path) + { + log::warn!("can't move the settings and cache of {} back: {e}", path.display()); + } + for aside in asides.iter().filter(|a| !is_kept(a)) { + delete_aside(aside); + } + let target = if std::fs::symlink_metadata(&path).is_err() { + asides.iter().rev().find(|a| is_kept(a)).unwrap_or(&asides[0]) + } else if !is_kept(&asides[0]) { + &asides[0] + } else if std::fs::symlink_metadata(&asides[1]).is_err() { + &asides[1] + } else { + return Err(StorageError::Io(format!("{}: {} and {} are in the way", path.display(), asides[0].display(), asides[1].display()))); + }; + match std::fs::rename(&path, target) { Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} Err(e) => return Err(StorageError::Io(format!("{}: {e}", path.display()))), Ok(()) => {} } if !forget() { - if std::fs::symlink_metadata(&aside).is_ok() - && let Err(e) = std::fs::rename(&aside, &path) + if std::fs::symlink_metadata(target).is_ok() + && let Err(e) = move_back(target, &path) { - log::warn!("can't move {} back: {e}", aside.display()); + log::warn!("can't move {} back: {e}", target.display()); + return Err(StorageError::Io(format!( + "{GRANT_NOT_REMOVED}, and its settings and cache can't be moved back from {} to {}: {e}", + target.display(), + path.display() + ))); } return Err(not_forgotten()); } close(); - if std::fs::symlink_metadata(&aside).is_ok() - && let Err(e) = std::fs::remove_dir_all(&aside) - { - log::warn!("can't delete {}: {e}", aside.display()); + for aside in &asides { + delete_aside(aside); } Ok(()) } @@ -688,10 +719,107 @@ pub(crate) fn plugin_data_dir(dir: &Path, id: &str) -> PathBuf { dir.join(PLUGIN_DATA_DIR).join(format!("id-{}", case_safe(id))) } -/// Where plug-in `id` keeps its settings and cache in the plug-in store `dir`. +/// `path` with `suffix` added to its last part. +fn suffixed(path: &Path, suffix: &str) -> PathBuf { + let mut named = path.as_os_str().to_os_string(); + named.push(suffix); + PathBuf::from(named) +} + +/// Where [`Session::remove_plugin_storage`] moves the plug-in folder `path` out of the way: +/// `.removed`, and `.removing` while `.removed` holds settings and cache an +/// earlier removal kept ([`is_kept`]). The second one, when it is there, is the newer. +fn aside_paths(path: &Path) -> [PathBuf; 2] { + [suffixed(path, ".removed"), suffixed(path, ".removing")] +} + +/// `