Merge remote-tracking branch 'origin/main' into feat/cutover-remaining-codecs

This commit is contained in:
FredApps
2026-11-16 07:08:15 +01:00
90 changed files with 3268 additions and 742 deletions
+4 -4
View File
@@ -182,28 +182,28 @@ pub fn effect_catalog() -> Vec<EffectInfo> {
REVOLVE,
"Revolve…",
&["Effect", "3D and Materials"],
"{angle: degrees (0..360, 360), offset: pt (0..100000, 0), edge: left|right, rotationX: degrees (0), rotationY: degrees (0), rotationZ: degrees (0), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), segments: integer (8..128, 64), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a hard-edged shadow, black at 50% times the art's opacity), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), cap: bool (true: solid, closing circular ends of open profiles and a partial sweep's cut sides; false: hollow), expandVisibleOnly: bool (true, trim covered opaque solid surfaces only on Expand Appearance; surfaces with graphics keep every face), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the swept side, see threeD.mapGraphic: symbol: name of a document symbol, face: front (the side), x: pt (0; the offset of the graphic's center from the middle of the side, around the axis: the angle times the profile's distance from the axis at that point), y: pt (0; along the profile, toward its lower end), scale: % (1..10000, 100), rotation: degrees (-360..360, 0; counterclockwise); wrapped around the side at its own size, so it reaches farther around where the profile comes nearer the axis, shaded with it and drawn only where the side's outside faces the viewer; a full turn cuts it at the back; nothing on the caps), render: object ({mode: shaded}; mode: shaded|wireframe, wireframe draws the edges of the faces the effect draws, each once, stroked 0.5 pt black with round joins, with no fill, shadow or graphics, whatever the opacity of the fills, strokes and group members, while the effect stays live; the stroke is VectorCraft's own)}. Shaded surfaces use smooth vector gradients automatically; intersecting profiles use approximate painter visibility.",
"{angle: degrees (0..360, 360), offset: pt (0..100000, 0), edge: left|right, rotationX: degrees (0), rotationY: degrees (0), rotationZ: degrees (0), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), segments: integer (8..128, 64), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), cap: bool (true: solid, closing circular ends of open profiles and a partial sweep's cut sides; false: hollow), expandVisibleOnly: bool (true, trim covered opaque solid surfaces only on Expand Appearance; surfaces with graphics keep every face), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the swept side, see threeD.mapGraphic: symbol: name of a document symbol, face: front (the side), x: pt (0; the offset of the graphic's center from the middle of the side, around the axis: the angle times the profile's distance from the axis at that point), y: pt (0; along the profile, toward its lower end), scale: % (1..10000, 100), rotation: degrees (-360..360, 0; counterclockwise); wrapped around the side at its own size, so it reaches farther around where the profile comes nearer the axis, shaded with it and drawn only where the side's outside faces the viewer; a full turn cuts it at the back; nothing on the caps), render: object ({mode: shaded}; mode: shaded|wireframe, wireframe draws the edges of the faces the effect draws, each once, stroked 0.5 pt black with round joins, with no fill, shadow or graphics, whatever the opacity of the fills, strokes and group members, while the effect stays live; the stroke is VectorCraft's own)}. Shaded surfaces use smooth vector gradients automatically; intersecting profiles use approximate painter visibility.",
json!({"angle":360.0,"offset":0.0,"edge":"left","rotationX":0.0,"rotationY":0.0,"rotationZ":0.0,"perspectiveAngle":0.0,"segments":64,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"cap":true,"expandVisibleOnly":true,"graphics":[],"render":{"mode":"shaded"}}),
),
g(
EXTRUDE,
"Extrude & Bevel…",
&["Effect", "3D and Materials"],
"{depth: pt (0..2000, 50), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none), bevelWidth: pt (0..1000, 4), bevelHeight: pt (0..1000, 4), bevelRepeat: integer (1..32, 1), bevelSpace: % (0..90, 0; flat between repeats), bevelInside: bool (false: added around the shape; true: carved into it), bevelBothSides: bool (false), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a hard-edged shadow, black at 50% times the art's opacity), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the caps, see threeD.mapGraphic: symbol: name of a document symbol, face: front|back (front; the back reads left to right as seen from behind), x: pt (0; the offset of the graphic's center from the center of the object's bounds, in the face's own plane), y: pt (0), scale: % (1..10000, 100; of the symbol's own size), rotation: degrees (-360..360, 0; counterclockwise); drawn turned, foreshortened and shaded with the cap and clipped to it, on a solid cap only), render: object ({mode: shaded}; mode: shaded|wireframe, as Revolve's)}. The front face is the art, extruded backwards about the centre of its bounds; painted with the top fill (else the top stroke).",
"{depth: pt (0..2000, 50), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: hollow), bevel: none|classic|rounded|cove|step|ogee (none), bevelWidth: pt (0..1000, 4), bevelHeight: pt (0..1000, 4), bevelRepeat: integer (1..32, 1), bevelSpace: % (0..90, 0; flat between repeats), bevelInside: bool (false: added around the shape; true: carved into it), bevelBothSides: bool (false), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the caps, see threeD.mapGraphic: symbol: name of a document symbol, face: front|back (front; the back reads left to right as seen from behind), x: pt (0; the offset of the graphic's center from the center of the object's bounds, in the face's own plane), y: pt (0), scale: % (1..10000, 100; of the symbol's own size), rotation: degrees (-360..360, 0; counterclockwise); drawn turned, foreshortened and shaded with the cap and clipped to it, on a solid cap only), render: object ({mode: shaded}; mode: shaded|wireframe, as Revolve's)}. The front face is the art, extruded backwards about the centre of its bounds; painted with the top fill (else the top stroke).",
json!({"depth":50.0,"twist":0.0,"taper":100.0,"cap":true,"bevel":"none","bevelWidth":4.0,"bevelHeight":4.0,"bevelRepeat":1,"bevelSpace":0.0,"bevelInside":false,"bevelBothSides":false,"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"graphics":[],"render":{"mode":"shaded"}}),
),
g(
INFLATE,
"Inflate…",
&["Effect", "3D and Materials"],
"{depth: pt (0..2000, 0; flat depth between front and back), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: no back, a shell open behind), volume: % (0..100, 50; 50 rounds the edge like a half sphere), bothSides: bool (false: flat back), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a hard-edged shadow, black at 50% times the art's opacity), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), render: object ({mode: shaded}; mode: shaded|wireframe, as Revolve's)}. Painted with the top fill (else the top stroke).",
"{depth: pt (0..2000, 0; flat depth between front and back), twist: degrees (0..360, 0; the back turned against the front), taper: % (1..100, 100; the back's size), cap: bool (true: solid; false: no back, a shell open behind), volume: % (0..100, 50; 50 rounds the edge like a half sphere), bothSides: bool (false: flat back), rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), render: object ({mode: shaded}; mode: shaded|wireframe, as Revolve's)}. Painted with the top fill (else the top stroke).",
json!({"depth":0.0,"twist":0.0,"taper":100.0,"cap":true,"volume":50.0,"bothSides":false,"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"render":{"mode":"shaded"}}),
),
g(
ROTATE,
"Rotate…",
&["Effect", "3D and Materials"],
"{rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a hard-edged shadow, black at 50% times the art's opacity), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the plane, as Extrude & Bevel's, with face front only), render: object ({mode: shaded}; mode: shaded|wireframe, as Revolve's)}. Turns the flat art in 3D about the centre of its bounds; every fill and stroke keeps its paint, shaded as one plane.",
"{rotationX: degrees (-180..180, -21.88), rotationY: degrees (-180..180, -23.4), rotationZ: degrees (-180..180, 9.06; the defaults are the Off-Axis Front position), perspectiveAngle: degrees (0..160, 0; 0 is none, wider brings the eye nearer), perspective: % (0..100; the earlier form, read as the perspectiveAngle that shows the same view), shade: bool (true), lightColor: #rrggbb (white, #ffffff; legacy directional light color), lights: null or array of 1..10 objects (color: #rrggbb, intensity: % 0..100, rotation: degrees -180..180, height: degrees 0..90, softness: % 0..100, behind: bool; overrides the single-light fields; ambient is shared), lightRotation: degrees (-180..180, 125.26; round the object on the page, 0 on its right, counterclockwise), lightHeight: degrees (0..90, 30; 0 beside the object, 90 straight in front), lightBehind: bool (false; true lights it from behind), lightIntensity: % (0..100, 80), lightSoftness: % (0..100, 0; how far round the object the light reaches, and how much it blurs the shadow), ambient: % (0..200, 25; Ambient Light), lightAzimuth: degrees (the earlier form: with lightElevation, read as the lightRotation, lightHeight and lightBehind of the same light), lightElevation: degrees (the earlier form, with lightAzimuth), shadow: bool (false; the first light casts a shadow, black at 50% times the art's opacity, hard-edged at the first light's softness 0 and blurred above it), shadowPosition: behind|below (behind; behind: on a plane square to the view, below: on the floor under the object, turned with it), shadowDistance: % (0..100, 0; how far the plane is from the object, as a share of its largest size), shadowBounds: % (10..400, 100; how far the plane reaches: at 100 it is four times the object's largest size across), graphics: array of 0..64 objects ([]; the 3D and Materials panel's Graphics on the plane, as Extrude & Bevel's, with face front only), render: object ({mode: shaded}; mode: shaded|wireframe, as Revolve's)}. Turns the flat art in 3D about the centre of its bounds; every fill and stroke keeps its paint, shaded as one plane.",
json!({"rotationX":-21.88,"rotationY":-23.4,"rotationZ":9.06,"perspectiveAngle":0.0,"shade":true,"lightColor":"#ffffff","lights":null,"lightRotation":125.26438968275465,"lightHeight":30.0,"lightBehind":false,"lightIntensity":80.0,"lightSoftness":0.0,"ambient":25.0,"shadow":false,"shadowPosition":"behind","shadowDistance":0.0,"shadowBounds":100.0,"graphics":[],"render":{"mode":"shaded"}}),
),
g(
+3 -3
View File
@@ -86,9 +86,9 @@ pub use raster::{
without_geometry,
};
pub use reshape::{
SYMBOL_ART_MAX_NODES, expand_outlined, follows_image_pixels, gives_image_shape, has_gradient_copies, has_instance_row_raster, has_item_geometry,
has_painted_effects, has_transform_art, has_transform_copies, has_transform_options, image_paint, instance_as_art, needs_outline, outer_effects,
outline_art, outline_text, paint_type_piece, reshape,
SYMBOL_ART_MAX_NODES, expand_outlined, follows_image_pixels, gives_image_shape, has_copied_row_raster, has_gradient_copies,
has_instance_row_raster, has_item_geometry, has_painted_effects, has_transform_art, has_transform_copies, has_transform_options, image_paint,
instance_as_art, needs_outline, outer_effects, outline_art, outline_text, paint_type_piece, reshape,
};
pub use revolve::{
CLASSIC_REVOLVE, REVOLVE, has_revolve, is_revolve, revolve_art, revolve_art_in, revolve_options, validate_revolve, validate_revolve_in,
+227 -31
View File
@@ -107,15 +107,66 @@ fn reaches_appearance(e: &Effect) -> bool {
}
/// Is `n` a path or compound path that its Transform effects make into art of separate objects
/// ([`has_gradient_copies`], [`has_layered_copies`], [`has_transform_options`], [`copied_raster_at`]),
/// or whose live-effect plug-ins paint what they return ([`has_painted_effects`])? It is drawn,
/// baked and expanded through that art ([`reshape`]).
/// ([`has_gradient_copies`], [`has_layered_copies`], [`has_transform_options`], [`copied_raster_at`],
/// [`has_copied_row_raster`]), or whose live-effect plug-ins paint what they return
/// ([`has_painted_effects`])? It is drawn, baked and expanded through that art ([`reshape`]).
pub fn has_transform_art(n: &Node) -> bool {
has_gradient_copies(n)
|| has_layered_copies(n)
|| has_transform_options(n)
|| has_painted_effects(n)
|| (matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) && copied_raster_at(n).is_some())
|| has_copied_row_raster(n)
}
/// Is `n` a path or compound path with a fill or stroke that paints and whose raster effects are
/// carried by copies: one whose own effects list a Transform effect that makes copies after a
/// raster effect that follows it ([`copied_row_raster_at`]), or one with a raster effect that
/// follows a Transform effect ([`crate::raster::follows`]) on a path whose own Transform effect makes
/// copies ([`has_transform_copies`])? Each copy is then an object of its own carrying that fill's or
/// stroke's raster effects, moved, turned, reflected and scaled with it ([`transform_item_leaf`],
/// [`follow_copies`]).
pub fn has_copied_row_raster(n: &Node) -> bool {
if !matches!(n.kind, NodeKind::Path { guide: false, clipping: false, .. } | NodeKind::Compound { .. }) {
return false;
}
// Checked first: this runs for every object drawn.
if !n.appearance.items.iter().any(follows_row_raster) {
return false;
}
n.appearance.items.iter().any(|i| crate::paints(i) && copied_row_raster_at(i.effects()).is_some()) || has_transform_copies(n)
}
/// Does `item` paint and carry a visible raster effect that follows a Transform effect
/// ([`crate::raster::follows`])?
fn follows_row_raster(item: &AppearanceItem) -> bool {
crate::paints(item) && item.effects().iter().any(|e| e.visible && crate::raster::follows(&e.id))
}
/// Where a fill's or stroke's own effects `fx` split so that each copy of a Transform effect carries
/// the raster effects listed before it: the index of the first visible Transform effect that makes
/// copies (an earlier one that makes copies included) for which a visible raster effect that
/// follows a Transform effect ([`crate::raster::follows`]) is listed before it, every other visible
/// effect before it is a geometry effect or such a raster effect, and no Transform effect before it
/// that makes copies or moves at random holds those raster effects back
/// ([`crate::raster::held_back`]). `None` otherwise, and when a raster effect is listed after it
/// and before a later Transform effect that makes copies or moves at random, which would apply to
/// the art that raster effect paints.
fn copied_row_raster_at(fx: &[Effect]) -> Option<usize> {
let copying =
|e: &Effect| e.visible && e.id == "distort.transform" && crate::distort::transform_map(Rect::ZERO, &merged_params(&e.id, &e.params), 0).1 > 0;
// Is a visible raster effect in `rest` listed before its last Transform effect that holds back?
let raster_held = |rest: &[Effect]| {
rest.iter().rposition(crate::raster::holds_back).is_some_and(|k| rest[..k].iter().any(|e| e.visible && crate::is_raster(&e.id)))
};
(0..fx.len()).find(|&t| {
let before = &fx[..t];
copying(&fx[t])
&& !raster_held(&fx[t + 1..])
&& crate::raster::held_back(before) == 0
&& before.iter().any(|e| e.visible && crate::raster::follows(&e.id))
&& before.iter().all(|e| !e.visible || is_geometry(&e.id) || crate::raster::follows(&e.id))
})
}
/// Where the own effects of `n`, a path, compound path, type, image or symbol instance, split so
@@ -999,7 +1050,7 @@ fn as_art_opts(
}
_ => outline_art_with(symbols, paint_doc, n, symbol_art, outline, nodes, apart)?,
};
reshape_leaves_apart(&mut art, &fx, &n.appearance.effects, Budget::EFFECTS, apart, paint_doc);
reshape_leaves_apart(&mut art, &fx, &n.appearance.effects, Budget::EFFECTS, (apart, has_copied_row_raster(n)), paint_doc);
if apart {
hoist_copies(&mut art);
}
@@ -1068,7 +1119,8 @@ fn copied_raster_art(doc: Option<&Document>, n: &Node, t: usize, apart: bool, ou
}
None => {
let mut art = one_piece(&source);
let carry = reshape_leaves_apart(&mut art, &geometry_effects(&source), &source.appearance.effects, Budget::EFFECTS, apart, doc);
let rows = has_copied_row_raster(&source);
let carry = reshape_leaves_apart(&mut art, &geometry_effects(&source), &source.appearance.effects, Budget::EFFECTS, (apart, rows), doc);
if apart {
hoist_copies(&mut art);
}
@@ -1109,7 +1161,7 @@ fn copied_raster_art(doc: Option<&Document>, n: &Node, t: usize, apart: bool, ou
}
}
let later: Vec<&Effect> = rest.iter().skip(1).filter(|e| e.visible && is_geometry(&e.id)).collect();
let carry = reshape_leaves_apart(&mut art, &later, &n.appearance.effects, Budget::EFFECTS, apart, doc);
let carry = reshape_leaves_apart(&mut art, &later, &n.appearance.effects, Budget::EFFECTS, (apart, has_copied_row_raster(n)), doc);
let mut ran = n.appearance.effects.clone();
if carry.skipped() {
carry.hide_skipped(&mut ran);
@@ -1240,19 +1292,19 @@ pub(crate) fn geometry_effects(n: &Node) -> Vec<&Effect> {
/// that live-effect plug-ins painting their pieces name are looked up in `doc`, and a deferred one
/// is listed by its index in `owner`, the effect list `fx` was taken from ([`reshape_leaves_apart`]).
pub(crate) fn reshape_leaves(art: &mut Node, fx: &[&Effect], owner: &[Effect], doc: Option<&Document>) {
reshape_leaves_apart(art, fx, owner, Budget::EFFECTS, false, doc);
reshape_leaves_apart(art, fx, owner, Budget::EFFECTS, (false, false), doc);
}
/// [`reshape_leaves`], and how gradients that paint the art as a whole (a group's own fills and
/// strokes) follow the effects ([`crate::Carry`]).
pub(crate) fn reshape_leaves_carrying(art: &mut Node, fx: &[&Effect], owner: &[Effect], doc: Option<&Document>) -> crate::Carry {
reshape_leaves_apart(art, fx, owner, Budget::EFFECTS, false, doc)
reshape_leaves_apart(art, fx, owner, Budget::EFFECTS, (false, false), doc)
}
/// [`reshape_leaves_carrying`] whose paths keep to `budget` together, or to what they cost.
#[cfg(test)]
pub(crate) fn reshape_leaves_within(art: &mut Node, fx: &[&Effect], budget: Budget, doc: Option<&Document>) -> crate::Carry {
reshape_leaves_apart(art, fx, &[], budget, false, doc)
reshape_leaves_apart(art, fx, &[], budget, (false, false), doc)
}
/// `art`, the group of the one piece a path's copies are made from ([`outline_art_with`]), holding
@@ -1273,7 +1325,10 @@ fn hoist_copies(art: &mut Node) {
/// [`reshape_leaves_carrying`] whose paths keep to `budget` together, or to what they cost; with
/// `apart`, a Transform effect's copies of each path are objects
/// of their own ([`copy_leaf`]) whatever paints them, as Expand Appearance makes them. A live-effect
/// of their own ([`copy_leaf`]) whatever paints them, as Expand Appearance makes them. With `rows`,
/// so are the copies of a path with a fill or stroke whose raster effects follow a Transform effect
/// ([`crate::raster::follows`]), and each copy's fills and strokes carry those raster effects moved,
/// turned, reflected and scaled with it ([`follow_copies`]). A live-effect
/// plug-in that paints what it returns makes each path a group of its pieces ([`paint_leaf`]),
/// whose swatches and patterns must be in `doc` (without one, pieces that name one are refused).
/// Returns how gradients that paint the art as a whole follow the effects, and the Transform
@@ -1284,7 +1339,14 @@ fn hoist_copies(art: &mut Node) {
/// type and live objects in it outlined and evaluated first ([`outlined_members`]). When a mask
/// stays as it was, or a Transform effect makes fewer copies than it asks for, art with linked
/// masks keeps its shape under that effect.
fn reshape_leaves_apart(art: &mut Node, fx: &[&Effect], owner: &[Effect], budget: Budget, apart: bool, doc: Option<&Document>) -> crate::Carry {
fn reshape_leaves_apart(
art: &mut Node,
fx: &[&Effect],
owner: &[Effect],
budget: Budget,
(apart, rows): (bool, bool),
doc: Option<&Document>,
) -> crate::Carry {
let mut whole = crate::Carry::default();
if fx.is_empty() {
return whole;
@@ -1321,7 +1383,7 @@ fn reshape_leaves_apart(art: &mut Node, fx: &[&Effect], owner: &[Effect], budget
let params = merged_params(&e.id, &e.params);
// Where a live-effect plug-in sits, which it is listed by when it is deferred.
let effect = owner.iter().position(|x| std::ptr::eq(x, *e)).or_else(|| listed.iter().position(|x| std::ptr::eq(*x, *e)));
let step = Step { e, params: &params, bounds, seed, effect, apart, doc, wholes: &wholes, held };
let step = Step { e, params: &params, bounds, seed, effect, apart, rows, doc, wholes: &wholes, held };
// Art with linked masks keeps its shape under an effect that a mask in it could not take
// as the art it masks did, so no mask is left apart from its art.
let before = masked.then(|| (art.clone(), used));
@@ -1365,6 +1427,7 @@ struct Step<'a> {
seed: u64,
effect: Option<usize>,
apart: bool,
rows: bool,
doc: Option<&'a Document>,
wholes: &'a HashMap<NodeId, bool>,
held: bool,
@@ -1529,8 +1592,12 @@ impl Step<'_> {
// make together; and Expand Appearance (`apart`) makes each copy an object.
// Fills and strokes that stack paint each copy below the one before (#5920, #6316).
// Each copy of a path with a linked mask carries the mask, moved with it.
// With `rows`, each copy carries the raster effects of its fills and strokes,
// following that copy's map.
let rows = self.rows && copies > 0 && leaf.appearance.items.iter().any(follows_row_raster);
let separate = copies > 0
&& (self.apart
|| rows
|| leaf.appearance.has_unplaced_gradient()
|| leaf.appearance.has_placed_gradient()
|| paints_copies_apart(&leaf.appearance, rule)
@@ -1538,9 +1605,12 @@ impl Step<'_> {
// The copies of a path replace it by a group of them, the path included.
let copied = |leaf: &Node| leaf.children().map_or(0, Vec::len);
if options.reach_appearance() {
let (made, moved) = transform_leaf(leaf, &path, map, copies, options, room, raster_map.is_some(), None);
let (made, moved) = transform_leaf(leaf, &path, map, copies, options, room, raster_map.is_some() || rows, None);
*used = used.minus(before).plus(made);
took |= moved;
if moved && rows {
follow_copies(leaf, map, None);
}
if moved {
// With Transform Objects off the path stays, and its mask takes the
// effect's stroke and pattern changes as its own art.
@@ -1556,6 +1626,9 @@ impl Step<'_> {
if separate {
let scaling = vectorcraft_doc::Scaling { keep_fit_when_flat: true, ..Default::default() };
let made = copy_leaf(leaf, &path, m, copies, scaling, room, None);
if rows {
follow_copies(leaf, m, None);
}
*used = used.minus(before).plus(made);
took = true;
moved_ids.insert(leaf.id);
@@ -1947,7 +2020,7 @@ fn transform_leaf(
kept: Kept,
) -> (Budget, bool) {
let mut scaling = copy_scaling(options);
if follows && copies == 0 {
if follows {
scaling.effects = options.strokes.then_some(scale_unfollowed as fn(&mut Effect, f64));
}
if !options.objects {
@@ -2263,7 +2336,8 @@ fn paint_piece(
/// Every path and compound path under `art` (other than clipping paths) with a fill or stroke whose
/// own Transform effect has Transform Patterns or Scale Strokes & Effects on
/// ([`item_transform_options`]), or whose own live-effect plug-in paints what it returns
/// ([`item_transform_options`]) or makes copies that carry the raster effects before it
/// ([`copied_row_raster_at`]), or whose own live-effect plug-in paints what it returns
/// ([`painted_plugin`]), made into a group of objects of its own ([`transform_item_leaf`]). The
/// new paths keep to one [`Budget::EFFECTS`] together (or to what `art` costs, when that is more).
/// The swatches and patterns painted pieces name must be in `doc`; without one they may name none.
@@ -2280,9 +2354,20 @@ fn makes_piece(e: &Effect) -> bool {
reaches_appearance(e) || painted_plugin(e).is_some()
}
/// Does `item` paint and carry an effect that [`makes_piece`]?
/// Where the fill's or stroke's own effects `fx` make its piece of a path an object of its own: the
/// index of the first effect that [`makes_piece`], or of the Transform effect whose copies carry the
/// raster effects before it ([`copied_row_raster_at`]), whichever is listed first.
fn piece_at(fx: &[Effect]) -> Option<usize> {
let copied = copied_row_raster_at(fx);
match fx.iter().position(makes_piece) {
Some(at) => Some(copied.map_or(at, |t| t.min(at))),
None => copied,
}
}
/// Does `item` paint and carry an effect that makes its piece an object of its own ([`piece_at`])?
fn item_makes_piece(item: &AppearanceItem) -> bool {
crate::paints(item) && item.effects().iter().any(makes_piece)
crate::paints(item) && piece_at(item.effects()).is_some()
}
/// `leaf`, a path or compound path with a fill or stroke whose own Transform effect has Transform
@@ -2292,12 +2377,17 @@ fn item_makes_piece(item: &AppearanceItem) -> bool {
/// as [`transform_leaf`] transforms an object with that effect's map, copies and options, so the
/// stroke's weight and dashes, the distances of the effects before the Transform effect and its
/// pattern follow the map, and the raster effects before it that follow it take their followed
/// values ([`follow_piece`]). The effects after it keep their values and apply to what it made
/// values ([`follow_piece`]), on each copy the values that copy's map gives them
/// ([`follow_copies`]). The effects after it keep their values and apply to what it made
/// ([`keep_listed`]), and with Transform Objects off so do the effects before it. The reference box
/// is that geometry's bounds and the seed is the leaf's id, as the renderer draws a fill's or
/// stroke's own effects. The geometry effects after the Transform effect then
/// stroke's own effects. A fill or stroke whose first such Transform effect makes copies that carry
/// the raster effects before it ([`copied_row_raster_at`]) becomes a path of its own the same way,
/// with neither option. The geometry effects after the Transform effect then
/// apply to the transformed path and its copies as one piece ([`transform_piece`]), and its other
/// effects stay on each of them. The other fills and strokes stay together on paths of the leaf's
/// effects stay on each of them, except that without either option the raster effects after a
/// Transform effect that makes copies paint once around all of them ([`lift_later_raster`]). The
/// other fills and strokes stay together on paths of the leaf's
/// geometry between them, with their own effects. `max` is the budget of the whole art and `used`
/// what it has spent.
///
@@ -2343,7 +2433,7 @@ fn transform_item_leaf(leaf: &mut Node, max: Budget, used: &mut Budget, doc: Opt
let later = |i: usize| (i + 1..transformed.len()).filter(|&j| transformed[j] || j == i + 1 || transformed[j - 1]).count();
for (i, item) in original.appearance.items.iter().enumerate() {
let fx = item.effects();
let Some(at) = fx.iter().position(makes_piece).filter(|_| crate::paints(item)) else {
let Some(at) = piece_at(fx).filter(|_| crate::paints(item)) else {
plain.push(item.clone());
continue;
};
@@ -2421,13 +2511,24 @@ fn transform_item_leaf(leaf: &mut Node, max: Budget, used: &mut Budget, doc: Opt
set_geometry(&mut p, g.clone(), rule);
let after = kept_before.len();
let keep = |k: usize| k >= after || !options.objects;
let (made, moved) = transform_leaf(&mut p, &g, map, copies, options, room, false, Some((&rest, &keep)));
*used = used.plus(made);
let from = crate::raster::held_back(before);
if moved && !held_later {
// Each copy carries the raster effects before the Transform effect, following that copy's
// map, unless a Transform effect before or after it holds them back.
let copied = copies > 0 && !held_later && from == 0;
let (made, moved) = transform_leaf(&mut p, &g, map, copies, options, room, copied, Some((&rest, &keep)));
*used = used.plus(made);
if moved && copied {
follow_copies(&mut p, map, Some(0..after));
} else if moved && !held_later {
follow_piece(&mut p, kept_before.get(from..).unwrap_or_default(), from, &fx[at]);
}
transform_piece(&mut p, (ctx.seed, i, &kept), crate::raster::held_back(&fx[..=at]), false, limit, used, doc);
// Without Transform Patterns and Scale Strokes & Effects, the raster effects after the
// Transform effect paint once around all the copies, as they paint around the one path of
// every copy.
if copies > 0 && !options.reach_appearance() {
lift_later_raster(&mut p, after);
}
pieces.push(Arc::new(p));
}
if !plain.is_empty() {
@@ -2478,6 +2579,7 @@ fn transform_piece(
count = count.max(item.effects().len());
}
});
let outer = held;
// The effects before a Transform effect among the piece's effects that makes copies or moves at
// random are held back from the Transform effects before it too.
let mut held = held;
@@ -2498,7 +2600,7 @@ fn transform_piece(
let from = held.min(j);
let mut holds = false;
let stage = vectorcraft_plugins::deferred::Stage { object: seed, effect: kept.get(j).copied().unwrap_or(j), item: Some(source) };
let at = PieceStage { j, from, seed, bounds, doc, stage };
let at = PieceStage { j, from, outer, seed, bounds, doc, stage };
// Stage `j` on `leaf`, a path `used` counts at `piece_cost` when `share`: whether `used`
// counts each path it became so, or `None` when it stays as it was.
let mut on_leaf = |leaf: &mut Node, share: bool| -> Option<Vec<bool>> {
@@ -2719,12 +2821,14 @@ thread_local! {
/// Where a stage of [`transform_piece`] runs: `j`, the index of its effect among the piece's
/// effects; `from`, the first of the effects before it whose raster effects follow a Transform
/// effect; the object's `seed`; the reference box `bounds` of all the piece's paths; the document
/// that painted pieces' swatches and patterns must be in; and the `stage` a deferred live-effect
/// plug-in is listed by.
/// effect; `outer`, how many of the piece's effects a Transform effect before them holds back; the
/// object's `seed`; the reference box `bounds` of all the piece's paths; the document that painted
/// pieces' swatches and patterns must be in; and the `stage` a deferred live-effect plug-in is
/// listed by.
struct PieceStage<'a> {
j: usize,
from: usize,
outer: usize,
seed: u64,
bounds: Rect,
doc: Option<&'a Document>,
@@ -2767,15 +2871,30 @@ fn piece_stage(leaf: &mut Node, e: &Effect, at: &PieceStage, (appearance, index)
let params = merged_params(&e.id, &e.params);
return paint_piece(leaf, &item, (appearance, index), (plugin, &params), at.bounds, room, at.doc, Some(at.stage));
}
if reaches_appearance(e) {
let copied = copies_carry(item.effects(), e, at);
if reaches_appearance(e) || copied {
let params = merged_params(&e.id, &e.params);
let (_, copies) = crate::distort::transform_map(at.bounds, &params, at.seed);
let options = crate::distort::TransformOptions::of(&params);
let map = crate::distort::transform_affine(at.bounds, &params, at.seed);
let j = at.j;
let keep = |k: usize| k > j || (k < j && !options.objects);
let (made, moved) = transform_leaf(leaf, &path, map, copies, options, room, false, Some((item.effects(), &keep)));
if moved {
let (made, moved) = transform_leaf(leaf, &path, map, copies, options, room, copied, Some((item.effects(), &keep)));
if moved && copied {
// Each copy's raster effects before the Transform effect follow that copy's map. The
// Transform effects before it have already moved them, so each run between two of
// them follows on its own.
let fx = item.effects();
let mut start = 0;
for k in 0..=j {
if k == j || fx.get(k).is_some_and(|f| f.id == "distort.transform") {
if start < k {
follow_copies(leaf, map, Some(start..k));
}
start = k + 1;
}
}
} else if moved {
follow_piece(leaf, was, at.from, e);
}
return Some(made);
@@ -2800,6 +2919,37 @@ fn piece_stage(leaf: &mut Node, e: &Effect, at: &PieceStage, (appearance, index)
Some(made)
}
/// Does Transform effect `e`, at stage `at` of [`transform_piece`] of a fill or stroke whose effects
/// are `fx`, make copies that each carry the raster effects listed before it, following that copy's
/// map ([`follow_copies`]), as the copies of the piece's first Transform effect do
/// ([`transform_item_leaf`])? It does when it makes copies with Transform Objects on, a visible
/// raster effect that follows a Transform effect ([`crate::raster::follows`]) is listed before it,
/// and no Transform effect that makes copies or moves at random holds those raster effects back:
/// none before the piece's effects, none listed before it after such a raster effect, and none
/// after it. Without Transform Patterns and Scale Strokes & Effects, every other visible effect
/// before it must also be a geometry effect or such a raster effect, and no visible raster effect
/// may be listed after it, as for [`copied_row_raster_at`].
fn copies_carry(fx: &[Effect], e: &Effect, at: &PieceStage) -> bool {
if !e.visible || e.id != "distort.transform" || at.outer > 0 {
return false;
}
let params = merged_params(&e.id, &e.params);
if !crate::distort::TransformOptions::of(&params).objects || crate::distort::transform_map(Rect::ZERO, &params, 0).1 == 0 {
return false;
}
let before = fx.get(..at.j).unwrap_or_default();
let after = fx.get(at.j + 1..).unwrap_or_default();
if crate::raster::held_back(before) > 0
|| !before.iter().any(|f| f.visible && crate::raster::follows(&f.id))
|| after.iter().any(crate::raster::holds_back)
{
return false;
}
reaches_appearance(e)
|| (before.iter().all(|f| !f.visible || is_geometry(&f.id) || crate::raster::follows(&f.id))
&& !after.iter().any(|f| f.visible && crate::is_raster(&f.id)))
}
/// Are `a` and `b` paths or compound paths that differ only in their fills and strokes?
fn same_path(a: &Node, b: &Node) -> bool {
let leaf = |n: &Node| matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. });
@@ -2872,6 +3022,52 @@ fn follow_piece(leaf: &mut Node, was: &[Effect], from: usize, t: &Effect) {
}
}
/// Make the raster effects that follow a Transform effect ([`crate::raster::follows`]) on the fills
/// and strokes of each copy [`copy_leaf`] made of `leaf` with map `m` follow that copy's map: the
/// copy `k` places below the original takes the linear part of `m` `k` times
/// ([`crate::raster::follow_contents`]), and the original, on top, keeps its effects. `range`, when
/// given, is which of each fill's or stroke's effects follow; the others keep their values.
fn follow_copies(leaf: &mut Node, m: Affine, range: Option<std::ops::Range<usize>>) {
let step = m.with_translation(vectorcraft_geom::Vec2::ZERO);
let Some(children) = leaf.children_mut() else { return };
let mut a = Affine::IDENTITY;
for c in children.iter_mut().rev().skip(1) {
a *= step;
for item in &mut Arc::make_mut(c).appearance.items {
let fx = item.effects_mut();
let fx = match &range {
Some(r) => fx.get_mut(r.clone()).unwrap_or_default(),
None => fx.as_mut_slice(),
};
crate::raster::follow_contents(fx, a, Affine::IDENTITY);
}
}
}
/// Move the raster effects from index `after` on of the fills and strokes of the paths under `p`,
/// a group of copies of one fill or stroke with the same effects, onto `p` itself, so they paint
/// once around all of the copies. The other effects stay where they are.
fn lift_later_raster(p: &mut Node, after: usize) {
if p.children().is_none() {
return;
}
let mut lifted: Option<Vec<Effect>> = None;
for_each_leaf(p, &mut |l| {
for item in &mut l.appearance.items {
let fx = item.effects_mut();
if fx.len() <= after {
continue;
}
let (raster, other): (Vec<Effect>, Vec<Effect>) = fx.split_off(after).into_iter().partition(|e| crate::is_raster(&e.id));
fx.extend(other);
lifted.get_or_insert(raster);
}
});
if let Some(raster) = lifted {
p.appearance.effects.extend(raster);
}
}
/// The bounds of each group of type's outlines under `n` ([`outline_text`]), `n` included, in
/// order. A group inside one of them is part of it.
fn type_outline_bounds(n: &Node, out: &mut Vec<Option<Rect>>) {
+2 -1
View File
@@ -992,7 +992,8 @@ fn art(doc: Option<&Document>, n: &Node, expand: bool) -> Option<Node> {
if let Some(b) = p.bounds()
&& let Some(mut shadow) = shadow_of(n.id, fx, &p, item, b, rule_options(fx, rule), kept).ok()?
{
shadow.appearance.effects = art.appearance.effects.clone();
// The shadow keeps its own blur (the light's Softness) below the later effects.
shadow.appearance.effects.extend(art.appearance.effects.iter().cloned());
shadows.push(Arc::new(shadow));
}
children.push(Arc::new(art));
+5 -1
View File
@@ -2177,7 +2177,11 @@ pub fn solid_art_in(doc: Option<&Document>, n: &Node) -> Option<Node> {
Arc::make_mut(&mut art).appearance.effects = later.clone();
art
};
shadows.extend(shadow.into_iter().map(with_later));
// A shadow keeps its own blur (the light's Softness) below the later effects.
shadows.extend(shadow.into_iter().map(|mut art| {
Arc::make_mut(&mut art).appearance.effects.extend(later.iter().cloned());
art
}));
children.extend(surfaces.into_iter().map(with_later));
} else {
let flat = Appearance { items: vec![item.clone()], ..Default::default() };
+17 -8
View File
@@ -1,12 +1,12 @@
//! The shadow of the 3D and Materials effects (Extrude & Bevel, Inflate, Rotate and Revolve): the
//! `shadow` switch with `shadowPosition`, `shadowDistance` and `shadowBounds`, and the shape it
//! draws behind the solids.
//! draws behind the solids, blurred by the first light's Softness.
use std::ops::Range;
use std::sync::Arc;
use serde_json::Value;
use serde_json::{Value, json};
use vectorcraft_doc::color::{BlendMode, Color, Paint};
use vectorcraft_doc::{Appearance, AppearanceItem, FillLayer, Node, NodeId};
use vectorcraft_doc::{Appearance, AppearanceItem, Effect, FillLayer, Node, NodeId};
use vectorcraft_three_d::{Shadow, ShadowCaster, ShadowPlane, ShadowPosition};
use super::Scope;
@@ -15,15 +15,21 @@ use crate::util::{flag, num, text};
/// The shadow's paint: black at this opacity. VectorCraft's own values.
const SHADOW_OPACITY: f32 = 0.5;
/// Blur radii below this, in points, leave the shadow hard-edged.
const MIN_BLUR: f64 = 0.01;
/// The shadow `p` asks for, or `None` with the switch off or when the first light lights nothing
/// (Shading is off or its intensity is 0), so that no shadow is built.
/// (Shading is off or its intensity is 0), so that no shadow is built. Its softness is the first
/// light's.
pub(crate) fn options(p: &Value) -> Option<Shadow> {
let intensity = crate::lighting::lights(p).and_then(|l| l.iter().next().map(|l| l.intensity)).unwrap_or_else(|| num(p, "lightIntensity", 80.0));
let first = crate::lighting::lights(p).and_then(|l| l.iter().next().copied());
let intensity = first.map_or_else(|| num(p, "lightIntensity", 80.0), |l| l.intensity);
let lit = flag(p, "shade", true) && intensity > 0.0;
(lit && flag(p, "shadow", false)).then(|| Shadow {
position: ShadowPosition::parse(text(p, "shadowPosition", "behind")).unwrap_or_default(),
distance: num(p, "shadowDistance", 0.0) / 100.0,
bounds: num(p, "shadowBounds", 100.0) / 100.0,
softness: first.map_or_else(|| num(p, "lightSoftness", 0.0) / 100.0, |l| l.softness),
})
}
@@ -64,8 +70,9 @@ pub(crate) fn casts(opacity: f32) -> bool {
}
/// The shadow of the faces in `caster` as a path of object `id`, cast by art in `ink`: filled
/// black at [`SHADOW_OPACITY`] times its opacity, in its blending mode, with the nonzero rule;
/// `None` when it casts nothing.
/// black at [`SHADOW_OPACITY`] times its opacity, in its blending mode, with the nonzero rule, and
/// with the light's Softness a Gaussian Blur of the plane's radius ([`ShadowPlane::blur`]), which
/// is drawn, measured, exported and expanded as that effect is; `None` when it casts nothing.
pub(crate) fn art(id: NodeId, caster: &ShadowCaster, shadow: Shadow, ink: Ink) -> Option<Node> {
let all = 0..caster.len();
let all = std::slice::from_ref(&all);
@@ -78,7 +85,9 @@ fn piece(id: NodeId, caster: &ShadowCaster, plane: &ShadowPlane, faces: &[Range<
let mut fill = FillLayer::new(Paint::solid(Color::BLACK));
fill.opacity = SHADOW_OPACITY * ink.opacity.clamp(0.0, 1.0);
fill.blend = ink.blend;
Some(Node::path(id, path, Appearance { items: vec![AppearanceItem::Fill(fill)], ..Default::default() }))
let blur = plane.blur();
let effects = if blur >= MIN_BLUR { vec![Effect { id: "blur.gaussian".into(), params: json!({"radius": blur}), visible: true }] } else { vec![] };
Some(Node::path(id, path, Appearance { items: vec![AppearanceItem::Fill(fill)], effects, ..Default::default() }))
}
/// Whether `a` and `b` are the same objects' scopes (each member holds its own copies).
+54
View File
@@ -87,6 +87,40 @@ fn the_shadow_moves_with_its_settings() {
}
}
/// The radius of the Gaussian Blur on shadow `n`; `None` without one.
fn shadow_blur(n: &Node) -> Option<f64> {
match n.appearance.effects.as_slice() {
[] => None,
[e] if e.id == "blur.gaussian" && e.visible => e.params["radius"].as_f64(),
other => panic!("unexpected effects on the shadow: {other:?}"),
}
}
/// The first light's Softness blurs the shadow, more with Softness and with Distance from Object;
/// at 0 % it stays the hard-edged path. A list of lights takes the first light's Softness.
#[test]
fn the_first_lights_softness_blurs_the_shadow() {
for id in CASTING {
let blur = |params: Value| {
let mut n = square_node(1, 0.0);
n.appearance.effects.push(crate::new_effect(id, &params).unwrap());
let lit = art(&n, id).unwrap();
let shadow = &lit.children().unwrap()[0];
assert!(is_shadow(shadow), "{id} {params}");
shadow_blur(shadow)
};
assert_eq!(blur(json!({"shadow": true})), None, "{id}: hard at 0 %");
let soft = blur(json!({"shadow": true, "lightSoftness": 50})).unwrap_or_else(|| panic!("{id}"));
let softer = blur(json!({"shadow": true, "lightSoftness": 100})).unwrap();
let far = blur(json!({"shadow": true, "lightSoftness": 100, "shadowDistance": 100})).unwrap();
assert!(soft > 0.0 && softer > soft && far > softer, "{id}: {soft} {softer} {far}");
let first = json!({"shadow": true, "lightSoftness": 0, "lights": [{"softness": 100}, {"softness": 0}]});
assert_eq!(blur(first), Some(softer), "{id}: the first light's");
let second = json!({"shadow": true, "lightSoftness": 100, "lights": [{"softness": 0}, {"softness": 100}]});
assert_eq!(blur(second), None, "{id}: only the first light casts");
}
}
#[test]
fn shadow_settings_out_of_range_or_of_the_wrong_kind_are_refused() {
for id in CASTING {
@@ -203,6 +237,26 @@ fn the_shadows_of_every_fill_go_behind_every_fill_s_solid() {
}
}
/// A fill's own 3D effect blurs its shadow by the light's Softness too, and the effects after it
/// in the fill's list follow the blur.
#[test]
fn a_fills_own_3d_effect_keeps_the_blur_below_its_later_effects() {
for id in CASTING {
for later in [None, Some(crate::new_effect("distort.roughen", &json!({})).unwrap())] {
let mut n = square_node(1, 0.0);
let fill = n.appearance.items.iter_mut().find(|i| matches!(i, AppearanceItem::Fill(_))).unwrap();
fill.effects_mut().push(crate::new_effect(id, &json!({"shadow": true, "lightSoftness": 100})).unwrap());
fill.effects_mut().extend(later.clone());
let lit = art(&n, id).unwrap_or_else(|| panic!("{id}"));
let shadow = &lit.children().unwrap()[0];
assert!(is_shadow(shadow), "{id}");
let ids: Vec<&str> = shadow.appearance.effects.iter().map(|e| e.id.as_str()).collect();
let want: Vec<&str> = std::iter::once("blur.gaussian").chain(later.as_ref().map(|e| e.id.as_str())).collect();
assert_eq!(ids, want, "{id}");
}
}
}
#[test]
fn expand_appearance_keeps_the_shadow_as_a_path() {
for id in CASTING {
+206 -3
View File
@@ -816,8 +816,8 @@ fn a_groups_transform_applies_after_its_members_own() {
}
/// An object's Transform effect transforms the raster effects of its fills and strokes with the
/// art, whatever its options: drawn, drawn through the art an option makes, and baked. One that
/// makes copies leaves them.
/// art, whatever its options: drawn, drawn through the art an option makes, and baked. For one that
/// makes copies, see [`each_copy_of_an_objects_transform_carries_its_fills_or_strokes_shadow`].
#[test]
fn an_objects_transform_moves_its_fills_shadows() {
let cases = [
@@ -825,7 +825,6 @@ fn an_objects_transform_moves_its_fills_shadows() {
(json!({"scaleH": 200, "scaleV": 100, "strokes": true}), (20.0, 10.0)),
(json!({"rotate": 90, "patterns": true}), (10.0, -10.0)),
(json!({"rotate": 90, "strokes": true}), (10.0, -10.0)),
(json!({"scaleH": 200, "scaleV": 200, "copies": 1}), (10.0, 10.0)),
];
for (params, want) in cases {
let mut n = fill_square(40, vec![shadow(10.0, 10.0, 0.0)]);
@@ -1217,6 +1216,169 @@ fn copies_past_the_budget_each_keep_their_shadow() {
assert_eq!(shadows_in(&art).len(), paths);
}
/// `n` with only its fill (or only a 4 pt blue stroke, with `stroke`), whose own effects are
/// `effects`.
fn one_row(mut n: Node, stroke: bool, effects: Vec<Effect>) -> Node {
let mut item = if stroke {
vectorcraft_doc::AppearanceItem::Stroke(vectorcraft_doc::StrokeLayer::new(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), 4.0))
} else {
n.appearance.items.remove(0)
};
*item.effects_mut() = effects;
n.appearance.items = vec![item];
n
}
/// A case of [`copying_cases`]: the params, each copy's offset and each copy's blur.
type CopyingCase = (Value, Vec<(f64, f64)>, Vec<f64>);
/// The cases of a Transform effect that makes copies with a drop shadow (10, 0) and a blur of 4
/// before it: the params, each copy's offset and each copy's blur, the last copy first.
fn copying_cases() -> Vec<CopyingCase> {
vec![
(json!({"moveH": 100, "copies": 2}), vec![(10.0, 0.0), (10.0, 0.0), (10.0, 0.0)], vec![4.0, 4.0, 4.0]),
// A turn of 90° counterclockwise on screen takes an offset to the right to one upward.
(json!({"rotate": 90, "copies": 2}), vec![(-10.0, 0.0), (0.0, -10.0), (10.0, 0.0)], vec![4.0, 4.0, 4.0]),
(json!({"reflectX": true, "moveH": 100, "copies": 1}), vec![(-10.0, 0.0), (10.0, 0.0)], vec![4.0, 4.0]),
(json!({"scaleH": 200, "scaleV": 200, "moveH": 100, "copies": 1}), vec![(20.0, 0.0), (10.0, 0.0)], vec![8.0, 4.0]),
// Scale Strokes & Effects does not scale the shadow a second time, nor leave it unturned.
(
json!({"scaleH": 200, "scaleV": 200, "rotate": 90, "moveH": 100, "copies": 1, "strokes": true}),
vec![(0.0, -20.0), (10.0, 0.0)],
vec![8.0, 4.0],
),
(
json!({"scaleH": 200, "scaleV": 200, "rotate": 90, "moveH": 100, "copies": 1, "patterns": true}),
vec![(0.0, -20.0), (10.0, 0.0)],
vec![8.0, 4.0],
),
]
}
/// Check that `n` is drawn, expanded and baked as `want.len()` paths, each with one shadow at the
/// offset and blur `want` and `blurs` give it, the last copy first.
fn assert_copies_carry(n: &Node, want: &[(f64, f64)], blurs: &[f64], what: &str) {
assert!(crate::has_transform_art(n), "{what}");
for (how, art) in
[("drawn", crate::reshape(None, n, None).unwrap()), ("expanded", expand_outlined(None, n, None).unwrap()), ("baked", baked(n.clone()))]
{
assert_eq!(paths_in(&art), want.len(), "{what}: {how} {art:?}");
let drawn = shadows_in(&art);
assert!(near(&drawn, want), "{what}: {how} {drawn:?}");
let b = shadow_blurs_in(&art);
assert!(b.len() == blurs.len() && b.iter().zip(blurs).all(|(x, y)| (x - y).abs() < 1e-9), "{what}: {how} blurs {b:?}");
}
}
/// A fill's or stroke's own Transform effect that makes copies gives each copy the shadow listed
/// before it in that fill's or stroke's effects, moved, turned, reflected and scaled with that copy,
/// the last copy lowest: drawn, expanded and baked. The original keeps the shadow as it is.
#[test]
fn each_copy_of_a_fills_or_strokes_own_transform_carries_the_shadow_before_it() {
for stroke in [false, true] {
for (params, want, blurs) in copying_cases() {
let n = one_row(square(95, vec![]), stroke, vec![shadow(10.0, 0.0, 4.0), transform(params.clone())]);
assert_copies_carry(&n, &want, &blurs, &format!("stroke {stroke}: {params}"));
}
// A Transform effect that makes copies before the shadow: its copies make one piece, which
// the Transform effect after the shadow copies, each copy with its own shadow.
let effects =
vec![transform(json!({"moveV": 100, "copies": 1})), shadow(10.0, 0.0, 4.0), transform(json!({"rotate": 90, "moveH": 200, "copies": 1}))];
let n = one_row(square(95, vec![]), stroke, effects);
assert!(crate::has_transform_art(&n), "stroke {stroke}");
for (how, art) in
[("drawn", crate::reshape(None, &n, None).unwrap()), ("expanded", expand_outlined(None, &n, None).unwrap()), ("baked", baked(n.clone()))]
{
let drawn = shadows_in(&art);
assert!(near(&drawn, &[(0.0, -10.0), (10.0, 0.0)]), "stroke {stroke}: two copying Transform effects, {how} {drawn:?}");
}
}
}
/// A Transform effect that makes copies, listed after a fill's or stroke's first Transform effect
/// with Transform Patterns on, gives each copy the shadow listed before it, as the first one's
/// copies do, with or without options of its own: drawn, expanded and baked.
#[test]
fn each_copy_of_a_later_copying_transform_carries_the_shadow_before_it() {
for stroke in [false, true] {
for (params, want, blurs) in copying_cases() {
let effects = vec![transform(json!({"patterns": true})), shadow(10.0, 0.0, 4.0), transform(params.clone())];
let n = one_row(square(102, vec![]), stroke, effects);
assert_copies_carry(&n, &want, &blurs, &format!("stroke {stroke}: {params}"));
}
}
}
/// A fill's or stroke's shadow under its object's Transform effect that makes copies is carried by
/// each copy, moved, turned, reflected and scaled with it: for a single fill, a single stroke, and
/// a fill and a stroke that paint each copy below the one before. Drawn, expanded and baked.
#[test]
fn each_copy_of_an_objects_transform_carries_its_fills_or_strokes_shadow() {
for (params, want, blurs) in copying_cases() {
for stroke in [false, true] {
let mut n = one_row(square(96, vec![]), stroke, vec![shadow(10.0, 0.0, 4.0)]);
n.appearance.effects = vec![transform(params.clone())];
assert_copies_carry(&n, &want, &blurs, &format!("stroke {stroke}: {params}"));
}
// Both a fill and a stroke: only the fill has the shadow.
let mut n = square(97, vec![transform(params.clone())]);
if let Some(vectorcraft_doc::AppearanceItem::Stroke(s)) = n.appearance.items.get_mut(1) {
s.paint = Paint::solid(Color::BLACK);
s.width = 2.0;
}
*n.appearance.items[0].effects_mut() = vec![shadow(10.0, 0.0, 4.0)];
assert!(crate::has_transform_art(&n), "{params}");
for (how, art) in
[("drawn", crate::reshape(None, &n, None).unwrap()), ("expanded", expand_outlined(None, &n, None).unwrap()), ("baked", baked(n.clone()))]
{
let drawn = shadows_in(&art);
assert!(near(&drawn, &want), "layered {params}: {how} {drawn:?}");
}
}
}
/// A shadow listed after a fill's own Transform effect that makes copies paints once around all of
/// them, and one listed before it on each copy. A Transform effect that makes no copies, or has
/// Transform Objects off, draws the fill as before, without art.
#[test]
fn a_fills_shadow_after_its_own_copying_transform_paints_once_around_the_copies() {
let effects = vec![shadow(10.0, 0.0, 0.0), transform(json!({"rotate": 90, "copies": 1})), shadow(0.0, 5.0, 0.0)];
let n = one_row(square(98, vec![]), false, effects);
for (how, art) in
[("drawn", crate::reshape(None, &n, None).unwrap()), ("expanded", expand_outlined(None, &n, None).unwrap()), ("baked", baked(n.clone()))]
{
assert!(near(&shadows_in(&art), &[(0.0, 5.0), (0.0, -10.0), (10.0, 0.0)]), "{how}: {:?}", shadows_in(&art));
assert_eq!(paths_in(&art), 2, "{how}");
}
for params in [json!({"rotate": 90}), json!({"rotate": 90, "copies": 1, "objects": false})] {
let n = one_row(square(99, vec![]), false, vec![shadow(10.0, 0.0, 0.0), transform(params.clone())]);
assert!(!crate::has_transform_art(&n), "{params}");
assert!(!crate::has_copied_row_raster(&n), "{params}");
}
// A shadow between two Transform effects that make copies paints on what the second one
// copies, so the fill is drawn as before, without art.
let copies = transform(json!({"rotate": 90, "copies": 1}));
let n = one_row(square(99, vec![]), false, vec![shadow(10.0, 0.0, 0.0), copies.clone(), shadow(0.0, 5.0, 0.0), copies]);
assert!(!crate::has_copied_row_raster(&n));
assert!(!crate::has_transform_art(&n));
}
/// Copies of a fill's own Transform effect that stop at the effect budget each keep their shadow,
/// and so do those of an object's Transform effect for its fill's shadow.
#[test]
fn row_copies_past_the_budget_each_keep_their_shadow() {
let copies = transform(json!({"moveV": 50, "copies": 1000}));
let own = one_row(path_node(100, wavy(30_000), vec![]), false, vec![shadow(1.0, 0.5, 0.0), copies.clone()]);
let mut owner = one_row(path_node(101, wavy(30_000), vec![]), false, vec![shadow(1.0, 0.5, 0.0)]);
owner.appearance.effects = vec![copies];
for n in [own, owner] {
let art = crate::reshape(None, &n, None).unwrap();
let paths = paths_in(&art);
assert!(paths > 1 && paths < 1001, "{paths}");
assert_eq!(shadows_in(&art).len(), paths);
}
}
/// Black 40 pt "IIII" with its baseline at (5, 60) and `effects`.
fn type_node(id: u64, effects: Vec<Effect>) -> Node {
use vectorcraft_doc::text::{CharStyle, TextObject};
@@ -1309,3 +1471,44 @@ fn type_with_a_reshaped_fill_keeps_one_shadow_around_its_copies() {
}));
assert_eq!(crate::outer_effects(&filled).len(), 2);
}
/// Type whose own fill's Transform effect makes copies is drawn as its outlines, and each copy
/// carries the shadow listed before that Transform effect, as a path's copies do: for the fill's
/// first Transform effect and for one listed after a Transform effect with Transform Patterns on.
/// Drawn, expanded and baked.
#[test]
fn type_carries_its_fills_shadow_on_each_copy() {
let filled = |mut n: Node, effects: Vec<Effect>| {
n.appearance.items.push(vectorcraft_doc::AppearanceItem::Fill(vectorcraft_doc::FillLayer {
effects,
..vectorcraft_doc::FillLayer::new(Paint::solid(Color::BLACK))
}));
n
};
let copying = vec![shadow(10.0, 0.0, 0.0), transform(json!({"moveH": 100, "copies": 1}))];
if !crate::outline_text(&type_node(95, vec![])).is_some_and(|o| paths_in(&o) > 0) {
eprintln!("type skipped: built without fonts (enable vectorcraft-text's bundled-fonts to run it)");
return;
}
let later = vec![transform(json!({"patterns": true})), shadow(10.0, 0.0, 0.0), transform(json!({"moveH": 100, "copies": 1}))];
for (what, effects) in [("first", copying), ("later", later)] {
let n = filled(type_node(95, vec![]), effects);
for (how, art) in
[("drawn", crate::reshape(None, &n, None)), ("expanded", expand_outlined(None, &n, None)), ("baked", Some(baked(n.clone())))]
{
let art = art.unwrap_or_else(|| panic!("{what}: {how}"));
assert!(near(&shadows_in(&art), &[(10.0, 0.0), (10.0, 0.0)]), "{what}: {how} {:?}", shadows_in(&art));
// The two shadows are on two objects 100 pt apart: the type and its copy.
let mut lefts = vec![];
art.walk(&mut |m| {
let lists = std::iter::once(&m.appearance.effects).chain(m.appearance.items.iter().map(|i| i.effects()));
let shadows = lists.map(|l| l.iter().filter(|e| e.id == "stylize.dropShadow").count()).sum::<usize>();
if let Some(b) = m.geometric_bounds() {
lefts.extend(std::iter::repeat_n(b.x0, shadows));
}
});
lefts.sort_by(f64::total_cmp);
assert!(lefts.len() == 2 && (lefts[1] - lefts[0] - 100.0).abs() < 1e-6, "{what}: {how} {lefts:?}");
}
}
}
+1 -1
View File
@@ -703,7 +703,7 @@ impl Relink {
self.name(Res::ParaStyle, s);
}
}
for r in [&mut l.values_rows, &mut l.categories_rows, &mut l.legend_rows].into_iter().flatten() {
for r in [&mut l.values_rows, &mut l.categories_rows, &mut l.legend_rows, &mut l.axis_rows, &mut l.ring_rows].into_iter().flatten() {
r.paint.fill.iter_mut().chain(r.paint.stroke.iter_mut()).for_each(|p| self.paint(p));
}
}
+24
View File
@@ -1089,6 +1089,27 @@ fn expand_pieces(
expanded
}
/// `m`, the art a 3D effect expanded into, with each object in it that has effects of its own (a
/// shadow blurred by the light's Softness) expanded as Expand Appearance expands it on its own:
/// a blurred shadow becomes an image. Groups in `m` without effects that hold such an object are
/// looked into; the rest are left as they are. The objects `skip` lists are not expanded.
fn expand_raster_pieces(d: &mut Document, mut m: Node, brushes: &[vectorcraft_brush::Brush], skip: &[NodeId], raster: &mut RasterBudget) -> Node {
for c in m.children_mut().into_iter().flatten() {
if !c.appearance.effects.is_empty() {
if let Some(e) = expanded_node(d, (**c).clone(), brushes, skip, &mut vec![], raster) {
*c = Arc::new(e);
}
} else if c.children().is_some() {
let mut holds = false;
c.walk(&mut |n| holds |= !n.appearance.effects.is_empty());
if holds {
*c = Arc::new(expand_raster_pieces(d, (**c).clone(), brushes, skip, raster));
}
}
}
m
}
/// Replace each symbol instance in `m`, art an instance placed (`depth` instances deep), whose
/// active fill or stroke has a geometry or raster effect ([`effects::has_item_geometry`],
/// [`effects::has_instance_row_raster`]) by its art ([`expanded_instance`]), and the instances in
@@ -1353,6 +1374,9 @@ fn expanded_node(
m
})
};
// A 3D effect's shadow blurred by the light's Softness keeps its blur in the art: it
// expands in turn, to an image.
let m = if effects::has_solid(&v) || effects::has_revolve(&v) { m.map(|m| expand_raster_pieces(d, m, brushes, skip, raster)) } else { m };
match image {
Some((image, _)) => {
let mut m = m.unwrap_or(v);
+43
View File
@@ -1017,6 +1017,49 @@ fn a_3d_shadow_is_one_undo_step_saved_exported_and_expanded() {
assert_eq!(shadows, 1);
}
/// With the light's Softness, the 3D shadow is blurred: the canvas paints past the hard shadow's
/// edge, the object's bounds take the blur in, SVG export blurs it as it does a Gaussian Blur
/// effect, and Expand Appearance keeps it as an image with no live effect left.
#[test]
fn a_soft_3d_shadow_is_drawn_measured_exported_and_expanded_blurred() {
let (mut s, id) = session_with_rect();
s.execute("effect.apply", &json!({"effect": effects::EXTRUDE, "ids": [id.0], "item": null})).unwrap();
let set = |s: &mut Session, params: serde_json::Value| {
s.execute("effect.setParams", &json!({"ids": [id.0], "index": 0, "item": null, "params": params})).unwrap();
};
let draw = |s: &Session| {
vectorcraft_render::Renderer::new().render(&s.doc().unwrap().doc, 400, 400, vectorcraft_geom::Affine::IDENTITY, &Default::default()).pixels
};
let bounds = |s: &Session| {
let doc = &s.doc().unwrap().doc;
vectorcraft_render::effect_bounds(&doc.symbol_boxes(), doc.node(id).unwrap()).unwrap()
};
let blurs = |s: &mut Session| {
let svg = s.execute("document.serialize", &json!({"format": "svg"})).unwrap();
let svg = svg["data"].as_str().or_else(|| svg["text"].as_str()).map(str::to_string).unwrap_or_else(|| svg.to_string());
svg.matches("<feGaussianBlur").count()
};
let none = draw(&s);
set(&mut s, json!({"shadow": true, "shadowDistance": 50}));
let (hard, hard_bounds, hard_blurs) = (draw(&s), bounds(&s), blurs(&mut s));
let undo = s.doc().unwrap().history.undo.len();
set(&mut s, json!({"lightSoftness": 100}));
assert_eq!(s.doc().unwrap().history.undo.len(), undo + 1, "one undo step");
let (soft, soft_bounds) = (draw(&s), bounds(&s));
// Pixels the hard shadow leaves as they are, the soft one paints.
let spread = none.chunks(4).zip(hard.chunks(4)).zip(soft.chunks(4)).filter(|((n, h), s)| n == h && n != s).count();
assert!(spread > 100, "{spread}");
assert!(soft_bounds.contains_rect(hard_bounds) && soft_bounds.area() > hard_bounds.area(), "{hard_bounds:?} {soft_bounds:?}");
assert_eq!(blurs(&mut s), hard_blurs + 1, "SVG export blurs the shadow as a Gaussian Blur effect");
s.execute("effect.expandAppearance", &json!({"ids": [id.0]})).unwrap();
let (mut live, mut pictures) = (0, 0);
s.doc().unwrap().doc.walk(|n| {
live += usize::from(!n.appearance.effects.is_empty() || n.appearance.items.iter().any(|i| !i.effects().is_empty()));
pictures += usize::from(matches!(n.kind, NodeKind::Image(_)));
});
assert_eq!((live, pictures), (0, 1), "the blurred shadow expands to an image");
}
/// Radial Blur's Blur Center: stored as given, drawn about that point of the object's bounds, and
/// a value outside 0 to 1 (or not a number) is refused with nothing changed and no undo step.
#[test]
+1 -1
View File
@@ -129,9 +129,9 @@ mod commands;
mod export_names;
mod formats;
pub(crate) use access::check_images_in;
#[cfg(not(target_arch = "wasm32"))]
pub(crate) use access::list_dir;
pub(crate) use access::{check_images_in, check_scripts_of};
pub use access::{check_linked_images, check_linked_scripts, write_file_with, write_save_file, write_save_file_with};
#[cfg(all(test, not(target_arch = "wasm32")))]
+43 -11
View File
@@ -121,22 +121,54 @@ pub(crate) fn naming_in_message(msg: &str, path: &str, name: &str) -> String {
out
}
/// The error for an SVG of a document that links a JavaScript file outside the read roots.
/// The error for a file that would name a JavaScript file the document links outside the read roots.
pub(crate) const SCRIPT_OUTSIDE: &str = "a linked JavaScript file is outside the read roots";
/// `cmd` may write `st`'s document in format `format` (a format id): any format but SVG and SVGZ,
/// and those too unless read roots are in force and the document links a JavaScript file outside
/// them (`svg_scripts`, a relative path taken from the document's folder; a URL is not checked),
/// which the file's `<script>` element would name. The error names no file or folder.
pub fn check_linked_scripts(cmd: &str, format: &str, st: &crate::DocState) -> Result<()> {
if !matches!(format, "svg" | "svgz") || crate::file_access::current().is_none() {
/// `cmd` may write `st`'s document in format `format` (a format id) with options `p` (presets
/// written out): always, unless read roots are in force, the document links a JavaScript file
/// outside them (`svg_scripts`, a relative path taken from the document's folder; a URL is not
/// checked) and the file names it ([`names_linked_scripts`], with the artboards `p` picks counted
/// in `st`'s document): an SVG's `<script>` element, or the native document that a native file, a
/// `.ai` file, an EPS file or a PDF with Preserve Editing carries. The error names no file or folder.
pub fn check_linked_scripts(cmd: &str, format: &str, st: &crate::DocState, p: &Value) -> Result<()> {
check_scripts_of(cmd, &st.doc, st.path.as_deref(), || names_linked_scripts(cmd, format, p, st.doc.artboards.len()))
}
/// `doc`, saved at `doc_path`, may be written by `cmd` in a file that names its linked JavaScript
/// files when `names` says so: as [`check_linked_scripts`] allows it.
pub(crate) fn check_scripts_of(cmd: &str, doc: &vectorcraft_doc::Document, doc_path: Option<&str>, names: impl FnOnce() -> bool) -> Result<()> {
if crate::file_access::current().is_none() || !doc.svg_scripts.iter().any(|f| crate::cmd::links::script_hidden(f, doc_path)) || !names() {
return Ok(());
}
let doc_path = st.path.as_deref();
if st.doc.svg_scripts.iter().any(|f| crate::cmd::links::script_hidden(f, doc_path)) {
return Err(bad(cmd, SCRIPT_OUTSIDE));
Err(bad(cmd, SCRIPT_OUTSIDE))
}
/// Does a file of a document with `artboards` artboards, written in format `format` with options
/// `p`, name the JavaScript files the document links? SVG, SVGZ, native files, native templates and
/// EPS files always do. A `.ai` or `.ait` file does unless it is a legacy version 7 `.ai` file or `p`
/// picks only some of the artboards; a PDF does with Preserve Editing on (as its preset, standard and
/// options leave it) unless `p` picks only some of the artboards. Neither a `.ai` file nor a PDF
/// does when `useArtboards` is false in `p` (one page, the bounds of the art). Options the encoder
/// refuses count as naming them.
pub(crate) fn names_linked_scripts(cmd: &str, format: &str, p: &Value, artboards: usize) -> bool {
use serde::Deserialize;
let every_artboard = || {
let pick = if p.is_object() { super::ArtboardPick::deserialize(p).ok() } else { Some(super::ArtboardPick::default()) };
pick.and_then(|pick| pick.resolve(artboards).ok()).is_none_or(|v| v.is_none_or(|v| v.iter().copied().eq(0..artboards)))
};
let art_page = || super::encode::use_artboards(cmd, p).is_ok_and(|u| u == Some(false));
match format {
"svg" | "svgz" | "vectorcraft" | "template" | "eps" => true,
"ai" | "ait" => {
let legacy = super::format(format).is_some_and(|f| super::legacy_ai::wanted(cmd, f, p).unwrap_or(false));
!legacy && !(format == "ai" && art_page()) && every_artboard()
}
"pdf" => {
let editing = super::pdf::settings(cmd, p).ok().is_none_or(|s| s.preserve_editing);
editing && !art_page() && every_artboard()
}
_ => false,
}
Ok(())
}
/// The error for an SVG that would name a linked image's file outside the read roots.
File diff suppressed because one or more lines are too long
+4 -3
View File
@@ -53,10 +53,10 @@ pub(super) fn export_reads(f: &Format, legacy: bool, key: &str) -> bool {
pub(super) fn serialize(s: &mut Session, p: &Value) -> Result<Value> {
let f = writable("document.serialize", Some(text_param(p, "format", "document.serialize")?.unwrap_or("vectorcraft")), None)?;
check_linked_scripts("document.serialize", f.id, s.doc()?)?;
let unused = unused_option_notes("document.serialize", f, p);
let expanded = expand_presets(s, "document.serialize", p)?;
let p = with_black_output(s, &expanded);
check_linked_scripts("document.serialize", f.id, s.doc()?, &p)?;
let (doc, display_doc_title) = source(s, f, &p, "document.serialize")?;
let doc = &*doc;
let mut q = p.clone();
@@ -97,10 +97,10 @@ pub(super) fn export(s: &mut Session, p: &Value) -> Result<Value> {
super::check_not_lossy_overwrite(s.doc()?, path, p, "document.export")?;
}
let f = writable("document.export", text_param(p, "format", "document.export")?, path)?;
check_linked_scripts("document.export", f.id, s.doc()?)?;
let unused = unused_option_notes("document.export", f, p);
let expanded = expand_presets(s, "document.export", p)?;
let p = with_black_output(s, &expanded);
check_linked_scripts("document.export", f.id, s.doc()?, &p)?;
let (doc, display_doc_title) = source(s, f, &p, "document.export")?;
let doc = &*doc;
let mut q = p.clone();
@@ -375,10 +375,11 @@ pub(super) fn export_selection(s: &mut Session, p: &Value) -> Result<Value> {
super::check_not_lossy_overwrite(s.doc()?, path, p, C)?;
}
let f = writable(C, text_param(p, "format", C)?, path)?;
check_linked_scripts(C, f.id, s.doc()?)?;
let unused = unused_option_notes(C, f, p);
let expanded = expand_presets(s, C, p)?;
let p = with_black_output(s, &expanded);
// The selection is written on one artboard of its own: every artboard, whatever `p` picks.
check_linked_scripts(C, f.id, s.doc()?, &without_artboards(&p))?;
let (d, bounds) = selection(s, C, f.id == "txt")?;
// The selected objects' links are looked for from the document they are in.
check_images_in(C, f.id, &d, crate::cmd::links::LinkBase::of(s.doc()?), &without_artboards(&p))?;
File diff suppressed because one or more lines are too long
+10 -3
View File
@@ -889,7 +889,6 @@ pub(crate) fn job_for(s: &Session, st: &DocState, plan: SavePlan) -> Result<Save
fn job_for_stamped(s: &Session, st: &DocState, plan: SavePlan, stamped: Option<i64>) -> Result<SaveJob> {
let cmd = plan.mode.command();
super::check_linked_scripts(cmd, plan.format.id, st)?;
let mut own = doc_to_save(st, plan.format);
let mut params = plan.options.clone();
if is_svg(plan.format) {
@@ -934,6 +933,14 @@ fn job_for_stamped(s: &Session, st: &DocState, plan: SavePlan, stamped: Option<i
o.insert("range".into(), json!("all"));
}
}
// A saved `.ai` or `.ait` file has the artboards as its pages, whatever `useArtboards` says.
let checked = match (&params, plan.format.id) {
(Value::Object(o), "ai" | "ait") => {
std::borrow::Cow::Owned(Value::Object(o.iter().filter(|(k, _)| *k != "useArtboards").map(|(k, v)| (k.clone(), v.clone())).collect()))
}
_ => std::borrow::Cow::Borrowed(&params),
};
super::check_linked_scripts(cmd, plan.format.id, st, &checked)?;
Ok(SaveJob { plan, doc, params, snapshot, source: st.doc.clone(), stamped, boards })
}
@@ -1318,7 +1325,7 @@ pub(super) fn specs() -> Vec<CommandSpec> {
"Save Document",
[],
None,
"{path?, format?: vectorcraft|template|pdf|svg|svgz|ai|eps (default: the path's extension, else the document's own format), options?: {…the format's options, see file.formatOptions; default: as last saved}, svg?: {…SVG options} (an SVG save keeps hidden layers, display:none, unless hiddenLayers is false), …the SVG and PDF options given flat instead (an option given flat or in svg and in options with different values is an error), compress?: bool (native, also in options: gzip; default: the useCompression preference; warnings name an option given flat or in options that the file doesn't read: a legacy .ai reads only its own options, and other .ai files don't read outlineText, hiddenObjects, transparentImages or preserveEditing), version?: 4 (3, 2 or 1: for older VectorCraft versions; 1 and 2 are never compressed), preview?: false (embed a PNG of the first artboard, at most 256 px), precision?: 0..9 (native: round path anchors and handles to this many decimal places, a smaller file; colors, transforms and type stay exact; default: exact, and a later save without it writes exactly again), separateArtboards?: false (native and .ai: also save each artboard of `range` to <name>-<artboard>.<ext> beside the file, holding that artboard and the art touching it; the result's files lists every file written), range?: \"1-3, 5\"|\"all\" (default; with separateArtboards), includeLinked?: false (keep linked files' own pixels, not just their previews; they stay linked), embedProfiles?: true (carry the ICC profiles loaded from files that the document is tagged with; opening the file installs them where missing), pdfCompatible?: true (native: also carry a PDF of every artboard; false omits it) | true for .ai (false: blank pages, only the native document; a .ai file's compress, default true, is its compression.compressText), modified?: Unix seconds|null (the File Info modified date, and created date when there is none, a save to a file stamps; default now, recorded in the journal so a replay matches; null: leave the dates)} → {path, format, bytes, warnings, files?: [path…] (the file and its artboards' files), linked?: [path…] (images an SVG links to)}. Save writes one artboard, except a .ai file and EPS (below): a .ai file is a PDF-compatible file of every artboard carrying the native document (preserveEditing always on; PDF options flat or in options), which document.open restores exactly, on the active artboard (the app's, else the one the document opened on; with editingData: false, the first); separateArtboards writes more files, one per artboard. EPS takes the options of document.exportEps: by default one file whose bounding box fits the visible art (the first artboard when no art shows), carrying the whole editable document; useArtboards: true (also when artboard, artboards or range names artboards; file.formatOptions then reports it true) makes the chosen artboard the page, drawn with its background color (without Use Artboards, only the first artboard's page when no art shows has its color), and with two or more chosen the file at the path is the central file of the visible art (again the first artboard when none shows) and each artboard is also written to <name>_<artboard>.eps beside it, holding that artboard; selectedOnly is refused; its PostScript appearance flattens transparency, as EPS requires. Without a path it writes the document's own file in its own format: a document opened from or saved as SVG/PDF/EPS saves as that again (warnings name what the format loses). No path known (never saved, converted from an older version, restored by Data Recovery, or another format) → {dataBase64, format, name, folder?, warnings} and the document stays modified. Under automation read roots, a reply leaves out the document's own file outside them when no path is given (files and linked then name the files by their file names), and a suggested folder outside them; an svg or svgz save (a document whose own format is SVG or SVGZ included) is refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked), or while the file would name a linked image's file outside them (images: link, preserveEditing, or an image whose pixels the document doesn't hold; a URL is not checked), also by file.saveAs and file.saveCopy. A key that no save format takes, beside the path or in options, and an unknown key inside a PDF option's object or svg, are refused. A terminal filesystem permission/read-only refusal returns READ_ONLY_LOCATION: followed by the reason; recovery-copy failures keep their original error. Non-UI callers never open a save panel",
"{path?, format?: vectorcraft|template|pdf|svg|svgz|ai|eps (default: the path's extension, else the document's own format), options?: {…the format's options, see file.formatOptions; default: as last saved}, svg?: {…SVG options} (an SVG save keeps hidden layers, display:none, unless hiddenLayers is false), …the SVG and PDF options given flat instead (an option given flat or in svg and in options with different values is an error), compress?: bool (native, also in options: gzip; default: the useCompression preference; warnings name an option given flat or in options that the file doesn't read: a legacy .ai reads only its own options, and other .ai files don't read outlineText, hiddenObjects, transparentImages or preserveEditing), version?: 4 (3, 2 or 1: for older VectorCraft versions; 1 and 2 are never compressed), preview?: false (embed a PNG of the first artboard, at most 256 px), precision?: 0..9 (native: round path anchors and handles to this many decimal places, a smaller file; colors, transforms and type stay exact; default: exact, and a later save without it writes exactly again), separateArtboards?: false (native and .ai: also save each artboard of `range` to <name>-<artboard>.<ext> beside the file, holding that artboard and the art touching it; the result's files lists every file written), range?: \"1-3, 5\"|\"all\" (default; with separateArtboards), includeLinked?: false (keep linked files' own pixels, not just their previews; they stay linked), embedProfiles?: true (carry the ICC profiles loaded from files that the document is tagged with; opening the file installs them where missing), pdfCompatible?: true (native: also carry a PDF of every artboard; false omits it) | true for .ai (false: blank pages, only the native document; a .ai file's compress, default true, is its compression.compressText), modified?: Unix seconds|null (the File Info modified date, and created date when there is none, a save to a file stamps; default now, recorded in the journal so a replay matches; null: leave the dates)} → {path, format, bytes, warnings, files?: [path…] (the file and its artboards' files), linked?: [path…] (images an SVG links to)}. Save writes one artboard, except a .ai file and EPS (below): a .ai file is a PDF-compatible file of every artboard carrying the native document (preserveEditing always on; PDF options flat or in options), which document.open restores exactly, on the active artboard (the app's, else the one the document opened on; with editingData: false, the first); separateArtboards writes more files, one per artboard. EPS takes the options of document.exportEps: by default one file whose bounding box fits the visible art (the first artboard when no art shows), carrying the whole editable document; useArtboards: true (also when artboard, artboards or range names artboards; file.formatOptions then reports it true) makes the chosen artboard the page, drawn with its background color (without Use Artboards, only the first artboard's page when no art shows has its color), and with two or more chosen the file at the path is the central file of the visible art (again the first artboard when none shows) and each artboard is also written to <name>_<artboard>.eps beside it, holding that artboard; selectedOnly is refused; its PostScript appearance flattens transparency, as EPS requires. Without a path it writes the document's own file in its own format: a document opened from or saved as SVG/PDF/EPS saves as that again (warnings name what the format loses). No path known (never saved, converted from an older version, restored by Data Recovery, or another format) → {dataBase64, format, name, folder?, warnings} and the document stays modified. Under automation read roots, a reply leaves out the document's own file outside them when no path is given (files and linked then name the files by their file names), and a suggested folder outside them; an svg or svgz save (a document whose own format is SVG or SVGZ included), and a save whose file carries the native document (vectorcraft, template, eps, ai but a version 7 file, pdf of every artboard with preserveEditing on and useArtboards not false), is refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked), or while the file would name a linked image's file outside them (images: link, preserveEditing, or an image whose pixels the document doesn't hold; a URL is not checked), also by file.saveAs and file.saveCopy. A key that no save format takes, beside the path or in options, and an unknown key inside a PDF option's object or svg, are refused. A terminal filesystem permission/read-only refusal returns READ_ONLY_LOCATION: followed by the reason; recovery-copy failures keep their original error. Non-UI callers never open a save panel",
has_doc,
|s, p| save(s, SaveMode::Save, p)
),
@@ -1345,7 +1352,7 @@ pub(super) fn specs() -> Vec<CommandSpec> {
"Save as Template…",
["File"],
None,
"{…as document.save} {path? (saved with the format's extension: one naming another format is replaced, and one is added to a name without it), format?: template (default) | ait (also when format is not given and the path ends in .ait), compress?, version?, preview?, precision?} a template that opens as a new untitled document: a native template (.vctemplate), or a PDF-compatible .ait written as a .ai file is (the .ai options and the PDF options, as document.save takes them for .ai; aiVersion 7 is an error); the document is unchanged → {path, format, bytes, warnings}; no path → {dataBase64, format, name: \"<name> template.<ext>\", folder: the Templates folder (preference templatesFolder), warnings}",
"{…as document.save} {path? (saved with the format's extension: one naming another format is replaced, and one is added to a name without it), format?: template (default) | ait (also when format is not given and the path ends in .ait), compress?, version?, preview?, precision?} a template that opens as a new untitled document: a native template (.vctemplate), or a PDF-compatible .ait written as a .ai file is (the .ai options and the PDF options, as document.save takes them for .ai; aiVersion 7 is an error); the document is unchanged → {path, format, bytes, warnings}; no path → {dataBase64, format, name: \"<name> template.<ext>\", folder: the Templates folder (preference templatesFolder), warnings}. Under automation read roots, it is refused, before any file is written, while the document links a JavaScript file outside them, as document.save refuses it",
has_doc,
|s, p| save(s, SaveMode::Template, p)
),
+27 -4
View File
@@ -1089,6 +1089,29 @@ pub(crate) fn with_export_preset(s: &Session, cmd: &str, settings: &mut Map<Stri
Ok(())
}
/// Does the file of `item` that row `r` writes carry the native document, and with it the
/// JavaScript files the document links ([`super::access::names_linked_scripts`])? A PDF holds the
/// artboards it is written with: those of `single` (Export PDFs As › Single file), every artboard
/// (Full Document), else the item's artboard of its document.
fn names_scripts(item: &Item, r: &Row, single: Option<&[usize]>) -> bool {
if r.format.id != "pdf" {
return super::access::names_linked_scripts(C, r.format.id, &r.options, item.doc.artboards.len());
}
let (doc, options) = match (single, &item.every_artboard) {
(Some(boards), _) => {
let mut options = r.options.clone();
options["range"] = json!(boards.iter().map(|b| (b + 1).to_string()).collect::<Vec<_>>().join(", "));
(&item.doc, options)
}
(None, Some(all)) => (all, r.options.clone()),
(None, None) => match r.options_for(item.region, item.artboard) {
Ok(options) => (&item.doc, options),
Err(_) => return true,
},
};
super::access::names_linked_scripts(C, "pdf", &options, doc.artboards.len())
}
/// Every chosen artboard (asset, layer, selected object) in every format row, one file each (a PDF
/// holds its artboard alone), or with `fullDocument` one file per row (a PDF of every artboard,
/// else the bounds of all art). Items that share a name get `-2`, `-3`… instead of overwriting, and
@@ -1105,10 +1128,6 @@ pub(crate) fn export(s: &mut Session, p: &Value, asked: &Value) -> Result<Value>
o.one_source()?;
// `<filename>`: the document's file, as Save names it, or its title before it is saved.
let st = s.doc()?;
// Before the folder is made or any row is written.
for r in &rows {
super::check_linked_scripts(C, r.format.id, st)?;
}
let naming = Naming::of(&o, st.path.as_deref().unwrap_or(&st.doc.title))?;
let selection = o.selection_mode()?;
let selected = if selection.is_some() { selected_artwork(s)? } else { vec![] };
@@ -1125,6 +1144,10 @@ pub(crate) fn export(s: &mut Session, p: &Value, asked: &Value) -> Result<Value>
};
let crop = rows.iter().any(|r| r.format.id != "pdf");
let items = items(&doc, &o, selection, &selected, &naming.filename, crop, true)?;
// Before the folder is made or any row is written, with the artboards each file holds.
let single: Option<Vec<usize>> = items.iter().map(|i| i.artboard).collect::<Option<Vec<_>>>().filter(|a| naming.single_pdf && a.len() > 1);
let st = s.doc()?;
super::check_scripts_of(C, &st.doc, st.path.as_deref(), || rows.iter().any(|r| items.iter().any(|i| names_scripts(i, r, single.as_deref()))))?;
// The file each item writes for each SVG row, before the folder is made or any row is written.
let base = crate::cmd::links::LinkBase::of(s.doc()?);
for r in rows.iter().filter(|r| matches!(r.format.id, "svg" | "svgz")) {
+28 -2
View File
@@ -1492,7 +1492,11 @@ pub(crate) fn capture_line_changes(before: &Document, doc: &mut Document, ids: &
let Some(spec) = doc.node_mut(graph).and_then(|n| n.extras_if_any().and_then(|e| e.graph.as_deref_mut())) else { continue };
let slot = line_slot(&mut spec.label_styles, line);
let mut rows = slot.clone().unwrap_or_else(|| line.default_rows());
let was_unpainted = stroke_unpainted(&rows);
merge_row_edits(&mut rows, &old, &new);
if old.paint.stroke != new.paint.stroke {
keep_painted_stroke_weight(&mut rows, was_unpainted, &new.paint);
}
let kept = (rows != line.default_rows()).then_some(rows);
changed |= *slot != kept;
*slot = kept;
@@ -1547,9 +1551,10 @@ pub(crate) fn capture_line_row_writes(doc: &mut Document, written: &[(NodeId, us
let Some(spec) = doc.node_mut(graph).and_then(|n| n.extras_if_any().and_then(|e| e.graph.as_deref_mut())) else { continue };
let slot = line_slot(&mut spec.label_styles, line);
let mut rows = slot.clone().unwrap_or_else(|| line.default_rows());
let was_unpainted = stroke_unpainted(&rows);
let k = &mut rows.paint;
if on_fill.paint {
k.fill = shown.fill;
k.fill = shown.fill.clone();
}
if on_fill.opacity {
k.fill_opacity = shown.fill_opacity;
@@ -1558,7 +1563,7 @@ pub(crate) fn capture_line_row_writes(doc: &mut Document, written: &[(NodeId, us
k.fill_blend = shown.fill_blend;
}
if on_stroke.paint {
k.stroke = shown.stroke;
k.stroke = shown.stroke.clone();
}
if on_stroke.weight {
k.stroke_width = shown.stroke_width;
@@ -1569,6 +1574,9 @@ pub(crate) fn capture_line_row_writes(doc: &mut Document, written: &[(NodeId, us
if on_stroke.blend {
k.stroke_blend = shown.stroke_blend;
}
if on_stroke.paint {
keep_painted_stroke_weight(&mut rows, was_unpainted, &shown);
}
let kept = (rows != line.default_rows()).then_some(rows);
changed |= *slot != kept;
*slot = kept;
@@ -1576,6 +1584,24 @@ pub(crate) fn capture_line_row_writes(doc: &mut Document, written: &[(NodeId, us
changed
}
/// Give kept line rows whose stroke an edit painted the painted line's stroke weight (`shown`) when the kind kept no
/// stroke paint before the edit (`was_unpainted`) and keeps the zero weight a stroke set to None left. A non-zero kept
/// weight stays, and so do a zero weight kept with a painted stroke and a zero weight the painted line shows.
fn keep_painted_stroke_weight(rows: &mut vectorcraft_doc::LabelRows, was_unpainted: bool, shown: &vectorcraft_doc::SeriesPaint) {
if was_unpainted
&& !stroke_unpainted(rows)
&& rows.paint.stroke_width.is_some_and(|w| w <= 0.0)
&& let Some(w) = shown.stroke_width.filter(|w| *w > 0.0)
{
rows.paint.stroke_width = Some(w);
}
}
/// Do kept line rows keep no stroke paint?
fn stroke_unpainted(rows: &vectorcraft_doc::LabelRows) -> bool {
rows.paint.stroke.as_ref().is_none_or(Paint::is_none)
}
/// Is `id` a graph line: a path directly in a graph's Axes group?
pub(crate) fn is_graph_line(doc: &Document, id: NodeId) -> bool {
graph_line(doc, id).is_some()
+72
View File
@@ -7905,6 +7905,28 @@ fn recoloring_a_graph_keeps_its_axis_lines_paint() {
assert!(!label_paint.is_empty() && label_paint.iter().all(|l| *l == ("#ffffff".to_string(), true)), "{label_paint:?}");
}
/// Swap Fill and Stroke on an axis line keeps the swapped paint for every axis line and leaves the fill opacity the axis
/// lines keep from another line, though the line swapped still shows 100%.
#[test]
fn swapping_an_axis_lines_paint_keeps_the_fill_opacity_its_kind_keeps() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
let id = graph(&mut s, "column");
let lines = line_nodes(&s, id);
let (first, second) = (lines[0].id, lines[1].id);
s.execute("paint.setFill", &json!({"ids": [first.0], "color": "#00ff00"})).unwrap();
s.execute("transparency.set", &json!({"ids": [first.0], "item": top_row(&s, first, true), "opacity": 40})).unwrap();
let shown = s.doc().unwrap().doc.node(second).unwrap().appearance.fill().map(|f| f.opacity);
assert!(shown.is_none_or(|o| o == 1.0), "the other lines show 100% until the graph is drawn again: {shown:?}");
s.execute("paint.swap", &json!({"ids": [second.0]})).unwrap();
s.execute("graph.setData", &json!({"id": id.0, "csv": ",2024,2025\nQ1,3,2\nQ2,5,4\nQ3,-1,6"})).unwrap();
for n in line_nodes(&s, id) {
let fill = n.appearance.fill().map(|f| (f.paint.color().map(|c| c.to_hex()), f.opacity));
assert!(fill.as_ref().is_some_and(|(c, o)| c.as_deref() == Some("#000000") && (*o - 0.4).abs() < 1e-6), "{fill:?}");
assert!(n.appearance.stroke_paint().is_none(), "the swapped line had no fill, so the lines have no stroke");
}
}
/// A stroke given the whole graph, or its Axes group, is kept for its axis lines.
#[test]
fn a_stroke_given_the_whole_graph_or_its_axes_group_is_kept_for_its_axis_lines() {
@@ -8047,6 +8069,56 @@ fn an_object_opacity_on_an_axis_line_keeps_the_stroke_its_kind_keeps() {
}
}
/// A stroke painted on an axis line after another axis line's stroke was set to None is kept for every axis line with
/// the painted line's weight, not the zero weight the unpainted stroke left on its kind.
#[test]
fn a_stroke_painted_after_an_axis_line_lost_its_stroke_keeps_a_weight() {
let cases = ["paint.setStroke", "addon.color.fillToStroke", "appearance.setItem"];
every_case(cases, |cmd| {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
let id = graph(&mut s, "column");
let lines = line_nodes(&s, id);
let weight = line_look(&lines[1]).1;
assert!(weight > 0.0, "{cmd}: the line has a stroke weight: {weight}");
s.execute("paint.setStroke", &json!({"ids": [lines[0].id.0], "none": true})).unwrap();
let b = lines[1].id.0;
match *cmd {
"paint.setStroke" => s.execute(cmd, &json!({"ids": [b], "color": "#ff0000"})).unwrap(),
"addon.color.fillToStroke" => {
s.execute("paint.setFill", &json!({"ids": [b], "color": "#ff0000"})).unwrap();
s.execute(cmd, &json!({"ids": [b]})).unwrap()
}
_ => s.execute(cmd, &json!({"ids": [b], "index": top_row(&s, lines[1].id, false), "color": "#ff0000"})).unwrap(),
};
let looks = redrawn_line_looks(&mut s, id);
assert!(looks.iter().all(|l| l.0 == "#ff0000" && (l.1 - weight).abs() < 1e-9), "{cmd}: {looks:?}");
});
}
/// A zero stroke weight set together with a stroke color on an axis line is kept for every axis line as set, also when
/// a stroke is painted on another axis line before the graph is drawn again.
#[test]
fn a_zero_weight_set_with_a_stroke_color_on_an_axis_line_is_kept() {
every_case([false, true], |repaint| {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 800, "height": 800})).unwrap();
let id = graph(&mut s, "column");
let lines = line_nodes(&s, id);
s.execute("paint.setStroke", &json!({"ids": [lines[0].id.0], "none": true})).unwrap();
let at = top_row(&s, lines[1].id, false);
s.execute("appearance.setItem", &json!({"ids": [lines[1].id.0], "index": at, "color": "#ff0000", "weight": 0})).unwrap();
let color = if *repaint {
s.execute("paint.setStroke", &json!({"ids": [lines[2].id.0], "color": "#0000ff"})).unwrap();
"#0000ff"
} else {
"#ff0000"
};
let looks = redrawn_line_looks(&mut s, id);
assert!(looks.iter().all(|l| l.0 == color && l.1 == 0.0), "repaint {repaint}: {looks:?}");
});
}
/// A reorder that leaves an axis line's rows as they were keeps what its kind keeps from another line and is no edit.
#[test]
fn a_reorder_that_changes_nothing_on_an_axis_line_keeps_the_stroke_its_kind_keeps() {
+28 -1
View File
@@ -24,7 +24,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Package",
[],
None,
"{folder?, name?: (default: \"<document> Folder\"), copyLinks?: true, linksFolder?: true (the linked files go in Links/, else next to the document), relink?: true (the packaged document links to the copies), copyFonts?: true (the fonts its type uses go in Fonts/; fonts whose licence doesn't allow embedding are left out), report?: true (<document> Report.txt)} copy the saved document as it is now into folder/name as <document>.vectorcraft with its linked files and fonts; the open document doesn't change → {folder, files: [paths relative to folder/name], links, fonts (counts copied), missingLinks: [file names not found], skippedFonts: [{font, reason}], warnings: [nested files copied unchanged or cycles/depth stopped]}; no folder → the same with {name: \"<name>.zip\", dataBase64} (a zip of the files in <name>/) instead of folder. The warnings and the report name a file outside the automation read roots by its file name",
"{folder?, name?: (default: \"<document> Folder\"), copyLinks?: true, linksFolder?: true (the linked files go in Links/, else next to the document), relink?: true (the packaged document links to the copies), copyFonts?: true (the fonts its type uses go in Fonts/; fonts whose licence doesn't allow embedding are left out), report?: true (<document> Report.txt)} copy the saved document as it is now into folder/name as <document>.vectorcraft with its linked files and fonts; the open document doesn't change → {folder, files: [paths relative to folder/name], links, fonts (counts copied), missingLinks: [file names not found], skippedFonts: [{font, reason}], warnings: [nested files copied unchanged or cycles/depth stopped]}; no folder → the same with {name: \"<name>.zip\", dataBase64} (a zip of the files in <name>/) instead of folder. The warnings and the report name a file outside the automation read roots by its file name. Under automation read roots, the package is refused, before any file is written, while the document, or a linked native document or a linked PDF, .ai or EPS file's native document, links a JavaScript file outside them (svgInteractivity; a URL is not checked)",
has_doc,
package
)]
@@ -113,6 +113,30 @@ thread_local! {
pub(crate) static PARTS_READ: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// The native document that the linked file `name` (`bytes`) is, or carries as the editing data of
/// a PDF, `.ai` or EPS file; `None` for other files and for data that can't be read.
fn carried_document(name: &str, bytes: &[u8]) -> Option<Document> {
if super::place::document::is_native(name, bytes) {
return vectorcraft_format::load_file(bytes).ok().map(|f| f.doc);
}
let data =
if super::place::document::is_pdf(name, bytes) { vectorcraft_pdf::editing(bytes).map(|e| e.data) } else { vectorcraft_eps::native(bytes) };
vectorcraft_format::load(&data?).ok()
}
/// Under read roots, the linked file `name` (`bytes`, found at `path`) is copied only when the
/// native document it is or carries ([`carried_document`]) links no JavaScript file outside them (a
/// relative path taken from the file's folder): the copy would name it.
fn check_carried_scripts(name: &str, bytes: &[u8], path: &str) -> Result<()> {
if crate::file_access::current().is_none() {
return Ok(());
}
match carried_document(name, bytes) {
Some(carried) => super::fileio::check_scripts_of(C, &carried, Some(path), || true),
None => Ok(()),
}
}
/// The fonts of the type on `pages` of the PDF or `.ai` file `name` (`bytes`, found at `path`);
/// none for other files.
fn page_fonts(name: &str, bytes: &[u8], path: &str, pages: &PlacedPages) -> BTreeSet<super::fonts::UsedFont> {
@@ -291,6 +315,7 @@ impl<'a> Collector<'a> {
// read from its editing data links are copied beside it.
let pages = placed.get(&file.path);
let placed_file = pages.is_some();
check_carried_scripts(&file.name, &bytes, found_path)?;
if placed_file && let Some(mut art) = super::place::document::editing_data(&file.name, &bytes) {
if depth >= vectorcraft_doc::placed_document::MAX_DEPTH {
self.warn(&mut lines, format!("{shown}: nesting limit reached; copied unchanged without collecting its own links"));
@@ -471,6 +496,8 @@ fn prepare(s: &mut Session, p: &Value) -> Result<Package> {
let given_name = text_param(p, "name", C)?;
let folder = text_param(p, "folder", C)?;
let doc_path = s.doc()?.path.clone().ok_or_else(|| bad(C, "save the document first: Package collects a saved document"))?;
// Before anything is collected or written, here where the request's read roots are in force.
super::fileio::check_linked_scripts(C, "vectorcraft", s.doc()?, &Value::Null)?;
let stem = Path::new(&doc_path).file_stem().map_or_else(|| "Untitled".into(), |s| s.to_string_lossy().into_owned());
let name = given_name.map_or_else(|| format!("{stem} Folder"), str::to_string);
if name.trim().is_empty() || name == "." || name == ".." || name.contains(['/', '\\', ':', '*', '?', '"', '<', '>', '|']) {
+1 -1
View File
@@ -39,7 +39,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Swap Fill and Stroke",
[],
Some("Shift+X"),
"{ids?|id?} swap the fill and stroke of the selection (type too) and of the defaults. On a path directly in a graph series, the graph also stores the swapped paints and the stroke weight, and on a graph label the swapped paints of its characters for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (exceptions: docs/mcp.md)",
"{ids?|id?} swap the fill and stroke of the selection (type too) and of the defaults. On a path directly in a graph series, the graph also stores the swapped paints and the stroke weight, and on a graph label the swapped paints of its characters for every label of its kind, and on a graph's axis line, tick mark or radar ring what the swap changes on its rows for every line of its kind (exceptions: docs/mcp.md)",
has_doc,
swap
),
+59 -16
View File
@@ -34,7 +34,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Recolor Artwork",
["Edit", "Edit Colors"],
None,
"{map: rows [{from: [colour keys (recolor.colors) or \"#rrggbb\" (every colour shown as that hex); may be empty: an empty row recolours nothing, adds no library swatch and gives `group` no colour], to: colour (hex, key, {c,m,y,k} or {l,a,b}) | null (in from, to and groupColors, #rrggbbaa and #rgba are refused), exclude?: false (the row's colours are kept), tint?: 100 (percent; with limitTo, art linked to the global or spot swatch the new color is takes this share of its tint)}] | {\"key or #rrggbb\": colour, …} (one row per colour), method?: \"exact\" (default)|\"preserveTints\"|\"scaleTints\"|\"tintsShades\"|\"hueShift\" (how a row's colours take its new colour, relative to the row's darkest, average or most saturated colour), limitTo?: swatch library id or name; or \"document\" (the document's swatches): new colours snap to its nearest colour, group?: colour group to rewrite, groupColors?: [colour] (what `group` is rewritten with; default: the rows' new colours, in order, excluded and empty rows left out), rename?: the group's new name, includeImages?: true, includePatterns?: true, globalAdjust?: {saturation?: 0, brightness?: 0, temperature?: 0, luminosity?: 0} (Global Adjust: percent from -100 to 100, 0 changes nothing; every colour a row that isn't excluded recolours, and the group's new colours, take the same change after the row's new colour: saturation scales HSB saturation by 1 + saturation/100, brightness moves HSB brightness that share of the way to full or to black, temperature adds 0.2 × temperature/100 to red and takes it from blue, luminosity moves Lab lightness that share of the way to 100 or 0 keeping a and b; with limitTo each row's new colour takes the change before it snaps to the library)} recolour the selection (gradients, text, meshes, image pixels and pattern tiles included; each new colour keeps the model of the one it replaces (model?: \"keep\" default | \"new\" (the new colour's own model, so a CMYK colour replacing RGB art gives CMYK art) | \"document\" (the document's colour mode)), except a library swatch's with limitTo: art takes the swatch itself, linked to a global or spot colour at its tints, and the swatch joins the document's swatches; art linked to a global swatch of `group` that is rewritten with its row's new color stays linked to it, at its tint, unless the row converts the color into the art's model; other recolored art, and art in a row linked to a global swatch of `group` that is rewritten with another color, keeps its row's new color and loses its swatch link) and the group, as one undo step (none when nothing changes). On a path directly in a graph series, the graph also stores the new paint of the topmost visible fill and stroke, and on a graph label the new paint of its characters and rows for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md) → {changed, swatches: [names added to the document's swatches], relinked?: with group, the other paints linked to its global swatches that took their new colors, note?: set when a colour kept a model other than its new colour's (see model), notChanged: {locked, hidden} (as edit.colors.invert), warning?: set when notChanged counts any object}",
"{map: rows [{from: [colour keys (recolor.colors) or \"#rrggbb\" (every colour shown as that hex); may be empty: an empty row recolours nothing, adds no library swatch and gives `group` no colour unless `added`], to: colour (hex, key, {c,m,y,k} or {l,a,b}) | null (in from, to and groupColors, #rrggbbaa and #rgba are refused), exclude?: false (the row's colours are kept), tint?: 100 (percent; with limitTo, art linked to the global or spot swatch the new color is takes this share of its tint), added?: false (an empty row's new color is a color added to `group`)}] | {\"key or #rrggbb\": colour, …} (one row per colour), method?: \"exact\" (default)|\"preserveTints\"|\"scaleTints\"|\"tintsShades\"|\"hueShift\" (how a row's colours take its new colour, relative to the row's darkest, average or most saturated colour), limitTo?: swatch library id or name; or \"document\" (the document's swatches): new colours snap to its nearest colour, group?: colour group to rewrite, groupColors?: [colour | null] (what `group` is rewritten with, a null removing the group's swatch at its place; default: the new colors of the rows with current colors, in order, then those of the empty rows with `added`, excluded rows left out), rename?: the group's new name, includeImages?: true, includePatterns?: true, globalAdjust?: {saturation?: 0, brightness?: 0, temperature?: 0, luminosity?: 0} (Global Adjust: percent from -100 to 100, 0 changes nothing; every colour a row that isn't excluded recolours, and the group's new colours, take the same change after the row's new colour: saturation scales HSB saturation by 1 + saturation/100, brightness moves HSB brightness that share of the way to full or to black, temperature adds 0.2 × temperature/100 to red and takes it from blue, luminosity moves Lab lightness that share of the way to 100 or 0 keeping a and b; with limitTo each row's new colour takes the change before it snaps to the library)} recolour the selection (gradients, text, meshes, image pixels and pattern tiles included; each new colour keeps the model of the one it replaces (model?: \"keep\" default | \"new\" (the new colour's own model, so a CMYK colour replacing RGB art gives CMYK art) | \"document\" (the document's colour mode)), except a library swatch's with limitTo: art takes the swatch itself, linked to a global or spot colour at its tints, and the swatch joins the document's swatches; art linked to a global swatch of `group` that is rewritten with its row's new color stays linked to it, at its tint, unless the row converts the color into the art's model; other recolored art, and art in a row linked to a global swatch of `group` that is rewritten with another color, keeps its row's new color and loses its swatch link) and the group, as one undo step (none when nothing changes). On a path directly in a graph series, the graph also stores the new paint of the topmost visible fill and stroke, and on a graph label the new paint of its characters and rows for every label of its kind, and on a graph's axis line, tick mark or radar ring its rows for every line of its kind (docs/mcp.md) → {changed, swatches: [names added to the document's swatches], relinked?: with group, the other paints linked to its global swatches that took their new colors, note?: set when a colour kept a model other than its new colour's (see model), notChanged: {locked, hidden} (as edit.colors.invert), warning?: set when notChanged counts any object}",
has_doc,
apply
),
@@ -1384,6 +1384,9 @@ struct Row {
tint: f32,
/// The row's own `model`, which takes the place of the command's for its colors.
model: Option<ModelRule>,
/// `added`: with no current colors, the new color is a color added to the group, which it
/// joins after the colors of the rows with current colors.
added: bool,
}
/// The color model a row's colors take (`model`): each color's own, the new color's, or the
@@ -1437,9 +1440,10 @@ fn parse_rows(p: &Value, cmd: &str) -> Result<Vec<Row>> {
};
let cur = |v: &Value| Match::of(v).ok_or_else(|| bad(cmd, format!("bad current colour {v}")));
match p.get("map") {
Some(Value::Object(m)) => {
m.iter().map(|(k, v)| Ok(Row { from: vec![cur(&json!(k))?], to: new(Some(v))?, exclude: false, tint: 1.0, model: None })).collect()
}
Some(Value::Object(m)) => m
.iter()
.map(|(k, v)| Ok(Row { from: vec![cur(&json!(k))?], to: new(Some(v))?, exclude: false, tint: 1.0, model: None, added: false }))
.collect(),
Some(Value::Array(rows)) => rows
.iter()
.map(|r| {
@@ -1450,7 +1454,8 @@ fn parse_rows(p: &Value, cmd: &str) -> Result<Vec<Row>> {
};
let tint = (super::number_or(r, "tint", 100.0, cmd)? / 100.0).clamp(0.0, 1.0) as f32;
let model = ModelRule::param(r, cmd)?;
Ok(Row { from, to: new(r.get("to"))?, exclude: switch_or(r, "exclude", false, cmd)?, tint, model })
let added = switch_or(r, "added", false, cmd)?;
Ok(Row { from, to: new(r.get("to"))?, exclude: switch_or(r, "exclude", false, cmd)?, tint, model, added })
})
.collect(),
_ => Err(bad(cmd, "missing `map` (rows [{from, to}] or {current: new})")),
@@ -1487,6 +1492,10 @@ struct ColorMap {
group: Vec<GroupSwatch>,
keys: HashMap<ColorKey, usize>,
hexes: HashMap<String, usize>,
/// The current colors of the rows whose new color was removed (`to: null`, not excluded),
/// which keep their colors.
removed_keys: std::collections::HashSet<ColorKey>,
removed_hexes: std::collections::HashSet<String>,
/// Set when a colour took a new colour of another model in its own model.
converted: std::cell::Cell<bool>,
/// The Global Adjust every mapped colour takes after its row's new colour.
@@ -1505,11 +1514,23 @@ impl ColorMap {
group,
keys: HashMap::new(),
hexes: HashMap::new(),
removed_keys: Default::default(),
removed_hexes: Default::default(),
converted: Default::default(),
adjust,
};
for (n, r) in rows.iter().enumerate().filter(|(_, r)| !r.from.is_empty()) {
let Some(to) = r.new_color() else { continue };
let Some(to) = r.new_color() else {
if !r.exclude {
for m in &r.from {
match m {
Match::Key(k) => out.removed_keys.insert(*k),
Match::Hex(h) => out.removed_hexes.insert(h.clone()),
};
}
}
continue;
};
let i = out.rows.len();
let colors: Vec<Color> = r.from.iter().map(Match::color).collect();
let link = links.get(n).cloned().flatten();
@@ -1550,9 +1571,18 @@ impl ColorMap {
/// the row gives it the new color in that color's model and the Global Adjust gives it the
/// swatch's new color at that tint;
/// other rows map the colour, which loses its link when it changes or when the group's rewrite
/// would change it. True when anything changed.
/// would change it; a color of a row whose new color was removed keeps its color and loses its
/// link to a swatch of the group whose rewrite would change it. True when anything changed.
fn map_link(&self, c: &mut Color, link: &mut Option<String>, tint: &mut f32) -> bool {
let Some(i) = self.row_of(*c) else { return false };
let Some(i) = self.row_of(*c) else {
let removed = self.removed_keys.contains(&ColorKey::of(c)) || self.removed_hexes.contains(&c.to_hex());
let rewritten = link.as_deref().and_then(|n| self.group.iter().find(|g| g.name == n)).is_some_and(|g| g.shown.tinted(*tint) != *c);
if removed && rewritten {
*link = None;
return true;
}
return false;
};
let (Some(row), Some(l)) = (self.rows.get(i), self.links.get(i)) else { return false };
if l.is_none()
&& let Some(g) = link.as_deref().and_then(|n| self.group.iter().find(|g| g.name == n))
@@ -1650,18 +1680,27 @@ fn apply(s: &mut Session, p: &Value) -> Result<Value> {
Some(Value::Array(cs)) => Some(cs),
Some(_) => return Err(bad(C, "`groupColors` must be an array")),
};
let new: Vec<Color> = match group_colors {
// A null in groupColors removes the group's swatch at its place.
let new: Vec<Option<Color>> = match group_colors {
Some(cs) => cs
.iter()
.map(|v| {
color_value(v)
.map(|v| match v {
Value::Null => Ok(None),
v => color_value(v)
.map(|c| adjust.apply(c))
.map(|c| in_doc_model(palette.as_ref().map_or(c, |pl| pl.nearest(c))))
.ok_or_else(|| bad(C, format!("bad colour {v} in groupColors")))
.map(|c| Some(in_doc_model(palette.as_ref().map_or(c, |pl| pl.nearest(c)))))
.ok_or_else(|| bad(C, format!("bad colour {v} in groupColors"))),
})
.collect::<Result<_>>()?,
// A row with no current colors gives the group no color.
None => rows.iter().filter(|r| !r.from.is_empty()).filter_map(Row::new_color).map(|c| mapped_adjust.apply(c)).collect(),
// A row with no current colors gives the group no color, unless it is a color added to
// the group: those follow the colors of the rows with current colors.
None => rows
.iter()
.filter(|r| !r.from.is_empty())
.chain(rows.iter().filter(|r| r.from.is_empty() && r.added))
.filter_map(Row::new_color)
.map(|c| Some(mapped_adjust.apply(c)))
.collect(),
};
let rename = text_param(p, "rename", C)?;
let colorized_ok = super::paint::check_colorized(&s.doc()?.doc).is_ok();
@@ -1696,7 +1735,8 @@ fn apply(s: &mut Session, p: &Value) -> Result<Value> {
.iter()
.zip(&new)
.filter(|(w, _)| w.global && !w.is_reserved())
.map(|(w, c)| GroupSwatch { name: w.name.clone(), color: *c, shown: d.linked_color(*c, w.spot) })
.filter_map(|(w, c)| Some((w, (*c)?)))
.map(|(w, c)| GroupSwatch { name: w.name.clone(), color: c, shown: d.linked_color(c, w.spot) })
.collect()
})
.unwrap_or_default();
@@ -1779,6 +1819,9 @@ fn randomize(_: &mut Session, p: &Value) -> Result<Value> {
if let Some(m) = model {
row["model"] = json!(m.id());
}
if r.added {
row["added"] = json!(true);
}
row
})
.collect();
+27 -15
View File
@@ -1255,43 +1255,54 @@ impl GroupEdit {
}
/// Rewrite colour group `group` with `colors`: its swatches take them in order (keeping their
/// names, kinds and global or spot flags), extra colours are added as new swatches and swatches
/// past the end are removed. Paints linked to its global swatches follow (a removed swatch's are
/// unlinked); `rename` renames the group. A built-in swatch (None, Registration) it would change or
/// remove is refused.
pub(super) fn rewrite_group(d: &mut Document, group: &str, colors: &[Color], rename: Option<&str>, cmd: &str) -> Result<GroupEdit> {
/// names, kinds and global or spot flags), a `None` removes the swatch at its place, extra colors
/// are added as new swatches and swatches past the end are removed. Paints linked to its global
/// swatches follow (a removed swatch's are unlinked); `rename` renames the group. A built-in swatch
/// (None, Registration) it would change or remove is refused.
pub(super) fn rewrite_group(d: &mut Document, group: &str, colors: &[Option<Color>], rename: Option<&str>, cmd: &str) -> Result<GroupEdit> {
let gi = d.swatch_groups.iter().position(|g| g.name == group).ok_or_else(|| bad(cmd, format!("no colour group `{group}`")))?;
let name = match rename.map(str::trim).filter(|n| !n.is_empty() && *n != group) {
Some(n) => d.free_swatch_name(n),
None => group.to_string(),
};
let old = &d.swatch_groups[gi].swatches;
if let Some(w) = old.iter().enumerate().find(|(i, w)| w.is_reserved() && colors.get(*i).is_none_or(|c| w.paint.color() != Some(*c))).map(|x| x.1)
if let Some(w) = old
.iter()
.enumerate()
.find(|(i, w)| w.is_reserved() && colors.get(*i).copied().flatten().is_none_or(|c| w.paint.color() != Some(c)))
.map(|x| x.1)
{
return Err(bad(cmd, format!("`{}` can't be edited or removed", w.name)));
}
let colorized_ok = super::paint::check_colorized(d).is_ok();
let mut relinks = vec![];
let mut swatches = std::mem::take(&mut d.swatch_groups[gi].swatches);
for gone in swatches.split_off(colors.len().min(swatches.len())) {
if gone.global {
relinks.push(Relink { from: gone.name.clone(), to: gone.name, color: None, keep: false });
let old = std::mem::take(&mut d.swatch_groups[gi].swatches);
let old_len = old.len();
// The swatches that stay, each with its new color.
let mut kept: Vec<(Swatch, Color)> = vec![];
for (i, w) in old.into_iter().enumerate() {
match colors.get(i).copied().flatten() {
Some(c) => kept.push((w, c)),
None if w.global => relinks.push(Relink { from: w.name.clone(), to: w.name, color: None, keep: false }),
None => {}
}
}
for (w, c) in swatches.iter_mut().zip(colors) {
if w.paint.color() != Some(*c) {
let mut swatches = Vec::with_capacity(kept.len());
for (mut w, c) in kept {
if w.paint.color() != Some(c) {
// A tint swatch becomes a colour of its own.
w.paint = Paint::solid(*c);
w.paint = Paint::solid(c);
if w.global {
// Art linked to a Lab spot shows it as the Spot Colors options say.
relinks.push(Relink { from: w.name.clone(), to: w.name.clone(), color: Some(d.linked_color(*c, w.spot)), keep: true });
relinks.push(Relink { from: w.name.clone(), to: w.name.clone(), color: Some(d.linked_color(c, w.spot)), keep: true });
}
}
swatches.push(w);
}
let mut free = d.free_swatch_names();
free.insert(&name);
swatches.iter().for_each(|w| free.insert(&w.name));
for c in colors.iter().skip(swatches.len()) {
for c in colors.iter().skip(old_len).flatten() {
let nm = free.take(&color_name(*c));
swatches.push(Swatch { name: nm, paint: Paint::solid(*c), global: false, spot: false });
}
@@ -1320,6 +1331,7 @@ fn swatch_edit_group(s: &mut Session, p: &Value) -> Result<Value> {
let colors: Vec<Color> =
colors.into_iter().enumerate().map(|(i, c)| if old.get(i) == Some(&Some(c)) { c } else { super::paint::new_color(s, p, c) }).collect();
let rename = str_param(p, "rename");
let colors: Vec<Option<Color>> = colors.into_iter().map(Some).collect();
let e = s.edit("Edit Color Group", |d, _| rewrite_group(d, group, &colors, rename, C))?;
e.defaults(s)?;
Ok(json!({"name": e.name, "swatches": e.swatches, "relinked": e.relinked}))
+8 -7
View File
@@ -468,7 +468,7 @@ fn styles_symbols_and_images_of_the_same_name_are_renamed() {
assert_eq!(key(&s, img2), src_key);
}
/// A graph whose series fill, value labels and legend rows paint with global swatch "Brand" and
/// A graph whose series fill, value labels, legend rows and axis and ring line rows paint with global swatch "Brand" and
/// whose value labels are set in character style "Emphasis" and paragraph style "Body", as a
/// later redraw would give them to its marks and labels.
fn styled_graph(s: &mut Session) -> NodeId {
@@ -484,8 +484,9 @@ fn styled_graph(s: &mut Session) -> NodeId {
let l = &mut g.label_styles;
l.values = Some(vectorcraft_doc::CharStyle { fill: brand.clone(), style_name: Some("Emphasis".into()), ..Default::default() });
l.values_para = Some(vectorcraft_doc::ParaStyle { style_name: Some("Body".into()), ..Default::default() });
let rows = vectorcraft_doc::SeriesPaint { stroke: Some(brand), ..Default::default() };
l.legend_rows = Some(vectorcraft_doc::graph::LabelRows { paint: rows, ..Default::default() });
let paint = vectorcraft_doc::SeriesPaint { stroke: Some(brand), ..Default::default() };
let rows = vectorcraft_doc::graph::LabelRows { paint, ..Default::default() };
(l.legend_rows, l.axis_rows, l.ring_rows) = (Some(rows.clone()), Some(rows.clone()), Some(rows));
id
}
@@ -515,7 +516,7 @@ fn a_pasted_graph_brings_and_follows_its_label_styles_and_paints() {
let d = doc(&s);
assert!(d.swatch("Brand").is_some(), "{v}");
assert!(d.char_styles.iter().any(|x| x.name == "Emphasis") && d.para_styles.iter().any(|x| x.name == "Body"), "{v}");
let brand = vec!["Brand".to_string(); 3];
let brand = vec!["Brand".to_string(); 5];
assert_eq!(graph_links(&s, ids_of(&v)[0]), (brand.clone(), Some("Emphasis".into()), Some("Body".into())));
// Into a document that gives each name something else: they come in renamed.
@@ -524,15 +525,15 @@ fn a_pasted_graph_brings_and_follows_its_label_styles_and_paints() {
s.execute("charStyle.new", &json!({"name": "Emphasis", "attrs": {"size": 8.0}})).unwrap();
s.execute("paraStyle.new", &json!({"name": "Body", "attrs": {"space_after": 2.0}})).unwrap();
let v = s.execute("edit.pasteInPlace", &json!({"swatchConflict": "add"})).unwrap();
let brand2 = vec!["Brand 2".to_string(); 3];
let brand2 = vec!["Brand 2".to_string(); 5];
assert_eq!(graph_links(&s, ids_of(&v)[0]), (brand2, Some("Emphasis 2".into()), Some("Body 2".into())), "{v}");
// Without formatting: the labels' text styles stay behind.
new_doc(&mut s);
let v = s.execute("edit.pasteWithoutFormatting", &json!({})).unwrap();
assert!(doc(&s).char_styles.is_empty() && doc(&s).para_styles.is_empty(), "{v}");
// The value labels' red characters stay behind too; the series fill and the legend rows keep Brand.
assert_eq!(graph_links(&s, ids_of(&v)[0]), (vec!["Brand".to_string(); 2], None, None));
// The value labels' red characters stay behind too; the series fill, the legend rows and the line rows keep Brand.
assert_eq!(graph_links(&s, ids_of(&v)[0]), (vec!["Brand".to_string(); 4], None, None));
}
/// Each label of graph `id` (the text of its Axes and Legend groups) with its size and its first paragraph's format.
+136
View File
@@ -341,3 +341,139 @@ fn svg_output_keeps_linked_javascript_files_a_caller_may_read() {
let text = run(&mut s, "document.serialize", json!({"format": "svg"}))["text"].as_str().unwrap().to_string();
assert!(text.contains(&format!("<script xlink:href=\"{outside}\"/>")), "{text}");
}
/// The JavaScript files that the native document a `document.serialize` reply carries links.
fn carried_scripts(r: &Value) -> Vec<String> {
let bytes = vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap();
let native = if bytes.starts_with(b"%PDF") { vectorcraft_pdf::editing(&bytes).expect("editing data").data } else { bytes };
vectorcraft_format::load(&native).unwrap().svg_scripts
}
/// A caller confined to read roots: every output that carries the native document (a native file
/// or template, a `.ai` or EPS file, a PDF with Preserve Editing, a package) of a document that
/// links a JavaScript file outside them is refused before a file or folder is written, with an
/// error that names no file or folder, and the document keeps the link.
#[test]
fn confined_native_output_refuses_a_linked_javascript_file_outside_the_read_roots() {
let away = Folder::new("native-script-away");
let home = Folder::new("native-script-home");
let script = away.file("menu.js");
let mut s = session();
let a = rect(&mut s, 10.0);
run(&mut s, "svgInteractivity.addFile", json!({"file": script}));
run(&mut s, "assets.add", json!({"ids": [a.0]}));
let own = home.file("own.vectorcraft");
run(&mut s, "file.saveAs", json!({"path": own}));
let before = std::fs::read(&own).unwrap();
rect(&mut s, 50.0);
let roots = crate::file_access::AutomationRoots::new(&[&home.0], &[&home.0]).unwrap().unwrap();
let hidden = [away.0.to_string_lossy().into_owned(), home.0.to_string_lossy().into_owned(), "menu.js".to_string()];
let refused = |s: &mut Session, cmd: &str, p: Value| {
let e = crate::file_access::confine(Some(&roots), || s.execute(cmd, &p)).expect_err(cmd);
assert!(matches!(e, EngineError::BadParams { .. }), "{cmd} {p}: {e:?}");
let e = e.to_string();
assert!(e.contains("a linked JavaScript file is outside the read roots"), "{cmd} {p}: {e}");
for h in &hidden {
assert!(!e.contains(h.as_str()), "{cmd} {p} names {h}: {e}");
}
};
let file = |name: &str| home.file(name);
let out = file("out");
refused(&mut s, "document.serialize", json!({}));
for format in ["vectorcraft", "template", "pdf", "ai", "eps"] {
refused(&mut s, "document.serialize", json!({"format": format}));
refused(&mut s, "document.export", json!({"format": format}));
refused(&mut s, "document.export", json!({"format": format, "selectedOnly": true}));
refused(&mut s, "document.exportSelection", json!({"format": format}));
}
// Every artboard picked, and Preserve Editing asked for.
refused(&mut s, "document.serialize", json!({"format": "pdf", "range": "1", "preserveEditing": true}));
refused(&mut s, "document.serialize", json!({"format": "ai", "artboards": [0], "pdfCompatible": false}));
refused(&mut s, "document.export", json!({"format": "pdf", "path": file("export.pdf")}));
refused(&mut s, "document.export", json!({"format": "ai", "path": file("export.ai")}));
refused(&mut s, "document.export", json!({"format": "eps", "path": file("export.eps")}));
refused(&mut s, "document.export", json!({"format": "vectorcraft", "path": file("export.vectorcraft")}));
refused(&mut s, "document.exportPdf", json!({}));
refused(&mut s, "document.exportPdf", json!({"path": file("direct.pdf")}));
refused(&mut s, "document.exportEps", json!({"path": file("direct.eps")}));
refused(&mut s, "document.save", json!({}));
refused(&mut s, "document.save", json!({"path": file("save.pdf")}));
refused(&mut s, "file.saveAs", json!({"path": file("save-as.ai")}));
// A saved `.ai` file has the artboards as its pages, whatever `useArtboards` says.
refused(&mut s, "file.saveAs", json!({"path": file("save-as-art.ai"), "useArtboards": false}));
refused(&mut s, "file.saveAs", json!({"path": file("save-as.eps")}));
refused(&mut s, "file.saveCopy", json!({"path": file("copy.vectorcraft")}));
refused(&mut s, "file.saveAsTemplate", json!({}));
refused(&mut s, "file.saveAsTemplate", json!({"format": "ait"}));
refused(&mut s, "document.exportForScreens", json!({"folder": out, "formats": [{"format": "png"}, {"format": "vectorcraft"}]}));
refused(&mut s, "document.exportForScreens", json!({"zip": true, "formats": [{"format": "pdf", "preserveEditing": true}]}));
refused(&mut s, "assets.export", json!({"folder": out, "formats": [{"format": "ai"}]}));
refused(&mut s, "assets.export", json!({"folder": out, "formats": [{"format": "eps"}]}));
refused(&mut s, "file.package", json!({"folder": out}));
refused(&mut s, "file.package", json!({}));
assert_eq!(std::fs::read(&own).unwrap(), before, "the document's own file is left as it was");
let written: Vec<_> = std::fs::read_dir(&home.0).unwrap().map(|e| e.unwrap().file_name()).collect();
assert_eq!(written, ["own.vectorcraft"]);
assert_eq!(s.doc().unwrap().doc.svg_scripts, [script]);
}
/// A confined caller still writes the outputs that carry no native document (a PDF without
/// Preserve Editing, a PDF or `.ai` file of the art's bounds or of some artboards, a legacy `.ai`
/// file, an image), and
/// native outputs that link only JavaScript files it may read keep them as stored. A caller without
/// roots writes a file outside them too.
#[test]
fn confined_output_without_the_document_or_with_scripts_the_caller_may_read_is_written() {
let away = Folder::new("native-script-kept-away");
let home = Folder::new("native-script-kept-home");
let outside = away.file("menu.js");
let mut s = session();
rect(&mut s, 10.0);
run(&mut s, "artboard.new", json!({"x": 200, "y": 0, "width": 100, "height": 100}));
run(&mut s, "svgInteractivity.addFile", json!({"file": outside}));
let roots = crate::file_access::AutomationRoots::new(&[&home.0], &[&home.0]).unwrap().unwrap();
let written = |s: &mut Session, cmd: &str, p: Value| {
crate::file_access::confine(Some(&roots), || s.execute(cmd, &p)).unwrap_or_else(|e| panic!("{cmd} {p}: {e}"))
};
for p in [
json!({"format": "pdf", "preserveEditing": false}),
json!({"format": "pdf", "useArtboards": false}),
json!({"format": "pdf", "range": "2"}),
json!({"format": "ai", "artboards": [1]}),
json!({"format": "ai", "useArtboards": false}),
json!({"format": "ai", "aiVersion": "7"}),
json!({"format": "png"}),
] {
written(&mut s, "document.serialize", p);
}
written(&mut s, "document.exportPdf", json!({"preserveEditing": false}));
written(&mut s, "document.exportForScreens", json!({"zip": true, "formats": [{"format": "pdf"}]}));
// A PDF of each artboard leaves the editing data out: it holds one of the two.
written(&mut s, "document.exportForScreens", json!({"zip": true, "formats": [{"format": "pdf", "preserveEditing": true}]}));
let refused = |s: &mut Session, p: Value| {
let e = crate::file_access::confine(Some(&roots), || s.execute("document.exportForScreens", &p)).expect_err("refused").to_string();
assert!(e.contains("a linked JavaScript file is outside the read roots"), "{p}: {e}");
};
// One PDF of both artboards, and Full Document's PDF of every artboard, carry it.
refused(&mut s, json!({"zip": true, "pdfs": "single", "formats": [{"format": "pdf", "preserveEditing": true}]}));
refused(&mut s, json!({"zip": true, "fullDocument": true, "formats": [{"format": "pdf", "preserveEditing": true}]}));
// Without roots, the native document keeps a file outside them.
let r = run(&mut s, "document.serialize", json!({}));
assert_eq!(carried_scripts(&r), [outside.as_str()]);
// Files the caller may read: inside the read roots, relative to the document's folder, a URL.
let inside = home.file("menu.js");
let url = "https://example.com/scripts/menu.js";
let kept = [inside.as_str(), "lib/tools.js", url];
let mut s = session();
rect(&mut s, 10.0);
for file in kept {
run(&mut s, "svgInteractivity.addFile", json!({"file": file}));
}
run(&mut s, "file.saveAs", json!({"path": home.file("doc.vectorcraft")}));
for format in ["vectorcraft", "pdf"] {
let r = written(&mut s, "document.serialize", json!({"format": format}));
assert_eq!(carried_scripts(&r), kept, "{format}");
}
written(&mut s, "document.exportPdf", json!({"path": home.file("doc.pdf")}));
written(&mut s, "file.package", json!({}));
}
+24
View File
@@ -278,6 +278,30 @@ fn each_copys_shadow_expands_as_the_canvas_draws_it() {
assert_eq!(diff, 0, "{diff} pixels differ");
}
/// Each copy of a fill's own Transform effect, and each copy of its object's Transform effect,
/// draws the fill's drop shadow under itself, scaled with it, and Expand Appearance keeps those
/// shadows: the copy (10..50 across, 90..130 down) has its own shadow 40 pt to its right.
#[test]
fn each_copys_fill_shadow_expands_as_the_canvas_draws_it() {
let shadow = json!({"x": 20, "y": 0, "blur": 0, "opacity": 100, "mode": "normal", "color": "#00ff00"});
let copies = json!({"scaleH": 200, "scaleV": 200, "moveV": 80, "copies": 1});
for own in [true, false] {
let mut s = session();
run(&mut s, "shape.rectangle", json!({"x": 20, "y": 20, "width": 20, "height": 20}));
run(&mut s, "paint.setFill", json!({"color": "#ff0000"}));
run(&mut s, "paint.setStroke", json!({"none": true}));
run(&mut s, "effect.apply", json!({"effect": "stylize.dropShadow", "params": shadow, "item": 0}));
let item = if own { json!(0) } else { json!(null) };
run(&mut s, "effect.apply", json!({"effect": "distort.transform", "params": copies, "item": item}));
let before = render(&s);
assert_eq!(before.pixel(80, 110), [0, 255, 0, 255], "own {own}: the copy's shadow");
run(&mut s, "effect.expandAppearance", json!({}));
let after = render(&s);
let diff = differing(&before, &after, 64);
assert_eq!(diff, 0, "own {own}: {diff} pixels differ");
}
}
/// Each copy of type's Transform effect draws the drop shadow listed before the effect under
/// itself, scaled with it, and Expand Appearance keeps those shadows: the type's copy, scaled 200 %
/// and moved 80 pt down, has its shadow 40 pt to the right of its letters rather than the type's
+54
View File
@@ -351,6 +351,60 @@ fn a_confined_package_names_files_outside_the_read_root_by_name() {
assert!(info.to_string().contains(&dir.file("art/red.png")), "the person's: {info}");
}
/// A confined request packages no document that links, or places a native document or a PDF with
/// Preserve Editing that links, a JavaScript file outside its read roots: the package is refused
/// before anything is written, with an error that names no file or folder. A JavaScript file inside
/// them is packaged, and so is one outside them when the person packages.
#[test]
fn a_confined_package_refuses_a_linked_javascript_file_outside_the_read_root() {
let away = Folder::new("package-script-away");
let home = Folder::new("package-script-home");
let script = away.file("menu.js");
let roots = crate::file_access::AutomationRoots::new(&[&home.0], &[&home.0]).unwrap().unwrap();
let hidden = [away.0.to_string_lossy().into_owned(), home.0.to_string_lossy().into_owned(), "menu.js".to_string()];
let refused = |s: &mut Session, p: Value| {
let e = crate::file_access::confine(Some(&roots), || s.execute("file.package", &p)).expect_err("refused");
assert!(matches!(e, EngineError::BadParams { .. }), "{p}: {e:?}");
let e = e.to_string();
assert!(e.contains("a linked JavaScript file is outside the read roots"), "{p}: {e}");
for h in &hidden {
assert!(!e.contains(h.as_str()), "{p} names {h}: {e}");
}
};
let mut part = session();
run(&mut part, "shape.rectangle", json!({"x": 10, "y": 10, "width": 30, "height": 30}));
run(&mut part, "svgInteractivity.addFile", json!({"file": script}));
std::fs::create_dir_all(home.0.join("art")).unwrap();
let native = home.file("art/part.vectorcraft");
save(&mut part, &native);
let r = run(&mut part, "document.serialize", json!({"format": "pdf"}));
let pdf = home.file("art/part.pdf");
write(&pdf, &vectorcraft_format::base64_decode(r["dataBase64"].as_str().unwrap()).unwrap());
let out = home.file("out");
refused(&mut part, json!({"folder": out}));
refused(&mut part, json!({}));
for placed in [&native, &pdf] {
let mut s = session();
let r = run(&mut s, "file.place", json!({"path": placed, "link": true}));
assert_eq!(r["linked"], true, "{r}");
save(&mut s, &home.file("poster.vectorcraft"));
refused(&mut s, json!({"folder": out}));
refused(&mut s, json!({}));
assert!(!std::path::Path::new(&out).exists(), "{placed}");
// The person's package copies it.
assert_eq!(run(&mut s, "file.package", json!({}))["links"], 1, "{placed}");
}
// A JavaScript file inside the read roots.
run(&mut part, "svgInteractivity.removeFile", json!({"file": script}));
run(&mut part, "svgInteractivity.addFile", json!({"file": home.file("menu.js")}));
save(&mut part, &native);
let mut s = session();
run(&mut s, "file.place", json!({"path": native, "link": true}));
save(&mut s, &home.file("poster.vectorcraft"));
let r = crate::file_access::confine(Some(&roots), || s.execute("file.package", &json!({"folder": out}))).unwrap();
assert_eq!(r["links"], 1, "{r}");
}
/// A missing link stored as a path relative to the document names a file inside a confined
/// request's read root: the package report and Document Info give its stored path.
#[test]
+88
View File
@@ -359,6 +359,35 @@ fn an_empty_row_adds_no_swatch_and_no_group_color() {
assert_eq!(hexes, ["#ff0000", "#0000ff"]);
}
/// An empty row with `added` (a color the Add Color tool added) recolors nothing, and without
/// `groupColors` gives a rewritten group its new color after the colors of the rows with current
/// colors; randomize keeps the flag, and an `added` that is not true or false is refused.
#[test]
fn an_added_empty_row_gives_the_group_its_color_after_the_others() {
let mut s = session();
let red = rect(&mut s, json!("#ff0000"));
let blue = rect(&mut s, json!("#0000ff"));
run(&mut s, "swatch.newGroup", json!({"name": "Pair", "colors": ["#ff0000", "#0000ff"]}));
select_all(&mut s);
let map = json!([
{"from": [], "to": "rgb 0 255 0", "added": true},
{"from": [], "to": "rgb 9 9 9"},
{"from": ["rgb 255 0 0"], "to": "rgb 255 0 0"},
{"from": ["rgb 0 0 255"], "to": "rgb 0 0 255"},
]);
let shuffled = run(&mut s, "recolor.randomize", json!({"map": map, "seed": 1}));
assert_eq!(shuffled["map"][0]["added"], json!(true), "{shuffled}");
assert_eq!(shuffled["map"][1].get("added"), None, "{shuffled}");
run(&mut s, "recolor.apply", json!({"map": map, "group": "Pair"}));
let d = &s.doc().unwrap().doc;
let g = d.swatch_groups.iter().find(|g| g.name == "Pair").unwrap();
let hexes: Vec<String> = g.swatches.iter().map(|w| w.paint.color().unwrap().to_hex()).collect();
assert_eq!(hexes, ["#ff0000", "#0000ff", "#00ff00"]);
assert_eq!((fill(&s, red).to_hex(), fill(&s, blue).to_hex()), ("#ff0000".into(), "#0000ff".into()), "no art is recolored");
let bad = json!([{"from": [], "to": "rgb 0 255 0", "added": "yes"}]);
assert!(s.execute("recolor.apply", &json!({"map": bad})).is_err());
}
#[test]
fn randomize_shuffles_new_colours_and_skips_excluded_rows() {
let mut s = session();
@@ -765,6 +794,65 @@ fn recolor_of_everything_counts_locked_art_that_only_loses_its_group_swatch_link
assert_eq!(r["notChanged"], json!({"locked": 1, "hidden": 0}), "{r}");
}
#[test]
fn a_null_in_group_colors_removes_that_swatch_and_the_ones_after_it_keep_their_places() {
let mut s = session();
run(&mut s, "swatch.newGroup", json!({"name": "Brand", "colors": ["#2878f0", "#ff0000", "#00ff00"]}));
let group = |s: &Session| -> Vec<(String, String)> {
let g = s.doc().unwrap().doc.swatch_groups.iter().find(|g| g.name == "Brand").unwrap().swatches.clone();
g.iter().map(|w| (w.name.clone(), w.paint.color().unwrap().to_hex())).collect()
};
let names: Vec<String> = group(&s).into_iter().map(|(n, _)| n).collect();
for name in &names {
run(&mut s, "swatch.edit", json!({"name": name, "global": true}));
}
let red = rect(&mut s, json!("#000000"));
let green = rect(&mut s, json!("#000000"));
run(&mut s, "paint.setFill", json!({"ids": [red.0], "swatch": names[1]}));
run(&mut s, "paint.setFill", json!({"ids": [green.0], "swatch": names[2]}));
select_all(&mut s);
// The middle swatch goes; the last keeps its name and color, and a color added after them is new.
run(&mut s, "recolor.apply", json!({"map": [], "group": "Brand", "groupColors": ["#2878f0", null, "#00ff00", "#123456"]}));
let g = group(&s);
assert_eq!(g.len(), 3, "{g:?}");
assert_eq!(g[..2], [(names[0].clone(), "#2878f0".into()), (names[2].clone(), "#00ff00".into())]);
assert_eq!(g[2].1, "#123456");
let link = |s: &Session, id: NodeId| match s.doc().unwrap().doc.node(id).unwrap().appearance.fill_paint() {
vectorcraft_color::Paint::Solid { color, swatch, .. } => (color.to_hex(), swatch),
p => panic!("{p:?}"),
};
assert_eq!(link(&s, red), ("#ff0000".into(), None), "art linked to the removed swatch keeps its color, unlinked");
assert_eq!(link(&s, green), ("#00ff00".into(), Some(names[2].clone())), "art linked to a swatch that stays keeps its link");
}
/// A row whose new color was removed keeps its art's colors: art in it linked to another swatch of
/// the group, which the rewrite gives another color, loses the link instead of following it.
#[test]
fn art_of_a_row_without_a_new_color_keeps_its_color_when_its_swatch_takes_another() {
let mut s = session();
run(&mut s, "swatch.newGroup", json!({"name": "Brand", "colors": ["#ff0000", "#0000ff", "#00ff00"]}));
let names: Vec<String> =
s.doc().unwrap().doc.swatch_groups.iter().find(|g| g.name == "Brand").unwrap().swatches.iter().map(|w| w.name.clone()).collect();
for name in &names {
run(&mut s, "swatch.edit", json!({"name": name, "global": true}));
}
let blue = rect(&mut s, json!("#000000"));
let green = rect(&mut s, json!("#000000"));
run(&mut s, "paint.setFill", json!({"ids": [blue.0], "swatch": names[1]}));
run(&mut s, "paint.setFill", json!({"ids": [green.0], "swatch": names[2]}));
select_all(&mut s);
// The rows are blue, red and green; the blue row's new color is removed, so the group's first
// swatch goes and its second takes the red row's new color.
let map = json!([{"from": ["#0000ff"], "to": null}, {"from": ["#ff0000"], "to": "#ff0000"}, {"from": ["#00ff00"], "to": "#00ff00"}]);
run(&mut s, "recolor.apply", json!({"map": map, "group": "Brand", "groupColors": [null, "#ff0000", "#00ff00"]}));
let link = |s: &Session, id: NodeId| match s.doc().unwrap().doc.node(id).unwrap().appearance.fill_paint() {
vectorcraft_color::Paint::Solid { color, swatch, .. } => (color.to_hex(), swatch),
p => panic!("{p:?}"),
};
assert_eq!(link(&s, blue), ("#0000ff".into(), None), "the art keeps its color, unlinked");
assert_eq!(link(&s, green), ("#00ff00".into(), Some(names[2].clone())), "art of another row keeps its link");
}
#[test]
fn recolor_of_everything_does_not_count_locked_art_whose_pattern_the_group_rewrite_recolors() {
let mut s = session();
+196
View File
@@ -12808,3 +12808,199 @@ fn a_clipping_objects_text_wrap_is_left_out_without_room() {
assert_eq!(carriers, if room >= 4 { vec![true] } else { vec![] }, "{room}\n{text}");
}
}
/// A clipping object written as art cut to it (one that isn't a path or compound path with points,
/// or any clipping object in art already cut to one) keeps its name, its opacity mask and its
/// visibility variable on one unpainted object, locked and hidden as it was: the reader reads the
/// name once, on that object, with the mask, and binds the variable to it. The fills and strokes the
/// clipping object paints keep its opacity mask, without its name.
#[test]
fn a_cut_clipping_object_keeps_its_name_mask_and_variables() {
use vectorcraft_doc::{TextObject, Variable, VariableKind};
// Each case, with the number of objects written for the clipping object's paint.
let cases = [
("group", 0),
("hidden", 0),
("locked", 0),
("image", 0),
("instance", 0),
("blend", 0),
("type", 1),
("unpainted path", 0),
("unpainted compound", 0),
("fill", 1),
("stroke", 1),
("fill and stroke", 2),
];
for (case, parts) in cases {
let mut doc = Document::new(200.0, 100.0);
let layer = doc.layers[0].id;
let art = square(&mut doc, Rect::new(0.0, 0.0, 10.0, 10.0), LEAF);
doc.symbols.push(Symbol { dynamic: false, name: "Leaf".into(), art: Arc::new(art) });
let rect = Rect::new(20.0, 20.0, 80.0, 80.0);
let mut cutter = match case {
"image" => image_node(&mut doc, ImageBlob::png(rgb_png()), (3, 2), Affine::new([20.0, 0.0, 0.0, 20.0, 30.0, 40.0]), None),
"instance" => instance(&mut doc, "Leaf", Affine::translate((40.0, 30.0))),
"blend" => {
let keys = vec![
Arc::new(square(&mut doc, Rect::new(20.0, 20.0, 30.0, 30.0), Color::gray(0.5))),
Arc::new(square(&mut doc, Rect::new(60.0, 20.0, 70.0, 30.0), Color::gray(0.5))),
];
let spec = vectorcraft_doc::BlendSpec { spacing: vectorcraft_doc::BlendSpacing::Distance(10.0), ..Default::default() };
Node::new(doc.alloc_id(), NodeKind::Blend { children: keys, spec: Box::new(spec) })
}
"type" => text_node(&mut doc, TextObject::point(vectorcraft_geom::Point::new(30.0, 50.0), "Clip", style(24.0, Color::BLACK))),
"unpainted path" => clipping(&mut doc, shapes::rectangle(rect)),
"unpainted compound" => {
let outer = Node::path(doc.alloc_id(), shapes::rectangle(rect), Appearance::default());
let inner = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(30.0, 30.0, 70.0, 70.0)), Appearance::default());
Node::new(doc.alloc_id(), NodeKind::Compound { children: vec![Arc::new(outer), Arc::new(inner)], rule: FillRule::EvenOdd })
}
"fill" | "stroke" | "fill and stroke" => {
let mut c = clipping(&mut doc, shapes::rectangle(rect));
let fill = if case == "stroke" { Paint::None } else { solid(Color::gray(0.5)) };
let stroke = if case == "fill" { Paint::None } else { solid(Color::rgb(0.0, 0.0, 1.0)) };
c.appearance = Appearance::basic(fill, stroke, if case == "fill" { 0.0 } else { 2.0 }).into();
c
}
_ => {
let members = vec![square(&mut doc, Rect::new(20.0, 20.0, 50.0, 60.0), Color::gray(0.5)), square(&mut doc, rect, Color::gray(0.5))];
group(&mut doc, members, false)
}
};
cutter.name = Some("Cutter".into());
cutter.visible = case != "hidden";
cutter.locked = case == "locked";
let veil = square(&mut doc, Rect::new(20.0, 20.0, 60.0, 60.0), Color::rgb(1.0, 1.0, 1.0));
cutter.extras_mut().mask = Some(Box::new(OpacityMask::new(veil, false)));
let id = cutter.id;
let member = square(&mut doc, Rect::new(30.0, 30.0, 70.0, 50.0), Color::rgb(1.0, 0.0, 0.0));
let mut top = group(&mut doc, vec![cutter, member], true);
if matches!(case, "unpainted path" | "unpainted compound" | "fill" | "stroke" | "fill and stroke") {
let frame = square(&mut doc, Rect::new(0.0, 0.0, 100.0, 100.0), Color::gray(0.9));
let frame = group(&mut doc, vec![frame], false);
top = group(&mut doc, vec![frame, top], true);
}
doc.insert(Some(layer), usize::MAX, top).unwrap();
doc.variables.variables.push(Variable { name: "show".into(), kind: VariableKind::Visibility });
doc.variables.bind(id, "show");
let out = export_ai_editing(&doc, &opts()).unwrap();
assert!(out.warnings.iter().all(|w| w != writer::BINDINGS), "{case}: {:?}", out.warnings);
let text = String::from_utf8(out.program).unwrap().replace("\r\n", "\n");
assert_eq!(text.matches("%_/XMLUID : (Cutter) ; (AI10_ArtUID) ,").count(), 1, "{case}\n{text}");
assert_eq!(text.matches("(AI9_Mask)").count(), 1 + parts, "{case}\n{text}");
let back = read_back(&doc);
let (mut cutters, mut masked) = (vec![], 0);
back.layers[0].walk(&mut |n| {
masked += usize::from(n.extras().mask.is_some());
if n.name.as_deref() == Some("Cutter") {
let unpainted = matches!(n.kind, NodeKind::Path { .. } | NodeKind::Compound { .. }) && n.appearance.items.is_empty();
cutters.push((n.id, unpainted, n.extras().mask.is_some(), n.locked, n.visible));
}
});
let [(carrier, unpainted, mask, locked, visible)] = cutters[..] else { panic!("{case}: {cutters:?}\n{text}") };
assert!(unpainted && mask, "{case}");
assert_eq!((locked, visible), (case == "locked", case != "hidden"), "{case}");
assert_eq!(masked, 1 + parts, "{case}");
assert_eq!(back.variables.objects_of("show"), vec![carrier], "{case}");
}
}
/// With too little room for the unpainted object that carries a cut clipping object's dictionary,
/// the dictionary is left out, never written on another object; with room for the object but not
/// for its opacity mask's art, only the mask is left out. The data stays readable.
#[test]
fn a_cut_clipping_objects_dictionary_is_left_out_without_room() {
let mut doc = Document::new(200.0, 100.0);
let layer = doc.layers[0].id;
let before = named(square(&mut doc, Rect::new(150.0, 10.0, 160.0, 20.0), Color::gray(0.2)), "Before");
doc.insert(Some(layer), usize::MAX, before).unwrap();
let members = vec![
square(&mut doc, Rect::new(20.0, 20.0, 50.0, 60.0), Color::gray(0.5)),
square(&mut doc, Rect::new(60.0, 30.0, 90.0, 70.0), Color::gray(0.5)),
];
let mut cutter = wrapped(named(group(&mut doc, members, false), "Cutter"), 2.0, false);
cutter.locked = true;
let veil = vec![
square(&mut doc, Rect::new(20.0, 20.0, 40.0, 40.0), Color::rgb(1.0, 1.0, 1.0)),
square(&mut doc, Rect::new(40.0, 40.0, 60.0, 60.0), Color::rgb(1.0, 1.0, 1.0)),
];
let veil = group(&mut doc, veil, false);
cutter.extras_mut().mask = Some(Box::new(OpacityMask::new(veil, false)));
let member = square(&mut doc, Rect::new(30.0, 30.0, 70.0, 50.0), Color::rgb(1.0, 0.0, 0.0));
let top = group(&mut doc, vec![cutter, member], true);
doc.insert(Some(layer), usize::MAX, top).unwrap();
let all = crate::import::objects_read(&export_ai_editing(&doc, &opts()).unwrap().program).unwrap();
let mut kept = vec![];
for room in 0..=all {
let out = export_within(&doc, &opts(), room).unwrap();
assert!(crate::import::objects_read(&out.program).unwrap() <= room);
let text = String::from_utf8_lossy(&out.program).replace("\r\n", "\n");
let (back, _) = crate::ai_alone(&out.program).unwrap();
let mut found = vec![];
back.layers[0].walk(&mut |n| {
let x = n.extras();
if !matches!(n.kind, NodeKind::Layer { .. }) && (n.name.is_some() || x.wrap.is_some() || x.mask.is_some()) {
let carrier = matches!(n.kind, NodeKind::Compound { .. }) && n.appearance.items.is_empty();
found.push((n.name.clone(), carrier, x.wrap.is_some(), x.mask.is_some(), n.locked));
}
});
let before = (Some("Before".to_string()), false, false, false, false);
let rest = match found.split_first() {
Some((b, rest)) if room > 0 => {
assert_eq!(b, &before, "{room}\n{text}");
rest
}
_ => &found[..],
};
match rest {
[] => kept.push((false, false)),
[(name, true, true, mask, true)] if name.as_deref() == Some("Cutter") => kept.push((true, *mask)),
_ => panic!("{room}: {found:?}\n{text}"),
}
}
assert_eq!(kept.last(), Some(&(true, true)));
// Once the carrier fits it stays, and once its mask fits it stays too.
let carrier = kept.iter().position(|k| k.0).unwrap();
let mask = kept.iter().position(|k| k.1).unwrap();
assert!(carrier < mask, "{kept:?}");
assert!(kept[carrier..].iter().all(|k| k.0) && kept[mask..].iter().all(|k| k.1), "{kept:?}");
}
/// A cut clipping object with an opacity mask alone gets no unpainted object when its mask's art
/// doesn't fit: an object without the dictionary it was written for would be extra art.
#[test]
fn a_cut_clipping_object_without_room_for_its_mask_gets_no_carrier() {
let mut doc = Document::new(200.0, 100.0);
let layer = doc.layers[0].id;
let members = vec![
square(&mut doc, Rect::new(20.0, 20.0, 50.0, 60.0), Color::gray(0.5)),
square(&mut doc, Rect::new(60.0, 30.0, 90.0, 70.0), Color::gray(0.5)),
];
let mut cutter = group(&mut doc, members, false);
let veil = vec![
square(&mut doc, Rect::new(20.0, 20.0, 40.0, 40.0), Color::rgb(1.0, 1.0, 1.0)),
square(&mut doc, Rect::new(40.0, 40.0, 60.0, 60.0), Color::rgb(1.0, 1.0, 1.0)),
];
let veil = group(&mut doc, veil, false);
cutter.extras_mut().mask = Some(Box::new(OpacityMask::new(veil, false)));
let top = group(&mut doc, vec![cutter], true);
doc.insert(Some(layer), usize::MAX, top).unwrap();
let all = crate::import::objects_read(&export_ai_editing(&doc, &opts()).unwrap().program).unwrap();
for room in 0..=all {
let out = export_within(&doc, &opts(), room).unwrap();
let text = String::from_utf8_lossy(&out.program).replace("\r\n", "\n");
let (back, _) = crate::ai_alone(&out.program).unwrap();
let mut carriers = vec![];
back.layers[0].walk(&mut |n| {
if matches!(n.kind, NodeKind::Compound { .. }) && n.appearance.items.is_empty() {
carriers.push(n.extras().mask.is_some());
}
});
assert!(carriers.is_empty() || carriers == [true], "{room}: {carriers:?}\n{text}");
assert_eq!(carriers.is_empty(), !text.contains("(AI9_Mask)"), "{room}\n{text}");
if room == all {
assert_eq!(carriers, [true], "{text}");
}
}
}
+39 -17
View File
@@ -1231,17 +1231,19 @@ impl<'a> Writer<'a> {
}
/// A container's members, the first one's outline cutting the others: its fills painted
/// behind them (cut to the region outside too), its strokes over them, not cut by it. Its text
/// wrap options are written once, under them all ([`Self::wrap_carrier`]), and not with its fills
/// or strokes, which may be cut or left out.
/// behind them (cut to the region outside too), its strokes over them, not cut by it. Its name,
/// variables and text wrap options are written once, under them all, with its opacity mask
/// ([`Self::object_carrier`]), and not with its fills or strokes, which may be cut or left out
/// and keep only the opacity mask they are drawn through.
fn clip_contents(&mut self, children: &[Arc<Node>]) {
let Some((first, rest)) = children.split_first() else { return };
self.wrap_carrier(first);
self.object_carrier(first);
// Nothing to clip by hides the clipped art.
let Some((outline, rule)) = vectorcraft_effects::clip_outline(first) else { return };
let mut paint = first.clip_paint();
for part in [&mut paint.fill, &mut paint.stroke].into_iter().flatten() {
part.extras_mut().wrap = None;
part.name = None;
}
let outer = self.clip.clone();
let region = self.cut(&PathData::from_bezpath(&outline), rule);
@@ -1258,26 +1260,46 @@ impl<'a> Writer<'a> {
}
}
/// The text wrap options of clipping object `first`, when it has them, on an unpainted path
/// (a compound path for several subpaths) of the outline area type wraps around
/// ([`vectorcraft_doc::text::wrap_outline`]), uncut, locked and hidden as `first` is. Nothing is
/// written for an empty outline or without room for the path ([`Self::take_objects`]).
fn wrap_carrier(&mut self, first: &Node) {
let Some(wrap) = first.extras().wrap.filter(|_| self.drawn == 0 && !self.in_look) else { return };
let outline = vectorcraft_doc::text::wrap_outline(first);
if outline.is_empty() {
/// The dictionary of clipping object `first` ([`Self::dictionary`]: its name, visibility
/// variables, text wrap options and opacity mask), when it has one, on an unpainted path (a
/// compound path for several subpaths), uncut, locked and hidden as `first` is. The path is the
/// outline area type wraps around when `first` has text wrap options
/// ([`vectorcraft_doc::text::wrap_outline`]); else, and without the options when that outline is
/// empty, `first`'s clipping outline, or the rectangle of its bounds when it has none. Nothing
/// is written without such a path, or without room for the path ([`Self::take_objects`]), or
/// when the dictionary would be empty (an opacity mask left out with nothing else in it).
fn object_carrier(&mut self, first: &Node) {
let points = |p: &PathData| p.subpaths.iter().any(|sp| !sp.anchors.is_empty());
let wrap = first.extras().wrap.filter(|_| self.drawn == 0 && !self.in_look);
let wrap_outline = wrap.map(|_| vectorcraft_doc::text::wrap_outline(first)).filter(points);
let named = first.name.as_deref().is_some_and(|s| !s.is_empty());
let bound = !self.bound_variables(first, false, false).is_empty();
if wrap_outline.is_none() && !named && !bound && first.extras().mask.is_none() {
return;
}
let wrapped = wrap_outline.is_some();
let outline = wrap_outline
.or_else(|| vectorcraft_effects::clip_outline(first).map(|(o, _)| PathData::from_bezpath(&o)).filter(points))
.or_else(|| finite_bounds(first).map(shapes::rectangle));
let Some(outline) = outline else { return };
let (start, state, gs, objects) = (self.body.len(), self.state, self.gs, self.objects);
self.state(first.locked, !first.visible);
let start = self.body.len();
self.plain_object(&outline, FillRule::NonZero, None, None, Xy::of(first).object());
if self.body.len() == start {
if self.objects == objects {
// Without the path, its lock and hidden lines are taken out too, and no dictionary follows.
self.body.truncate(start);
self.state = state;
return;
}
self.block_end = usize::MAX;
self.body.push_str("%_/ArtDictionary :\n");
self.text_wrap(wrap);
self.body.push_str("%_;\n%_\n");
let path_end = self.body.len();
// Text wrap options go only on the outline area type wraps around.
self.wrap_moved = !wrapped;
self.dictionary(first);
if self.body.len() == path_end {
self.body.truncate(start);
(self.state, self.gs, self.objects) = (state, gs, objects);
}
}
/// `path` (filled by `rule`) cut to the region the art is cut to, as a non-zero path.
+2
View File
@@ -1555,6 +1555,8 @@ fn headless_backend_methods() {
let selected = h.call("ui.tool.select", json!({"tool": tool.id})).unwrap();
assert_eq!(selected["tool"], tool.id);
}
let polygonal = groups.iter().flat_map(|group| group.as_array().unwrap()).find(|entry| entry["id"] == "polygonalLasso");
assert_eq!(polygonal.map(|entry| entry["label"].clone()), Some(json!("Polygonal Lasso Tool")));
assert!(h.call("ui.resize", json!({})).is_err());
}
+1 -1
View File
@@ -1390,7 +1390,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"file.exportAs",
"Export As…",
"",
"{format?, useArtboards?, range?} opens Export As (then the format's options); with {path, …document.export options} writes the file(s) → {path, warnings, files?}; exportSelection: true writes the selection alone, cropped to it, as document.exportSelection writes it (artboard options are not used); under automation read roots, an SVG or SVGZ is refused while the document links a JavaScript file outside them, or while the file would name a linked image's file outside them, as document.export refuses it",
"{format?, useArtboards?, range?} opens Export As (then the format's options); with {path, …document.export options} writes the file(s) → {path, warnings, files?}; exportSelection: true writes the selection alone, cropped to it, as document.exportSelection writes it (artboard options are not used); under automation read roots, an SVG or SVGZ, or a file that carries the native document, is refused while the document links a JavaScript file outside them, or while the file would name a linked image's file outside them, as document.export refuses it",
),
(
"ui.fileInfoDialog",
+3 -2
View File
@@ -96,8 +96,9 @@ pub(crate) fn visual_bounds(symbols: &SymbolBoxes, n: &Node) -> Option<Rect> {
return art.visual_bounds_with(symbols).map(|r| with_raster_reach(symbols, n, r));
}
// Copies that each carry the raster effects listed before their Transform effect reach as far
// as each copy's raster effects paint, and the raster effects after it spread them all.
if effects::outer_effects(n).len() < n.appearance.effects.len()
// as each copy's raster effects paint, and the raster effects after it spread them all,
// as do copies whose fills and strokes each carry their own raster effects.
if (effects::outer_effects(n).len() < n.appearance.effects.len() || effects::has_copied_row_raster(n))
&& let Some(art) = effects::reshape(Some(symbols.document()), n, None)
{
return cull_bounds(symbols, &art);
+39
View File
@@ -1311,6 +1311,45 @@ fn each_copy_of_a_transform_effect_draws_its_own_shadow() {
assert!(b.x1 >= 80.0 - 1e-9, "{b:?}");
}
/// Each copy of a fill's own Transform effect, and each copy of its object's Transform effect,
/// draws the fill's drop shadow under itself, scaled with it: as for the object's own shadow
/// above, the copy's green shadow is 40 pt to its right. A 4 pt stroke's own Transform effect
/// gives each copy the shadow of its stroke: the copy's right edge (38..42 across) casts it at
/// 78..82. The bounds reach as far as the copy's shadow.
#[test]
fn each_copy_of_a_fills_or_strokes_transform_draws_its_own_shadow() {
let shadow = || fx("stylize.dropShadow", json!({"x": 20, "y": 0, "blur": 0, "opacity": 100, "mode": "normal", "color": "#00ff00"}));
let copies = || fx("distort.transform", json!({"scaleH": 200, "scaleV": 200, "moveV": 60, "copies": 1}));
let square = |item: AppearanceItem| {
Node::path(NodeId(0), shapes::rectangle(Rect::new(10.0, 10.0, 30.0, 30.0)), Appearance { items: vec![item], ..Default::default() })
};
let mut red = FillLayer::new(Paint::solid(Color::rgb(1.0, 0.0, 0.0)));
red.effects = vec![shadow(), copies()];
let own = square(AppearanceItem::Fill(red.clone()));
red.effects = vec![shadow()];
let mut owner = square(AppearanceItem::Fill(red));
owner.appearance.effects = vec![copies()];
for (what, n) in [("own", own), ("object's", owner)] {
let d = doc_with(Document::new(100.0, 100.0), n);
let img = render(&d);
assert_eq!(img.pixel(20, 20), [255, 0, 0, 255], "{what}: the square");
assert_eq!(img.pixel(45, 20), [0, 255, 0, 255], "{what}: the square's shadow");
assert_eq!(img.pixel(20, 80), [255, 0, 0, 255], "{what}: the copy");
assert_eq!(img.pixel(70, 80), [0, 255, 0, 255], "{what}: the copy's shadow, 40 pt to its right");
assert_eq!(img.pixel(85, 80), [255, 255, 255, 255], "{what}: past the copy's shadow");
let n = &d.layers[0].children().unwrap()[0];
let b = crate::fx::visual_bounds(&d.symbol_boxes(), n).unwrap();
assert!(b.x1 >= 80.0 - 1e-9, "{what}: {b:?}");
}
let mut blue = StrokeLayer::new(Paint::solid(Color::rgb(0.0, 0.0, 1.0)), 4.0);
blue.effects = vec![shadow(), copies()];
let d = doc_with(Document::new(100.0, 100.0), square(AppearanceItem::Stroke(blue)));
let img = render(&d);
assert_eq!(img.pixel(50, 20), [0, 255, 0, 255], "the square's stroke shadow");
assert_eq!(img.pixel(80, 80), [0, 255, 0, 255], "the copy's stroke shadow, 40 pt to the right of its edge");
assert_eq!(img.pixel(60, 80), [255, 255, 255, 255], "inside the copy's stroke shadow");
}
/// Each copy of an image's Transform effect draws the drop shadow listed before the effect under
/// itself, scaled with it: the red image (20..50) has its green shadow 10 pt to its right, and its
/// copy scaled 50 % and moved 40 pt down (27.5..42.5 across, 67.5..82.5 down) has its own 5 pt to
+35 -5
View File
@@ -1,6 +1,7 @@
//! The shadow a 3D effect's solid casts: its faces projected along the first light onto a plane
//! behind the object (square to the view) or below it (under the object's own vertical axis, turned
//! with it), as one hard-edged vector shape.
//! with it), as one vector shape. The light's Softness gives the shape a blur radius
//! ([`ShadowPlane::blur`]); at 0 the shape stays hard-edged.
//!
//! Every face is projected whole, so the shape is the union of the projected faces: each contour is
//! turned so that its face winds the same way, and the shape is filled with the nonzero rule. The
@@ -48,20 +49,36 @@ pub struct Shadow {
/// How far the plane reaches, as a share (0.1..4): at 1 the plane is a square four times the
/// object's largest size across.
pub bounds: f64,
/// The casting light's Softness (0..1): at 0 the shadow is hard-edged, above it blurred
/// ([`ShadowPlane::blur`]).
pub softness: f64,
}
impl Default for Shadow {
fn default() -> Self {
Self { position: ShadowPosition::Behind, distance: 0.0, bounds: 1.0 }
Self { position: ShadowPosition::Behind, distance: 0.0, bounds: 1.0, softness: 0.0 }
}
}
impl Shadow {
fn sanitized(self) -> Self {
Self { distance: finite(self.distance, 0.0, 0.0, 1.0), bounds: finite(self.bounds, 1.0, 0.1, 4.0), ..self }
Self {
distance: finite(self.distance, 0.0, 0.0, 1.0),
bounds: finite(self.bounds, 1.0, 0.1, 4.0),
softness: finite(self.softness, 0.0, 0.0, 1.0),
..self
}
}
}
/// The blur radius at full Softness on a plane that touches the object, as a share of the object's
/// largest size, and what each share of Distance from Object adds to it. VectorCraft's own values.
const BLUR_NEAR: f64 = 0.05;
const BLUR_PER_DISTANCE: f64 = 0.2;
/// Most blur radius a shadow takes, in points (the Gaussian Blur effect's own limit).
pub const MAX_SHADOW_BLUR: f64 = 1000.0;
/// The rotation and projection a solid is drawn with.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct Projection {
@@ -119,6 +136,17 @@ pub struct ShadowPlane {
foot: V3,
/// Half the side of the square the plane ends at.
half: f64,
/// The blur radius of the shadow on the plane, in points ([`ShadowPlane::blur`]).
blur: f64,
}
impl ShadowPlane {
/// The radius, in points, of the blur that softens the edges of the shadow on this plane: 0 at
/// Softness 0, and with Softness a share of the object's largest size that grows with the
/// plane's distance from the object (VectorCraft's own mapping), at most [`MAX_SHADOW_BLUR`].
pub fn blur(&self) -> f64 {
self.blur
}
}
/// The faces of one object's solids, gathered to cast one shadow. The solids of one object share
@@ -254,13 +282,15 @@ impl ShadowCaster {
let level = corners().map(|v| n.dot(*v)).fold(f64::INFINITY, f64::min) - s.distance * size;
let centre = V3((lo.0 + hi.0) / 2.0, (lo.1 + hi.1) / 2.0, (lo.2 + hi.2) / 2.0);
let foot = add(centre, scale(n, level - n.dot(centre)));
Some(ShadowPlane { projection: p, light, reach, n, u, w, level, foot, half: 2.0 * s.bounds * size })
let blur = (s.softness * size * (BLUR_NEAR + BLUR_PER_DISTANCE * s.distance)).min(MAX_SHADOW_BLUR);
let blur = if blur.is_finite() { blur } else { 0.0 };
Some(ShadowPlane { projection: p, light, reach, n, u, w, level, foot, half: 2.0 * s.bounds * size, blur })
}
/// The shadow the faces in the ranges `faces` cast on `plane`, on the page, filled with the
/// nonzero rule; `None` when nothing of it falls within the plane.
pub fn path_on(&self, plane: &ShadowPlane, faces: &[Range<usize>]) -> Option<PathData> {
let &ShadowPlane { projection: p, light, reach, n, u, w, level, foot, half } = plane;
let &ShadowPlane { projection: p, light, reach, n, u, w, level, foot, half, .. } = plane;
// A corner's shadow, in the plane's axes about the foot.
let cast = |v: V3| {
let q = add(v, scale(light, -(n.dot(v) - level) / reach));
+31
View File
@@ -127,10 +127,41 @@ fn bad_settings_are_sanitized_and_an_empty_caster_casts_nothing() {
let wild = Shadow { distance: f64::NAN, bounds: f64::INFINITY, ..Shadow::default() };
assert_eq!(wild.sanitized(), Shadow { bounds: 1.0, ..Shadow::default() });
assert_eq!(Shadow { distance: -3.0, bounds: 99.0, ..Shadow::default() }.sanitized(), Shadow { bounds: 4.0, ..Shadow::default() });
assert_eq!(Shadow { softness: f64::NAN, ..Shadow::default() }.sanitized(), Shadow::default());
assert_eq!(Shadow { softness: 7.0, ..Shadow::default() }.sanitized(), Shadow { softness: 1.0, ..Shadow::default() });
assert_eq!(ShadowPosition::parse("below"), Some(ShadowPosition::Below));
assert_eq!(ShadowPosition::parse("under"), None);
}
/// Softness blurs the shadow by a radius that grows with Softness and with the plane's distance
/// from the object, and scales with the object; at 0 the shadow keeps its hard edge. The outline
/// itself does not change.
#[test]
fn softness_blurs_the_shadow_more_the_farther_the_plane_is() {
let blur = |s: f64, shadow: Shadow| {
let path = square(100.0, 100.0, s);
let mut caster = ShadowCaster::new();
caster.extrude(&path, FillRule::NonZero, Rect::new(100.0, 100.0, 100.0 + s, 100.0 + s), Extrude::default(), front()).unwrap();
let all = 0..caster.len();
let all = std::slice::from_ref(&all);
let plane = caster.shadow_plane(shadow, all).unwrap();
(plane.blur(), caster.path_on(&plane, all).unwrap())
};
let (hard, hard_path) = blur(100.0, Shadow::default());
assert_eq!(hard, 0.0);
let (half, half_path) = blur(100.0, Shadow { softness: 0.5, ..Shadow::default() });
let (full, _) = blur(100.0, Shadow { softness: 1.0, ..Shadow::default() });
let (far, _) = blur(100.0, Shadow { softness: 1.0, distance: 1.0, ..Shadow::default() });
assert!(half > 0.0 && full > half && far > full, "{half} {full} {far}");
assert_eq!(half_path, hard_path, "the outline stays");
// Twice the object, twice the blur.
let (twice, _) = blur(200.0, Shadow { softness: 1.0, ..Shadow::default() });
assert!((twice - 2.0 * full).abs() < 1e-9, "{twice} {full}");
// A huge object's blur stops at the Gaussian Blur effect's limit.
let (huge, _) = blur(1.0e7, Shadow { softness: 1.0, distance: 1.0, ..Shadow::default() });
assert_eq!(huge, MAX_SHADOW_BLUR);
}
#[test]
fn the_faces_one_shadow_is_cast_from_are_bounded() {
// An open profile of 500 points revolves into about 64,000 faces at 128 segments: five fit,
+14 -3
View File
@@ -10,6 +10,7 @@ pub mod enclosing_lasso;
pub mod extend_path;
pub mod measure_inspect;
pub mod parametric_shape;
pub mod polygonal_lasso;
pub mod shared_edge;
pub mod slide_anchor;
pub mod smart_pen;
@@ -38,13 +39,21 @@ pub const ENCLOSING_LASSO: &[ToolInfo] = &[ToolInfo { id: enclosing_lasso::ID, l
pub const BOX_3D: &[ToolInfo] = &[ToolInfo { id: box3d::ID, label: "3D Box Tool", shortcut: None, icon: "box" }];
pub const POLYGONAL_LASSO: &[ToolInfo] = &[ToolInfo { id: polygonal_lasso::ID, label: "Polygonal Lasso Tool", shortcut: None, icon: "tool-lasso" }];
/// The add-ons' tool groups, after the toolbar's own ([`crate::TOOL_GROUPS`]), each with the
/// heading the All Tools drawer lists it under (its add-on's name).
const HEADED: &[(&[ToolInfo], &str)] =
&[(PATH_TOOLS, "Path Precision Tools"), (SMART_PEN, "Smart Pen"), (ENCLOSING_LASSO, "Enclosing Lasso"), (CONTOUR, "Contour"), (BOX_3D, "3D Box")];
const HEADED: &[(&[ToolInfo], &str)] = &[
(PATH_TOOLS, "Path Precision Tools"),
(SMART_PEN, "Smart Pen"),
(ENCLOSING_LASSO, "Enclosing Lasso"),
(CONTOUR, "Contour"),
(BOX_3D, "3D Box"),
(POLYGONAL_LASSO, "Polygonal Lasso"),
];
/// The add-ons' tool groups, after the toolbar's own ([`crate::TOOL_GROUPS`]).
pub const GROUPS: &[&[ToolInfo]] = &[PATH_TOOLS, SMART_PEN, ENCLOSING_LASSO, CONTOUR, BOX_3D];
pub const GROUPS: &[&[ToolInfo]] = &[PATH_TOOLS, SMART_PEN, ENCLOSING_LASSO, CONTOUR, BOX_3D, POLYGONAL_LASSO];
/// The heading the All Tools drawer lists tool `id` under: its add-on's name.
pub fn heading(id: &str) -> Option<&'static str> {
@@ -66,6 +75,7 @@ pub fn create(id: &str) -> Option<Box<dyn Tool>> {
enclosing_lasso::ID => Box::new(enclosing_lasso::EnclosingLassoTool::default()),
contour::ID => Box::new(contour::ContourTool::default()),
box3d::ID => Box::new(box3d::Box3dTool::default()),
polygonal_lasso::ID => Box::new(polygonal_lasso::PolygonalLassoTool::default()),
_ => return None,
})
}
@@ -88,6 +98,7 @@ mod tests {
assert_eq!(heading(enclosing_lasso::ID), Some("Enclosing Lasso"));
assert_eq!(heading(contour::ID), Some("Contour"));
assert_eq!(heading(box3d::ID), Some("3D Box"));
assert_eq!(heading(polygonal_lasso::ID), Some("Polygonal Lasso"));
assert_eq!(GROUPS.len(), HEADED.len());
assert!(crate::catalog::all_tools().any(|t| t.id == extend_path::ID));
assert!(create("pen").is_none() && heading("pen").is_none());
+186
View File
@@ -0,0 +1,186 @@
//! Polygonal Lasso selects anchor points inside a straight-edged loop, as the Lasso does inside a
//! freehand one. Each click sets a vertex, and a segment from the last vertex follows the pointer.
//! A double-click, Enter or a click on the first vertex closes the loop; Backspace or Delete removes
//! the last vertex and Escape drops the loop. Shift keeps the next segment to 45° steps (from the Constrain
//! Angle). Shift held at the first click adds to the selection and Alt subtracts from it.
use vectorcraft_geom::{Point, constrain_angle_from};
use crate::meshedit::MeshEdit;
use crate::xform::lasso_select;
use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey};
pub const ID: &str = "polygonalLasso";
/// The most vertices a loop keeps; clicks past it are ignored.
pub(crate) const MAX_VERTICES: usize = 65_536;
#[derive(Default)]
pub struct PolygonalLassoTool {
vertices: Vec<Point>,
/// Where the segment from the last vertex ends: the pointer, constrained while Shift is held.
hover: Option<Point>,
/// Shift held at the first click: the loop adds to the selection.
add: bool,
/// Alt held at the first click: the loop subtracts from the selection.
sub: bool,
/// Whether the press in progress set a vertex (a dropped press takes it back).
pressed_vertex: bool,
/// The picked gradient mesh points (the tool's `meshPoints` option), as with the Lasso.
mesh: MeshEdit,
}
impl PolygonalLassoTool {
/// The next vertex for a pointer at `p`: with Shift and a vertex already set, at a 45° step
/// from the last vertex.
fn target(&self, cx: &ToolContext, p: Point, mods: Mods) -> Point {
match self.vertices.last() {
Some(&last) if mods.shift => last + constrain_angle_from(p - last, 45.0, cx.constrain_angle),
_ => p,
}
}
/// How near a vertex a click counts as a click on it.
fn reach(cx: &ToolContext) -> f64 {
cx.tol(5.0).max(cx.point_tol())
}
/// Removes the last vertex and hides the segment that followed the pointer until the pointer
/// moves again. A press in progress no longer owns a vertex, so dropping it removes nothing more.
fn take_back_vertex(&mut self) {
self.vertices.pop();
self.hover = None;
self.pressed_vertex = false;
}
fn clear(&mut self) {
self.vertices.clear();
self.hover = None;
self.pressed_vertex = false;
}
/// Closes the loop and selects inside it. A loop of fewer than three vertices selects nothing.
fn close(&mut self, cx: &ToolContext) -> Vec<Action> {
let vertices = std::mem::take(&mut self.vertices);
self.clear();
if vertices.len() < 3 {
return vec![];
}
vec![lasso_select(cx, &mut self.mesh, &vertices, self.add, self.sub)]
}
}
impl Tool for PolygonalLassoTool {
fn id(&self) -> &'static str {
ID
}
fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec<Action> {
if !ev.pos.is_finite() {
return vec![];
}
match ev.kind {
PointerKind::Move | PointerKind::Drag => {
self.hover = (!self.vertices.is_empty()).then(|| self.target(cx, ev.pos, ev.mods));
vec![]
}
PointerKind::Down => {
self.pressed_vertex = false;
let reach = Self::reach(cx);
let Some(&first) = self.vertices.first() else {
self.add = ev.mods.shift;
self.sub = ev.mods.alt;
self.vertices.push(ev.pos);
self.pressed_vertex = true;
return vec![];
};
if first.distance(ev.pos) <= reach {
// With fewer than three vertices, a click on the first one adds nothing.
return if self.vertices.len() >= 3 { self.close(cx) } else { vec![] };
}
let p = self.target(cx, ev.pos, ev.mods);
// The second click of a double-click lands on the vertex the first one set.
if self.vertices.last().is_some_and(|last| last.distance(p) > reach) && self.vertices.len() < MAX_VERTICES {
self.vertices.push(p);
self.pressed_vertex = true;
}
self.hover = Some(p);
vec![]
}
PointerKind::Up => {
self.pressed_vertex = false;
vec![]
}
PointerKind::DoubleClick => self.close(cx),
// The third click of a triple-click starts no loop of its own.
PointerKind::TripleClick => {
if self.vertices.len() == 1 {
self.clear();
}
vec![]
}
}
}
fn key(&mut self, cx: &ToolContext, key: ToolKey, _mods: Mods) -> Vec<Action> {
match key {
ToolKey::Enter => self.close(cx),
ToolKey::Escape => {
self.clear();
vec![]
}
ToolKey::Backspace | ToolKey::Delete => {
self.take_back_vertex();
vec![]
}
_ => vec![],
}
}
/// A dropped press (a second finger, a canceled touch) takes back only the vertex it set.
fn drop_press(&mut self, _cx: &ToolContext) -> Vec<Action> {
if std::mem::take(&mut self.pressed_vertex) {
self.take_back_vertex();
}
vec![]
}
fn claims_key(&self, _cx: &ToolContext, key: ToolKey) -> bool {
!self.vertices.is_empty() && matches!(key, ToolKey::Enter | ToolKey::Escape | ToolKey::Backspace | ToolKey::Delete)
}
/// A loop being drawn: Escape drops it. Keys the tool does not claim run their commands.
fn ends_on_escape(&self, _cx: &ToolContext) -> bool {
!self.vertices.is_empty()
}
fn deactivate(&mut self, _cx: &ToolContext) -> Vec<Action> {
self.clear();
vec![]
}
fn hover_ended(&mut self, _cx: &ToolContext) {
self.hover = None;
}
fn options(&self) -> serde_json::Value {
self.mesh.options()
}
fn overlays(&self, cx: &ToolContext) -> Vec<Overlay> {
let mut out = self.mesh.overlays(cx, &|id| cx.selection.contains(id));
let mut line = self.vertices.clone();
line.extend(self.hover.filter(|_| !self.vertices.is_empty()));
if line.len() >= 2 {
out.push(Overlay::Path { path: crate::xform::polygon(&line, false), color: [0x40, 0x40, 0x40], width: 1.0, dashed: true });
}
out
}
fn cursor(&self, _cx: &ToolContext, _p: Point, _m: Mods) -> Cursor {
Cursor::Lasso
}
}
#[cfg(test)]
mod tests;
@@ -0,0 +1,243 @@
use super::*;
use crate::testutil::*;
use serde_json::Value;
use vectorcraft_doc::{Appearance, Document, Node, Selection};
use vectorcraft_geom::{Rect, shapes};
fn click(tool: &mut dyn Tool, cx: &ToolContext, (x, y): (f64, f64), mods: Mods) -> Vec<Action> {
let mut acts = tool.pointer(cx, &PointerEvent::new(PointerKind::Down, x, y).with_mods(mods));
acts.extend(tool.pointer(cx, &PointerEvent::new(PointerKind::Up, x, y).with_mods(mods)));
acts
}
/// Clicks each vertex in turn with `first` held at the first click only.
fn clicks(tool: &mut dyn Tool, cx: &ToolContext, vertices: &[(f64, f64)], first: Mods) {
for (i, v) in vertices.iter().enumerate() {
let acts = click(tool, cx, *v, if i == 0 { first } else { Mods::default() });
assert!(acts.is_empty(), "a vertex click selects nothing: {acts:?}");
}
}
/// The anchors each selected path has in a `select.anchorsMany` command, and its mode.
fn selected(acts: &[Action]) -> (Vec<(u64, usize)>, String) {
let [Action::Exec(c, v)] = acts else { panic!("one selection command: {acts:?}") };
assert_eq!(c, "select.anchorsMany");
let items = v["items"].as_array().unwrap();
let ids = items.iter().map(|it| (it["id"].as_u64().unwrap(), it["anchors"].as_array().unwrap().len())).collect();
(ids, v["mode"].as_str().unwrap().to_owned())
}
/// A triangle around the rectangle's top left corner (100, 100) only.
const CORNER: &[(f64, f64)] = &[(80.0, 80.0), (140.0, 80.0), (80.0, 140.0)];
#[test]
fn a_double_click_enter_or_a_click_on_the_first_vertex_closes_the_loop() {
let (d, id) = doc_with_rect();
let (s, p) = (Selection::default(), paint());
let cx = cx(&d, &s, &p);
type Closing<'a> = &'a dyn Fn(&mut dyn Tool) -> Vec<Action>;
let closings: [Closing; 3] = [
&|t| {
let mut acts = click(t, &cx, (80.0, 141.0), Mods::default());
acts.extend(t.pointer(&cx, &PointerEvent::new(PointerKind::DoubleClick, 80.0, 141.0)));
acts
},
&|t| t.key(&cx, ToolKey::Enter, Mods::default()),
&|t| click(t, &cx, (82.0, 81.0), Mods::default()),
];
for (i, close) in closings.iter().enumerate() {
let mut tool = crate::create(ID);
assert_eq!(tool.id(), ID);
clicks(tool.as_mut(), &cx, CORNER, Mods::default());
assert!(tool.ends_on_escape(&cx) && tool.claims_key(&cx, ToolKey::Enter), "closing {i}");
assert_eq!(selected(&close(tool.as_mut())), (vec![(id.0, 1)], "set".to_owned()), "closing {i}");
assert!(!tool.ends_on_escape(&cx), "closing {i}");
}
}
#[test]
fn a_double_click_at_a_new_point_sets_that_vertex_and_closes() {
let (d, id) = doc_with_rect();
let (s, p) = (Selection::default(), paint());
let cx = cx(&d, &s, &p);
let mut tool = PolygonalLassoTool::default();
clicks(&mut tool, &cx, &CORNER[..2], Mods::default());
let mut acts = click(&mut tool, &cx, (80.0, 140.0), Mods::default());
acts.extend(click(&mut tool, &cx, (80.0, 140.0), Mods::default()));
assert!(acts.is_empty(), "{acts:?}");
assert_eq!(tool.vertices.len(), 3, "the second click of the double-click sets no vertex");
let acts = tool.pointer(&cx, &PointerEvent::new(PointerKind::DoubleClick, 80.0, 140.0));
assert_eq!(selected(&acts), (vec![(id.0, 1)], "set".to_owned()));
assert!(!tool.ends_on_escape(&cx));
}
#[test]
fn backspace_or_delete_removes_the_last_vertex() {
let (d, id) = doc_with_rect();
let (s, p) = (Selection::default(), paint());
let cx = cx(&d, &s, &p);
let mut tool = PolygonalLassoTool::default();
// (300, 300) would take in the corner at (200, 200) too.
clicks(&mut tool, &cx, &[(80.0, 80.0), (140.0, 80.0), (300.0, 300.0)], Mods::default());
assert!(tool.claims_key(&cx, ToolKey::Backspace));
assert!(tool.key(&cx, ToolKey::Backspace, Mods::default()).is_empty());
assert_eq!(tool.vertices.len(), 2);
// The preview runs along the two vertices left, not back to the removed one.
let overlays = tool.overlays(&cx);
let [Overlay::Path { path, .. }] = overlays.as_slice() else { panic!("one preview path") };
assert_eq!(path.elements().len(), 2);
clicks(&mut tool, &cx, &[(300.0, 300.0)], Mods::default());
assert!(tool.claims_key(&cx, ToolKey::Delete));
assert!(tool.key(&cx, ToolKey::Delete, Mods::default()).is_empty());
assert_eq!(tool.vertices.len(), 2);
clicks(&mut tool, &cx, &[(80.0, 140.0)], Mods::default());
assert_eq!(selected(&tool.key(&cx, ToolKey::Enter, Mods::default())), (vec![(id.0, 1)], "set".to_owned()));
assert!(!tool.claims_key(&cx, ToolKey::Delete), "with no loop open, Delete deletes");
}
#[test]
fn escape_drops_the_loop_and_leaves_the_selection() {
let (d, _) = doc_with_rect();
let (s, p) = (Selection::default(), paint());
let cx = cx(&d, &s, &p);
let mut tool = PolygonalLassoTool::default();
clicks(&mut tool, &cx, CORNER, Mods::default());
assert!(tool.claims_key(&cx, ToolKey::Escape));
assert!(tool.key(&cx, ToolKey::Escape, Mods::default()).is_empty());
assert!(!tool.ends_on_escape(&cx) && !tool.claims_key(&cx, ToolKey::Enter));
assert!(tool.overlays(&cx).is_empty());
assert!(tool.key(&cx, ToolKey::Enter, Mods::default()).is_empty());
assert!(tool.pointer(&cx, &PointerEvent::new(PointerKind::DoubleClick, 80.0, 140.0)).is_empty());
}
#[test]
fn shift_keeps_the_segment_to_45_degree_steps() {
let (d, _) = doc_with_rect();
let (s, p) = (Selection::default(), paint());
let cx = cx(&d, &s, &p);
let shift = Mods { shift: true, ..Mods::default() };
let mut tool = PolygonalLassoTool::default();
clicks(&mut tool, &cx, &[(100.0, 100.0)], Mods::default());
tool.pointer(&cx, &PointerEvent::new(PointerKind::Move, 200.0, 110.0).with_mods(shift));
let hover = tool.hover.unwrap();
assert!((hover.y - 100.0).abs() < 1e-9 && hover.x > 199.0, "{hover:?}");
assert_eq!(tool.overlays(&cx).len(), 1, "the segment follows the pointer");
click(&mut tool, &cx, (190.0, 175.0), shift);
let v = tool.vertices[1];
assert!(((v.x - 100.0) - (v.y - 100.0)).abs() < 1e-9 && v.x > 150.0, "on the 45° line: {v:?}");
tool.pointer(&cx, &PointerEvent::new(PointerKind::Move, 200.0, 110.0));
assert_eq!(tool.hover, Some(Point::new(200.0, 110.0)), "without Shift the segment goes to the pointer");
}
#[test]
fn shift_or_alt_at_the_first_click_adds_or_subtracts() {
let (d, id) = doc_with_rect();
let (s, p) = (Selection::default(), paint());
let cx = cx(&d, &s, &p);
let shift = Mods { shift: true, ..Mods::default() };
let alt = Mods { alt: true, ..Mods::default() };
for (first, mode) in [(shift, "add"), (alt, "subtract"), (Mods::default(), "set")] {
let mut tool = PolygonalLassoTool::default();
clicks(&mut tool, &cx, CORNER, first);
assert_eq!(selected(&tool.key(&cx, ToolKey::Enter, Mods::default())), (vec![(id.0, 1)], mode.to_owned()));
}
// Shift held only at a later click constrains that segment and does not add.
let mut tool = PolygonalLassoTool::default();
clicks(&mut tool, &cx, &CORNER[..2], Mods::default());
click(&mut tool, &cx, (80.0, 140.0), shift);
assert_eq!(selected(&tool.key(&cx, ToolKey::Enter, Mods::default())).1, "set");
}
#[test]
fn a_concave_loop_leaves_out_anchors_in_its_notch() {
let (d, id) = doc_with_rect();
let (s, p) = (Selection::default(), paint());
let cx = cx(&d, &s, &p);
let mut tool = PolygonalLassoTool::default();
// An L: the bottom left corner (100, 200) is in the notch.
clicks(&mut tool, &cx, &[(60.0, 60.0), (240.0, 60.0), (240.0, 240.0), (160.0, 240.0), (160.0, 170.0), (60.0, 170.0)], Mods::default());
let acts = tool.key(&cx, ToolKey::Enter, Mods::default());
assert_eq!(selected(&acts), (vec![(id.0, 3)], "set".to_owned()));
let Action::Exec(_, v) = &acts[0] else { panic!() };
let picked: Vec<Value> = v["items"][0]["anchors"].as_array().unwrap().clone();
// The rectangle's anchors run (100, 100), (200, 100), (200, 200), (100, 200).
assert!(!picked.contains(&serde_json::json!([0, 3])), "{picked:?}");
}
#[test]
fn fewer_than_three_vertices_select_nothing() {
let (d, _) = doc_with_rect();
let (s, p) = (Selection::default(), paint());
let cx = cx(&d, &s, &p);
let mut tool = PolygonalLassoTool::default();
clicks(&mut tool, &cx, &CORNER[..2], Mods::default());
// A click on the first vertex of a two-vertex loop sets no vertex on top of it and closes nothing.
assert!(click(&mut tool, &cx, (81.0, 80.0), Mods::default()).is_empty());
assert_eq!(tool.vertices.len(), 2);
assert!(tool.pointer(&cx, &PointerEvent::new(PointerKind::DoubleClick, 81.0, 80.0)).is_empty());
assert!(!tool.ends_on_escape(&cx));
clicks(&mut tool, &cx, &CORNER[..2], Mods::default());
assert!(tool.key(&cx, ToolKey::Enter, Mods::default()).is_empty());
assert!(!tool.ends_on_escape(&cx));
// A double-click on empty canvas: its second click sets no second vertex.
assert!(click(&mut tool, &cx, (80.0, 80.0), Mods::default()).is_empty());
assert!(click(&mut tool, &cx, (81.0, 80.0), Mods::default()).is_empty());
assert!(tool.pointer(&cx, &PointerEvent::new(PointerKind::DoubleClick, 81.0, 80.0)).is_empty());
assert!(!tool.ends_on_escape(&cx));
}
#[test]
fn a_loop_that_crosses_itself_selects_by_the_even_odd_rule() {
// A small square in the middle of a five-pointed star, where the star's edges wind twice, and
// one in the star's top point, where they wind once.
let mut d = Document::new(500.0, 500.0);
let l = d.layers[0].id;
let (middle, point) = (d.alloc_id(), d.alloc_id());
d.insert(Some(l), 0, Node::path(middle, shapes::rectangle(Rect::new(140.0, 140.0, 160.0, 160.0)), Appearance::default_art())).unwrap();
d.insert(Some(l), 1, Node::path(point, shapes::rectangle(Rect::new(148.0, 78.0, 152.0, 82.0)), Appearance::default_art())).unwrap();
let (s, p) = (Selection::default(), paint());
let cx = cx(&d, &s, &p);
let star: Vec<(f64, f64)> = (0..5)
.map(|k| {
let a = f64::from(-90 + 144 * k).to_radians();
(150.0 + 100.0 * a.cos(), 150.0 + 100.0 * a.sin())
})
.collect();
let mut tool = PolygonalLassoTool::default();
clicks(&mut tool, &cx, &star, Mods::default());
assert_eq!(selected(&tool.key(&cx, ToolKey::Enter, Mods::default())), (vec![(point.0, 4)], "set".to_owned()));
}
#[test]
fn a_dropped_press_takes_back_only_its_vertex() {
let (d, _) = doc_with_rect();
let (s, p) = (Selection::default(), paint());
let cx = cx(&d, &s, &p);
let mut tool = PolygonalLassoTool::default();
clicks(&mut tool, &cx, &CORNER[..2], Mods::default());
tool.pointer(&cx, &PointerEvent::new(PointerKind::Down, 80.0, 140.0));
assert!(tool.drop_press(&cx).is_empty());
assert_eq!(tool.vertices, vec![Point::new(80.0, 80.0), Point::new(140.0, 80.0)]);
assert_eq!(tool.hover, None);
}
#[test]
fn a_dropped_press_after_backspace_keeps_the_earlier_vertices() {
let (d, _) = doc_with_rect();
let (s, p) = (Selection::default(), paint());
let cx = cx(&d, &s, &p);
let mut tool = PolygonalLassoTool::default();
clicks(&mut tool, &cx, &CORNER[..2], Mods::default());
tool.pointer(&cx, &PointerEvent::new(PointerKind::Down, 80.0, 140.0));
assert!(tool.key(&cx, ToolKey::Backspace, Mods::default()).is_empty());
assert!(tool.drop_press(&cx).is_empty());
assert_eq!(tool.vertices, vec![Point::new(80.0, 80.0), Point::new(140.0, 80.0)]);
}
#[test]
fn the_tool_shows_the_lasso_cursor() {
let (d, _) = doc_with_rect();
let (s, p) = (Selection::default(), paint());
let cx = cx(&d, &s, &p);
assert_eq!(PolygonalLassoTool::default().cursor(&cx, Point::new(10.0, 10.0), Mods::default()), Cursor::Lasso);
}
+1 -1
View File
@@ -747,7 +747,7 @@ hotspot = "The tip."
[[cursor]]
id = "Lasso"
group = "Drawing and editing tools"
shown_when = ["The Lasso tool: drag a loop round anchor points and segments to select them; Shift adds to the selection, Alt takes from it.", "The Enclosing Lasso tool: draw a loop to select fully enclosed objects; Shift adds, Alt subtracts."]
shown_when = ["The Lasso tool: drag a loop round anchor points and segments to select them; Shift adds to the selection, Alt takes from it.", "The Enclosing Lasso tool: draw a loop to select fully enclosed objects; Shift adds, Alt subtracts.", "The Polygonal Lasso tool: click the corners of a loop around anchor points to select them; Shift or Alt at the first click adds or subtracts."]
hotspot = "Where the loop is drawn from."
[[cursor]]
+1
View File
@@ -686,6 +686,7 @@ mod cursor_tests {
for (id, c) in [
("lasso", Cursor::Lasso),
(addons::enclosing_lasso::ID, Cursor::Lasso),
(addons::polygonal_lasso::ID, Cursor::Lasso),
("magicWand", Cursor::MagicWand),
("paintbrush", Cursor::Paintbrush),
("blobBrush", Cursor::BlobBrush),
+1
View File
@@ -25,6 +25,7 @@ pub use gradient::GradientTool;
pub(crate) use measure::end_point as measure_end_point;
pub use measure::{MeasureTool, measure};
pub use transform::{TransformKind, TransformTool};
pub(crate) use wand::lasso_select;
pub use wand::{LassoTool, MagicWandTool};
/// Create a transform/utility tool by id (None = not one of ours).
+41 -34
View File
@@ -77,6 +77,46 @@ fn anchors_json(v: &BTreeSet<AnchorRef>) -> Value {
Value::Array(v.iter().map(|(s, a)| json!([s, a])).collect())
}
/// The selection a closed loop `poly` (even-odd) makes, for the Lasso and the Polygonal Lasso:
/// the anchor points inside it on every editable path a click can pick, and the gradient mesh
/// points inside it, which `mesh` keeps picked, with their meshes. `add` (Shift) adds to the
/// selection and `sub` (Alt) subtracts from it.
pub(crate) fn lasso_select(cx: &ToolContext, mesh: &mut MeshEdit, poly: &[Point], add: bool, sub: bool) -> Action {
// Anchors inside the loop for every editable path the Lasso may pick.
let mut hits: Vec<(NodeId, BTreeSet<AnchorRef>)> = vec![];
let mut inside: Vec<(NodeId, usize)> = vec![];
crate::draw2::walk_pickable(cx, |n| {
if let Some(grid) = grid_of(n) {
inside.extend(grid.points.iter().enumerate().filter(|(_, q)| point_in_polygon(poly, q.p)).map(|(i, _)| (n.id, i)));
}
if let NodeKind::Path { path, .. } = &n.kind {
let v: BTreeSet<AnchorRef> = path.anchors().filter(|(_, _, a)| point_in_polygon(poly, a.p)).map(|(s, i, _)| (s, i)).collect();
if !v.is_empty() {
hits.push((n.id, v));
}
}
});
let editable = cx.doc.editable();
hits.retain(|(id, _)| editable(*id) && cx.doc.is_visible(*id));
// The mesh points inside the loop are picked, and their meshes selected whole;
// Alt deselects a mesh only when it loses its last picked point.
inside.retain(|(id, _)| editable(*id) && cx.doc.is_visible(*id));
for (id, any) in mesh.lasso(&inside, add, sub) {
if any != sub {
hits.push((id, BTreeSet::new()));
}
}
let items: Vec<Value> = hits.iter().map(|(id, v)| json!({ "id": id.0, "anchors": anchors_json(v) })).collect();
let mode = if sub {
"subtract"
} else if add {
"add"
} else {
"set"
};
Action::Exec("select.anchorsMany".into(), json!({ "items": items, "mode": mode }))
}
impl Tool for LassoTool {
fn id(&self) -> &'static str {
"lasso"
@@ -107,40 +147,7 @@ impl Tool for LassoTool {
if poly.len() < 3 {
return if add || sub { vec![] } else { vec![Action::Exec("select.none".into(), json!({}))] };
}
// Anchors inside the loop for every editable path the Lasso may pick.
let mut hits: Vec<(NodeId, BTreeSet<AnchorRef>)> = vec![];
let mut inside: Vec<(NodeId, usize)> = vec![];
crate::draw2::walk_pickable(cx, |n| {
if let Some(grid) = grid_of(n) {
inside.extend(grid.points.iter().enumerate().filter(|(_, q)| point_in_polygon(&poly, q.p)).map(|(i, _)| (n.id, i)));
}
if let NodeKind::Path { path, .. } = &n.kind {
let v: BTreeSet<AnchorRef> =
path.anchors().filter(|(_, _, a)| point_in_polygon(&poly, a.p)).map(|(s, i, _)| (s, i)).collect();
if !v.is_empty() {
hits.push((n.id, v));
}
}
});
let editable = cx.doc.editable();
hits.retain(|(id, _)| editable(*id) && cx.doc.is_visible(*id));
// The mesh points inside the loop are picked, and their meshes selected whole;
// Alt deselects a mesh only when it loses its last picked point.
inside.retain(|(id, _)| editable(*id) && cx.doc.is_visible(*id));
for (id, any) in self.mesh.lasso(&inside, add, sub) {
if any != sub {
hits.push((id, BTreeSet::new()));
}
}
let items: Vec<Value> = hits.iter().map(|(id, v)| json!({ "id": id.0, "anchors": anchors_json(v) })).collect();
let mode = if sub {
"subtract"
} else if add {
"add"
} else {
"set"
};
vec![Action::Exec("select.anchorsMany".into(), json!({ "items": items, "mode": mode }))]
vec![lasso_select(cx, &mut self.mesh, &poly, add, sub)]
}
_ => vec![],
}
+2
View File
@@ -12,6 +12,7 @@ pub mod image;
pub mod packaging;
pub mod pathtools;
pub mod pen;
pub mod polygonal_lasso;
pub mod select;
pub mod shapes;
pub mod typetools;
@@ -33,6 +34,7 @@ pub fn plugin_menu() -> Vec<Item> {
Item::Sub("Image Tools", image::menu()),
Item::Sub("Packaging Tools", packaging::menu()),
Item::Sub("Path Precision Tools", pathtools::menu()),
Item::Sub("Polygonal Lasso", polygonal_lasso::menu()),
Item::Sub("Selection Tools", select::menu()),
Item::Sub("Smart Pen", pen::menu()),
Item::Sub("Type Tools", typetools::menu()),
@@ -0,0 +1,8 @@
use serde_json::json;
use vectorcraft_tools::addons::polygonal_lasso;
use crate::menus::Item;
pub fn menu() -> Vec<Item> {
vec![Item::Cmd("Polygonal Lasso Tool", "tool.select", json!({"tool": polygonal_lasso::ID}))]
}
+212 -26
View File
@@ -24,7 +24,13 @@
//! show the new colors on the smooth wheel, on a segmented wheel (solid patches of 24 hues by 5
//! saturations; its markers move as freely) or as color bars (one per new color, in row order: click
//! one to select it for the sliders, drag one to move its row, which changes no color); the dialog
//! opens on the smooth wheel. With art, the Prominent Colors bar under the wheel shows the new
//! opens on the smooth wheel. Under them, the Add Color tool adds a click on either wheel as a new
//! color (the hue and saturation clicked, at the wheel's brightness; on the segmented wheel the
//! patch's color) in a new row with no current colors, which becomes the selected one, and the
//! Remove Color tool removes the color whose marker is clicked; a bar's right-click menu has Remove
//! Color too. The base color can't be removed. A removed color's row goes, unless it has current
//! colors and art or a group is open: it then keeps them, with no new color, so that art keeps its
//! colors and the group's swatch at that place goes. With art, the Prominent Colors bar under the wheel shows the new
//! colors, each part as wide as its row's share of the art's uses, the largest first; dragging the
//! edge between two parts moves width between them, and when the drag ends the rows' current
//! colors move toward those widths (`recolor.weigh`), and the art previews them. The New Color
@@ -39,19 +45,22 @@
//! The Color Theme Picker button beside the tabs turns on picking from the canvas: a click on an
//! object takes the palette of the object a Selection tool click takes, a drag takes the palette
//! of the art inside its marquee, and Shift adds to the picks so far (`recolor.pickTheme`). The
//! rows that aren't excluded and hold current colors take the picked colors as their new colors,
//! rows that aren't excluded and hold current colors (or were added on the Edit tab) take the
//! picked colors as their new colors,
//! the most used color first and repeating when the rows outnumber them, and the art previews
//! them; OK keeps them as one undo step. A new count of Colors keeps the picks: the new rows take them again.
//!
//! Fields (`ui.dialog.set`): `rows` ([{from: [keys], to: key, exclude?, tint?: percent of a spot
//! color}]), `colors` (null: Auto, or a count), `method`, `preserveWhite`, `preserveBlack`,
//! color, added?}]; a row with no current colors, `from: []`, recolors no art, and with `added: true`
//! (a color the Add Color tool added) adds its new color to the color group; `to: null`, no new color), `colors` (null: Auto, or a count), `method`, `preserveWhite`, `preserveBlack`,
//! `preserveGrays`, `limitTo` (library id, "document" for the document's swatches, "" for none),
//! `group`, `groupName`, `tab` (`assign` or `edit`), `rule` (harmony id), `linked`, `preview`,
//! `sliderMode` (`hsb`, `rgb`, `cmyk`, `lab` or `tint`; unset: the row color's own model, HSB for
//! a gray and Tint for a spot color; `global`: Global Adjust, on the Edit tab), `globalAdjust`
//! (`{saturation, brightness, temperature, luminosity}` in percent, sent as `recolor.apply`'s
//! `globalAdjust` in every slider mode), `display` (the Edit tab's `smooth`, `segmented` or `bars`;
//! unset: `smooth`), `themePicker` (the Color Theme Picker is on), `themePicks` (its picks, as
//! unset: `smooth`), `wheelTool` (`add`: the Add Color tool, `remove`: the Remove Color tool;
//! unset: neither, a click on the wheel selects a marker), `themePicker` (the Color Theme Picker is on), `themePicks` (its picks, as
//! `recolor.pickTheme`'s `picks`; a new list recolors the rows), `weights` (one per row, as
//! `recolor.weigh`'s; a new list moves the rows' current colors toward them), `findColors` (Find is
//! on; it shows the art so on the Assign tab, with art and rows selected). Changing `colors`, a
@@ -393,7 +402,7 @@ fn group_colors<'a>(app: &VectorcraftApp, d: &Dialog, rs: impl Iterator<Item = &
}
/// The New Color Group menu's request: save the new colors of the rows that aren't excluded and
/// hold current colors (Save All Colors, in row order; a row without one gives its first current
/// hold current colors or were added on the Edit tab (Save All Colors, in row order; a row without one gives its first current
/// color) or of the Prominent Colors bar (Save Prominent Colors, in its order) as a new color
/// group, a step of its own (`swatch.newGroup`).
fn save_group(app: &mut VectorcraftApp, d: &mut Dialog, which: &str) {
@@ -420,7 +429,7 @@ const THEME_PICKS: &str = "themePicks";
const THEME_DONE: &str = "__themePicked";
/// When the picks of the Color Theme Picker changed, give the rows that aren't excluded and hold
/// current colors the palette of the art picked (`recolor.pickTheme`, as many colors as those
/// current colors or were added on the Edit tab the palette of the art picked (`recolor.pickTheme`, as many colors as those
/// rows), in row order; with fewer colors than rows, the colors repeat. Picks that touch no art
/// leave the rows as they are.
fn sync_theme(app: &mut VectorcraftApp, d: &mut Dialog) {
@@ -561,14 +570,25 @@ fn excluded(row: &Value) -> bool {
row["exclude"].as_bool().unwrap_or(false)
}
/// Whether `row` holds no current colors: a row made with New Row, until colors are merged into it.
/// Its new color recolors nothing and is no color of a color group, the wheel or the harmony rules.
/// Whether `row` has no current colors (a row made with New Row, or a color added on the Edit tab).
fn no_current(row: &Value) -> bool {
row["from"].as_array().is_none_or(Vec::is_empty)
}
/// Whether `row` is a color added on the Edit tab (`added`), which joins the color group.
fn is_added(row: &Value) -> bool {
row["added"].as_bool().unwrap_or(false)
}
/// Whether `row` is a row made with New Row that holds no current colors, until colors are merged
/// into it. Its new color recolors nothing and is no color of a color group, the wheel or the
/// harmony rules. A color added on the Edit tab (`added`) is not empty: it joins the color group.
fn empty(row: &Value) -> bool {
row["from"].as_array().is_some_and(Vec::is_empty)
row["from"].as_array().is_some_and(Vec::is_empty) && !is_added(row)
}
/// Whether `row`'s new color is one of the colors a color group takes: the row isn't excluded and
/// holds current colors.
/// holds current colors or is a color added on the Edit tab.
fn in_group(row: &Value) -> bool {
!excluded(row) && !empty(row)
}
@@ -583,15 +603,19 @@ fn selection(d: &Dialog) -> Vec<usize> {
}
/// `recolor.apply` parameters: the rows, method, library and the group with its new name and
/// colours: the rows' new colours, then (with art) the group's colours no row took.
/// colors: the new colors of the rows with current colors, each in its swatch's place (`null`
/// for a row whose new color was removed, which removes its swatch), then (with art) the group's
/// colors no row took, then the colors added on the Edit tab.
fn apply_params(d: &Dialog) -> Value {
let rs = rows(d);
let group = d.fields.get("group").and_then(Value::as_str).map(|g| {
// A row made with New Row that holds no current colors gives the group no color.
let filled: Vec<&Value> = rs.iter().filter(|r| !empty(r)).map(|r| &r["to"]).collect();
// A row made with New Row that holds no current colors gives the group no color; a color
// added on the Edit tab (`added`) joins it after the others.
let took: Vec<&Value> = rs.iter().filter(|r| !no_current(r)).map(|r| &r["to"]).collect();
let assign = d.fields.get("__assign").and_then(Value::as_array).filter(|_| d.bool("__art"));
let rest = assign.map_or(&[][..], |a| a.get(filled.len()..).unwrap_or_default());
let colors: Vec<&Value> = filled.into_iter().chain(rest).collect();
let rest = assign.map_or(&[][..], |a| a.get(took.len()..).unwrap_or_default());
let added = rs.iter().filter(|r| no_current(r) && is_added(r) && !excluded(r)).map(|r| &r["to"]).filter(|c| !c.is_null());
let colors: Vec<&Value> = took.into_iter().chain(rest).chain(added).collect();
let name = d.str("groupName");
let rename = (!name.trim().is_empty() && name != g).then_some(name);
json!({"group": g, "groupColors": colors, "rename": rename})
@@ -921,15 +945,21 @@ fn assign_tab(app: &mut VectorcraftApp, ui: &mut Ui, d: &mut Dialog, rows: &mut
let (nr, _) = ui.allocate_exact_size(vec2(46.0, 20.0), Sense::hover());
let nresp = ui.interact(nr, egui::Id::unique((NEW_CHIP, i)), Sense::click());
let to = to_color(row).unwrap_or_default();
chip(ui, nr, shown.get(i).copied().unwrap_or_default(), off);
// A row whose new color was removed shows an empty frame and an empty hex field.
let has_new = to_color(row).is_some();
if has_new {
chip(ui, nr, shown.get(i).copied().unwrap_or_default(), off);
} else {
ui.painter().rect_stroke(nr, 1.0, egui::Stroke::new(1.0, t.border), egui::StrokeKind::Inside);
}
if nresp.clicked() {
clicked = Some(i);
}
if nresp.double_clicked() {
if nresp.double_clicked() && has_new {
pick = Some(i);
}
ui.add_space(6.0);
let hex = crate::panels::color::hex_digits(&to);
let hex = if has_new { crate::panels::color::hex_digits(&to) } else { String::new() };
let hex_name = format!("{} {}", tl!("Color"), i + 1);
if let Some(h) = widgets::hex_field_named(ui, ("recolor-hex", i), Some(&hex_name), &hex)
&& let Some(c) = crate::panels::color::parse_hex(&h)
@@ -1383,7 +1413,7 @@ fn new_row(rows: &mut Vec<Value>, sel: &[usize]) -> usize {
}
/// The rows the Edit tab shows, the harmony rules fill and the Color Theme Picker recolors: those
/// with a new colour that aren't excluded and hold current colors.
/// with a new colour that aren't excluded and hold current colors or were added on the Edit tab.
fn active_rows(rows: &[Value]) -> Vec<usize> {
(0..rows.len()).filter(|i| in_group(&rows[*i]) && to_color(&rows[*i]).is_some()).collect()
}
@@ -1413,8 +1443,61 @@ fn move_color(rows: &mut [Value], i: usize, hsb: [f32; 3], linked: bool) {
/// The rows when a drag on the Edit tab's wheel started.
const DRAG: &str = "__drag";
/// The field of the Edit tab's wheel tools: `add` (Add Color) or `remove` (Remove Color).
const WHEEL_TOOL: &str = "wheelTool";
/// The new color the Add Color tool gives a click at hue `h` (degrees) and saturation `s`: at the
/// brightness of `base` (the base color, whose brightness the wheel shows; full without one), the
/// segmented wheel's patch color with `segmented`, in `base`'s model.
fn added_color(base: Option<Color>, h: f32, s: f32, segmented: bool) -> Color {
let v = base.map_or(1.0, |b| b.to_hsb()[2]);
let c = if segmented { widgets::segment_color(h, s, v) } else { Color::from_hsb(h, s, v) };
base.map_or(c, |b| keep_model(b, c))
}
/// Add new color `c` as a row with no current colors, marked `added`, after the others. Returns
/// its index.
fn add_color(rows: &mut Vec<Value>, c: &Color) -> usize {
rows.push(json!({"from": [], "to": key(c), "added": true}));
rows.len() - 1
}
/// Remove row `i`'s new color: a row with no current colors (or, without `keep`, any row) goes,
/// and with `keep` (art, or a color group whose swatches the rows are) a row with current colors
/// stays with no new color, so that its art keeps its colors and its group swatch is removed in
/// its place. The base row `base` stays. Returns the base row's index afterwards, or `None` when
/// nothing changed.
fn remove_color(rows: &mut Vec<Value>, i: usize, base: Option<usize>, keep: bool) -> Option<usize> {
if Some(i) == base || i >= rows.len() || to_color(&rows[i]).is_none() {
return None;
}
if keep && !no_current(&rows[i]) {
rows[i]["to"] = Value::Null;
if let Some(r) = rows[i].as_object_mut() {
r.remove("tint");
r.remove("model");
}
return Some(base.unwrap_or(0));
}
rows.remove(i);
Some(base.map_or(0, |b| if b > i { b - 1 } else { b }))
}
/// Whether Remove Color keeps a row with current colors (see [`remove_color`]): with art, or with a
/// color group.
fn keeps_rows(d: &Dialog) -> bool {
d.bool("__art") || d.fields.get("group").is_some_and(Value::is_string)
}
/// After Remove Color: select the base row at `base`; the slider values held were for a row index
/// that may now hold another row.
fn removed(d: &mut Dialog, base: usize) {
d.fields.insert("__sel".into(), json!([base]));
d.fields.remove(COMPS);
}
/// The Edit tab. Returns true when the rows changed.
fn edit_tab(app: &VectorcraftApp, ui: &mut Ui, d: &mut Dialog, rows: &mut [Value]) -> bool {
fn edit_tab(app: &VectorcraftApp, ui: &mut Ui, d: &mut Dialog, rows: &mut Vec<Value>) -> bool {
let top = ui.cursor().top();
let t = Tokens::get(ui.ctx());
let mut changed = false;
@@ -1468,6 +1551,9 @@ fn edit_tab(app: &VectorcraftApp, ui: &mut Ui, d: &mut Dialog, rows: &mut [Value
let colors: Vec<Color> = active.iter().filter_map(|&i| to_color(&rows[i])).collect();
let marked = base.and_then(|b| active.iter().position(|&i| i == b));
let display = d.str("display");
let tool = d.str(WHEEL_TOOL);
// The tools act on either wheel, not on the color bars.
let on_wheel = display != "bars";
let mut w = widgets::WheelResponse::default();
ui.horizontal(|ui| {
// The display buttons, beside the wheel so the tab keeps its height.
@@ -1482,6 +1568,14 @@ fn edit_tab(app: &VectorcraftApp, ui: &mut Ui, d: &mut Dialog, rows: &mut [Value
d.fields.insert("display".into(), json!(id));
}
}
// The wheel tools: a click on the button turns its tool on, or off again.
ui.add_space(8.0);
for (id, icon, tip) in [("add", "plus", tl!("Add Color Tool")), ("remove", "minus", tl!("Remove Color Tool"))] {
let on = tool == id;
if widgets::icon_button_enabled(ui, icon, tip, on && on_wheel, on_wheel, 24.0).clicked() {
d.fields.insert(WHEEL_TOOL.into(), if on { Value::Null } else { json!(id) });
}
}
});
ui.vertical(|ui| match display.as_str() {
"segmented" => w = widgets::segmented_wheel(ui, "recolor-wheel", WHEEL, &colors, marked),
@@ -1489,17 +1583,33 @@ fn edit_tab(app: &VectorcraftApp, ui: &mut Ui, d: &mut Dialog, rows: &mut [Value
_ => w = widgets::harmony_wheel(ui, "recolor-wheel", WHEEL, &colors, marked),
});
});
// A click with a wheel tool adds a color there, or removes the color of the marker clicked.
let clicked = w.clicked.filter(|_| on_wheel && matches!(tool.as_str(), "add" | "remove"));
if let Some((hit, [h, s])) = clicked {
if tool == "add" {
let c = added_color(base.and_then(|b| to_color(&rows[b])), h, s, display == "segmented");
let i = add_color(rows, &c);
d.fields.insert("__sel".into(), json!([i]));
d.fields.remove(COMPS);
changed = true;
} else if let Some(b) = hit.and_then(|k| remove_color(rows, active[k], base, keeps_rows(d))) {
removed(d, b);
changed = true;
}
}
// Prominent Colors: the art's new colors, each as wide as its share of the art.
if art {
prominent_bar(ui, d, rows);
}
if let Some(k) = w.pressed {
// A tool's click selects no marker: Add Color selects the new row, and Remove Color keeps the
// base color.
if let Some(k) = w.pressed.filter(|_| clicked.is_none()) {
d.fields.insert("__sel".into(), json!([active[k]]));
}
// A drag (of a marker or the brightness slider) moves the rows as they were when it started:
// a new colour read back from its model (CMYK through the colour profile) isn't exactly the
// colour written, so building on last frame's rows drifted the linked colours (#1733).
if let Some((k, set)) = w.moved {
if let Some((k, set)) = w.moved.filter(|_| clicked.is_none()) {
let start = match d.fields.get(DRAG).and_then(Value::as_array) {
Some(s) if s.len() == rows.len() => s.clone(),
_ => rows.to_vec(),
@@ -1519,6 +1629,9 @@ fn edit_tab(app: &VectorcraftApp, ui: &mut Ui, d: &mut Dialog, rows: &mut [Value
if !art {
ui.add_space(SLIDERS_GAP);
}
// A color added or removed above changed the rows, so the sliders and chips read them afresh.
let active = active_rows(rows);
let base = selection(d).into_iter().find(|i| active.contains(i)).or(active.first().copied());
if d.str("sliderMode") == GLOBAL {
let sample = base.and_then(|b| to_color(&rows[b])).unwrap_or(Color::rgb(0.8, 0.45, 0.25));
global_sliders(ui, d, sample);
@@ -1549,11 +1662,12 @@ fn edit_tab(app: &VectorcraftApp, ui: &mut Ui, d: &mut Dialog, rows: &mut [Value
/// The Edit tab's color bars: a solid bar per row of `active` with its new color, in row order, the
/// base row's framed, scrolling past the wheel's height. A click on a bar selects its row (the
/// sliders under it edit that row's new color); a drag moves the bar's row to where the line under
/// the pointer shows, keeping every new color. Returns true when the rows moved.
fn color_bars(ui: &mut Ui, d: &mut Dialog, rows: &mut [Value], active: &[usize], base: Option<usize>) -> bool {
/// the pointer shows, keeping every new color. A bar's right-click menu has Remove Color (not for the
/// base row's). Returns true when the rows moved or a color was removed.
fn color_bars(ui: &mut Ui, d: &mut Dialog, rows: &mut Vec<Value>, active: &[usize], base: Option<usize>) -> bool {
let t = Tokens::get(ui.ctx());
let mut rects: Vec<Rect> = Vec::with_capacity(active.len());
let (mut dragging, mut released, mut dropped) = (None, None, None);
let (mut dragging, mut released, mut dropped, mut remove) = (None, None, None, None);
// The area is given its full height first: in the row beside the display buttons a scroll area
// alone is only as tall as the room the row has.
let area = vec2(ui.available_width(), BARS_H);
@@ -1584,7 +1698,12 @@ fn color_bars(ui: &mut Ui, d: &mut Dialog, rows: &mut [Value], active: &[usize],
released = Some(n);
}
rects.push(r);
resp.on_hover_text(rows[i]["to"].as_str().unwrap_or_default());
let resp = resp.on_hover_text(rows[i]["to"].as_str().unwrap_or_default());
resp.context_menu(|ui| {
if widgets::menu_item_name(ui, tl!("Remove Color"), Some(i) != base, false) {
remove = Some(i);
}
});
}
// The place a dragged bar goes: before the first bar whose middle is below the pointer.
let at = ui.input(|i| i.pointer.latest_pos()).map(|p| rects.iter().filter(|r| r.center().y < p.y).count());
@@ -1599,6 +1718,10 @@ fn color_bars(ui: &mut Ui, d: &mut Dialog, rows: &mut [Value], active: &[usize],
dropped = released.zip(at);
});
});
if let Some(b) = remove.and_then(|i| remove_color(rows, i, base, keeps_rows(d))) {
removed(d, b);
return true;
}
let Some(moved) = dropped.and_then(|(n, to)| move_bar(rows, active, n, to)) else { return false };
d.fields.insert("__sel".into(), json!([moved]));
// The slider values held are those of a row index that may now hold another row.
@@ -1689,6 +1812,58 @@ mod tests {
assert!(c.to_hsb()[1] < 1e-3, "{c:?}");
}
/// Remove Color: a row with no current colors goes, with art or a group a row's current colors
/// stay with no new color, without either the row goes, and the base row stays; the base row's
/// index follows.
#[test]
fn remove_color_drops_added_rows_and_empties_rows_of_art() {
let mut r = rows();
assert_eq!(add_color(&mut r, &Color::rgb(0.0, 1.0, 1.0)), 3);
assert_eq!(r[3], json!({"from": [], "to": "rgb 0 255 255", "added": true}));
assert_eq!(remove_color(&mut r, 0, Some(0), true), None, "the base row stays");
r[1]["tint"] = json!(50);
assert_eq!(remove_color(&mut r, 1, Some(2), true), Some(2));
assert_eq!(r[1], json!({"from": ["rgb 0 0 255", "rgb 0 0 128"], "to": null}), "the art's colors stay, without a tint");
assert_eq!(remove_color(&mut r, 1, Some(2), true), None, "no new color left to remove");
assert_eq!(remove_color(&mut r, 3, Some(2), true), Some(2));
assert_eq!(r.len(), 3, "the added row goes");
assert_eq!(remove_color(&mut r, 9, Some(2), true), None);
let mut r = rows();
assert_eq!(remove_color(&mut r, 0, Some(2), false), Some(1), "without art the row goes, and the base row moves up");
assert_eq!(r.len(), 2);
assert_eq!(r[1]["from"], json!(["rgb 0 255 0"]));
}
/// An added color is the hue and saturation clicked at the base color's brightness (full without
/// one), the patch's color on the segmented wheel, in the base color's model.
#[test]
fn an_added_color_takes_the_base_colors_brightness_and_model() {
let near = |a: [f32; 3], b: [f32; 3]| a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-3);
let base = Color::from_hsb(10.0, 0.8, 0.6);
assert!(near(added_color(Some(base), 120.0, 0.5, false).to_hsb(), [120.0, 0.5, 0.6]));
assert!(near(added_color(None, 200.0, 0.25, false).to_hsb(), [200.0, 0.25, 1.0]));
assert!(near(added_color(None, 7.0, 0.95, true).to_hsb(), [0.0, 0.9, 1.0]), "the patch's color");
let cmyk = color_value(&json!("cmyk 0 100 100 0")).unwrap();
assert!(matches!(added_color(Some(cmyk), 120.0, 0.5, false), Color::Cmyk { .. }));
}
/// With a color group and art, a row without a new color removes its swatch in its place, the
/// group's colors no row of art took stay in theirs, and a color added on the Edit tab adds its
/// new color after them; a row made with New Row, which holds no current colors, adds none.
#[test]
fn apply_params_give_the_group_added_colors_and_keep_its_other_colors() {
let mut d = Dialog::new(KIND, json!({"group": "G", "groupName": "G", "__art": true, "__assign": ["rgb 1 1 1", "rgb 2 2 2", "rgb 3 3 3"]}));
let mut rs = vec![json!({"from": ["rgb 255 0 0"], "to": "rgb 1 1 1"}), json!({"from": ["rgb 0 0 255"], "to": null})];
new_row(&mut rs, &[]);
add_color(&mut rs, &Color::rgb(9.0 / 255.0, 9.0 / 255.0, 9.0 / 255.0));
d.fields.insert("rows".into(), json!(rs));
assert_eq!(apply_params(&d)["groupColors"], json!(["rgb 1 1 1", null, "rgb 3 3 3", "rgb 9 9 9"]));
// An added color whose row is excluded joins no group.
rs[3]["exclude"] = json!(true);
d.fields.insert("rows".into(), json!(rs));
assert_eq!(apply_params(&d)["groupColors"], json!(["rgb 1 1 1", null, "rgb 3 3 3"]));
}
#[test]
fn merge_and_separate_rows() {
let mut r = rows();
@@ -1816,6 +1991,17 @@ mod tests {
assert_eq!(edit_slider_row(&sel(json!([0])), &r, &[], None), None, "no row to edit");
}
/// A color added on the Edit tab holds no current colors but is not an empty row: the Edit tab
/// shows it and a color group takes it.
#[test]
fn an_added_color_is_not_an_empty_row() {
let added = json!({"from": [], "to": "rgb 0 255 255", "added": true});
assert!(!empty(&added) && in_group(&added));
let mut r = rows();
r.push(added);
assert_eq!(active_rows(&r), [0, 1, 2, 3]);
}
/// A rule or a wheel move that gives a row a new color drops the row's tint; a row whose
/// color stays keeps it.
#[test]
+1 -1
View File
@@ -300,7 +300,7 @@ fn code_view(app: &VectorcraftApp, ui: &mut egui::Ui, d: &Dialog) {
None => {
const MAX: usize = 200_000;
let params = json!({ "svg": opts });
let encoded = vectorcraft_engine::cmd::fileio::check_linked_scripts("document.export", "svg", st).and_then(|()| {
let encoded = vectorcraft_engine::cmd::fileio::check_linked_scripts("document.export", "svg", st, &params).and_then(|()| {
let selected;
let doc = if selection {
selected = vectorcraft_engine::cmd::fileio::selection_doc(st, "document.exportSelection", false)?.0;
+5 -2
View File
@@ -637,6 +637,7 @@ fn addon_tools_are_in_the_drawer_not_the_toolbars() {
let enclosing = vectorcraft_tools::addons::enclosing_lasso::ID;
let contour = vectorcraft_tools::addons::contour::ID;
let box3d = vectorcraft_tools::addons::box3d::ID;
let polygonal = vectorcraft_tools::addons::polygonal_lasso::ID;
let addon: Vec<&str> = vectorcraft_tools::addons::GROUPS.iter().flat_map(|g| g.iter().map(|t| t.id)).collect();
assert_eq!(
addon,
@@ -652,7 +653,8 @@ fn addon_tools_are_in_the_drawer_not_the_toolbars() {
"smartPen",
enclosing,
contour,
box3d
box3d,
polygonal
]
);
for advanced in [false, true] {
@@ -669,7 +671,8 @@ fn addon_tools_are_in_the_drawer_not_the_toolbars() {
assert_eq!(listed(enclosing), Some(("Enclosing Lasso", vec![enclosing])));
assert_eq!(listed(contour), Some(("Contour", vec![contour])));
assert_eq!(listed(box3d), Some(("3D Box", vec![box3d])));
for tool in ["extendPath", "smartPen", enclosing, contour, box3d] {
assert_eq!(listed(polygonal), Some(("Polygonal Lasso", vec![polygonal])));
for tool in ["extendPath", "smartPen", enclosing, contour, box3d, polygonal] {
app.run("toolbar.addTool", json!({"tool": tool})).unwrap();
assert!(slot_of(&app, tool).is_some(), "{tool}");
}
+5
View File
@@ -1504,6 +1504,9 @@ font-technology Variable Променливи
Show smooth color wheel Показване на плавно цветово колело
Show segmented color wheel Показване на сегментирано цветово колело
Show color bars Показване на цветни ленти
Add Color Tool Инструмент „Добавяне на цвят“
Remove Color Tool Инструмент „Премахване на цвят“
Remove Color Премахване на цвят
Find the selected colors in the artwork Намиране на избраните цветове в илюстрацията
Harmony Sets Набори от хармонии
Height Височина
@@ -1836,6 +1839,8 @@ font-technology Variable Променливи
Lasso Tool Инструмент „Ласо“
Enclosing Lasso Tool Инструмент „Обхващащо ласо“
Enclosing Lasso Обхващащо ласо
Polygonal Lasso Tool Инструмент „Многоъгълно ласо“
Polygonal Lasso Многоъгълно ласо
Last Effect: {name} Посл. ефект: {name}
Last Effect: {} Посл. ефект: {}
Last Effect… Посл. ефект…
Can't render this file because it is too large.
+5
View File
@@ -1413,6 +1413,8 @@ lighting Light Svjetlo
Lasso Tool Alat laso
Enclosing Lasso Tool Alat laso za obuhvatanje
Enclosing Lasso Laso za obuhvatanje
Polygonal Lasso Tool Alat poligonalni laso
Polygonal Lasso Poligonalni laso
Lasso Laso
Line Cut Tool Alat za rez linijom
Line Graph Tool Alat za linijski grafikon
@@ -2925,6 +2927,9 @@ digits Malayalam Malajalam
Show smooth color wheel Prikaži glatki kotač boja
Show segmented color wheel Prikaži segmentirani kotač boja
Show color bars Prikaži trake boja
Add Color Tool Alat za dodavanje boje
Remove Color Tool Alat za uklanjanje boje
Remove Color Ukloni boju
Find the selected colors in the artwork Pronađi odabrane boje u crtežu
Harmony Rules Pravila harmonije
Keep this row's colors (exclude) Zadrži boje ovog reda (isključi)
Can't render this file because it contains an unexpected character in line 2 and column 73.
+5
View File
@@ -2044,6 +2044,9 @@ digits Malayalam Malaiàlam
Show smooth color wheel Mostra la roda de color contínua
Show segmented color wheel Mostra la roda de color segmentada
Show color bars Mostra les barres de color
Add Color Tool Eina Afegeix color
Remove Color Tool Eina Elimina color
Remove Color Elimina el color
Find the selected colors in the artwork Troba els colors seleccionats a l’obra
Harmony Sets Conjunts d’harmonia
HDTV 1080p HDTV 1080p
@@ -2348,6 +2351,8 @@ digits Malayalam Malaiàlam
Lasso Tool Eina de llaç
Enclosing Lasso Tool Eina de llaç envoltant
Enclosing Lasso Llaç envoltant
Polygonal Lasso Tool Eina de llaç poligonal
Polygonal Lasso Llaç poligonal
Last Últim
Last Artboard Últim tauler
Status Bar Show Mostra a la barra d'estat
Can't render this file because it contains an unexpected character in line 2 and column 73.
+5
View File
@@ -1439,6 +1439,8 @@ lighting Light Světlo
Lasso Tool Nástroj Laso
Enclosing Lasso Tool Nástroj obklopující laso
Enclosing Lasso Obklopující laso
Polygonal Lasso Tool Nástroj Mnohoúhelníkové laso
Polygonal Lasso Mnohoúhelníkové laso
Lasso Laso
Line Cut Tool Nástroj Řez čarou
Line Graph Tool Nástroj Spojnicový graf
@@ -3010,6 +3012,9 @@ digits Malayalam Malajálamské
Show smooth color wheel Zobrazit plynulé barevné kolo
Show segmented color wheel Zobrazit segmentované barevné kolo
Show color bars Zobrazit barevné pruhy
Add Color Tool Nástroj Přidat barvu
Remove Color Tool Nástroj Odstranit barvu
Remove Color Odstranit barvu
Find the selected colors in the artwork Najít vybrané barvy v kresbě
Harmony Rules Pravidla harmonie
Keep this row's colors (exclude) Ponechat barvy tohoto řádku (vyloučit)
Can't render this file because it is too large.
+5
View File
@@ -4014,6 +4014,8 @@ lighting Light Lys
Lasso Tool Lassoværktøj
Enclosing Lasso Tool Omsluttende lassoværktøj
Enclosing Lasso Omsluttende lasso
Polygonal Lasso Tool Polygonlassoværktøj
Polygonal Lasso Polygonlasso
Lasso Lasso
Line Cut Tool Linjeskæringsværktøj
Line Graph Tool Linjediagramværktøj
@@ -5458,6 +5460,9 @@ digits Malayalam Malayalam
Show smooth color wheel Vis glat farvehjul
Show segmented color wheel Vis segmenteret farvehjul
Show color bars Vis farvebjælker
Add Color Tool Værktøjet Tilføj farve
Remove Color Tool Værktøjet Fjern farve
Remove Color Fjern farve
Find the selected colors in the artwork Find de valgte farver i grafikken
Harmony Rules Harmoniregler
Keep this row's colors (exclude) Behold farverne i denne række (ekskludér)
Can't render this file because it is too large.
+5
View File
@@ -1554,6 +1554,9 @@ file-filter Templates Vorlagen
Show smooth color wheel Stufenlosen Farbkreis anzeigen
Show segmented color wheel Segmentierten Farbkreis anzeigen
Show color bars Farbbalken anzeigen
Add Color Tool Farbe-hinzufügen-Werkzeug
Remove Color Tool Farbe-entfernen-Werkzeug
Remove Color Farbe entfernen
Find the selected colors in the artwork Ausgewählte Farben in der Grafik finden
Harmony Sets Harmoniesätze
Height Höhe
@@ -1902,6 +1905,8 @@ file-filter Templates Vorlagen
Lasso Tool Lasso-Werkzeug
Enclosing Lasso Tool Umschließendes Lasso-Werkzeug
Enclosing Lasso Umschließendes Lasso
Polygonal Lasso Tool Polygon-Lasso-Werkzeug
Polygonal Lasso Polygon-Lasso
Last Effect: {name} Letzter Effekt: {name}
Last Effect: {} Letzter Effekt: {}
Last Effect… Letzter Effekt…
Can't render this file because it is too large.
+5
View File
@@ -1486,6 +1486,9 @@ font-technology Variable Μεταβλητές
Show smooth color wheel Εμφάνιση ομαλού χρωματικού τροχού
Show segmented color wheel Εμφάνιση τμηματοποιημένου χρωματικού τροχού
Show color bars Εμφάνιση χρωματικών ράβδων
Add Color Tool Εργαλείο προσθήκης χρώματος
Remove Color Tool Εργαλείο αφαίρεσης χρώματος
Remove Color Αφαίρεση χρώματος
Find the selected colors in the artwork Εύρεση των επιλεγμένων χρωμάτων στο σχέδιο
Harmony Sets Σύνολα χρωματικής αρμονίας
Height Ύψος
@@ -1806,6 +1809,8 @@ font-technology Variable Μεταβλητές
Lasso Tool Λάσο (Lasso Tool)
Enclosing Lasso Tool Εργαλείο περικλείοντος λάσου
Enclosing Lasso Περικλείον λάσο
Polygonal Lasso Tool Εργαλείο πολυγωνικού λάσου
Polygonal Lasso Πολυγωνικό λάσο
Last Effect: {name} Τελευταίο εφέ: {name}
Last Effect: {} Τελευταίο εφέ: {}
Last Effect… Τελευταίο εφέ…
Can't render this file because it is too large.
+5
View File
@@ -1569,6 +1569,9 @@ font-technology Variable Variables
Show smooth color wheel Mostrar rueda de color continua
Show segmented color wheel Mostrar rueda de color segmentada
Show color bars Mostrar barras de color
Add Color Tool Herramienta Añadir color
Remove Color Tool Herramienta Eliminar color
Remove Color Eliminar color
Find the selected colors in the artwork Buscar los colores seleccionados en la ilustración
Harmony Sets Conjuntos de armonía
Height Altura
@@ -1903,6 +1906,8 @@ font-technology Variable Variables
Lasso Tool Herramienta Lazo
Enclosing Lasso Tool Herramienta Lazo envolvente
Enclosing Lasso Lazo envolvente
Polygonal Lasso Tool Herramienta Lazo poligonal
Polygonal Lasso Lazo poligonal
Last Effect: {name} Último efecto: {name}
Last Effect: {} Último efecto: {}
Last Effect… Último efecto…
Can't render this file because it contains an unexpected character in line 2 and column 73.
+5
View File
@@ -1415,6 +1415,8 @@ lighting Light Valo
Lasso Tool Lassotyökalu
Enclosing Lasso Tool Sulkeva lassotyökalu
Enclosing Lasso Sulkeva lasso
Polygonal Lasso Tool Monikulmiolassotyökalu
Polygonal Lasso Monikulmiolasso
Lasso Lasso
Line Cut Tool Viivaleikkaustyökalu
Line Graph Tool Viivakaaviotyökalu
@@ -2954,6 +2956,9 @@ digits Malayalam Malajalam
Show smooth color wheel Näytä liukuva väriympyrä
Show segmented color wheel Näytä segmentoitu väriympyrä
Show color bars Näytä väripalkit
Add Color Tool Lisää väri -työkalu
Remove Color Tool Poista väri -työkalu
Remove Color Poista väri
Find the selected colors in the artwork Etsi valitut värit kuvituksesta
Harmony Rules Harmoniasäännöt
Keep this row's colors (exclude) Säilytä tämän rivin värit (jätä pois)
Can't render this file because it contains an unexpected character in line 2 and column 73.
File diff suppressed because it is too large Load Diff
+5
View File
@@ -2735,6 +2735,8 @@
Polygon બહુકોણ
Polygon Properties: બહુકોણના ગુણધર્મો:
Polygon Tool બહુકોણ ટૂલ
Polygonal Lasso બહુકોણીય લાસો
Polygonal Lasso Tool બહુકોણીય લાસો ટૂલ
Portrait પોટ્રેટ
Portuguese પોર્ટુગીઝ
Position સ્થિતિ
@@ -3605,6 +3607,9 @@
Show all plates બધી પ્લેટ બતાવો
Show axis અક્ષ બતાવો
Show color bars રંગ બાર બતાવો
Add Color Tool રંગ ઉમેરો સાધન
Remove Color Tool રંગ દૂર કરો સાધન
Remove Color રંગ દૂર કરો
Find the selected colors in the artwork પસંદ કરેલા રંગો આર્ટવર્કમાં શોધો
Show handles when multiple anchors are selected બહુવિધ એન્કર પસંદ હોય ત્યારે હૅન્ડલ બતાવો
Show in Folder ફોલ્ડરમાં બતાવો
Can't render this file because it contains an unexpected character in line 72 and column 5.
+5
View File
@@ -3682,6 +3682,8 @@ antiAlias Sharp शार्प
Polygon बहुभुज
Polygon Properties: बहुभुज प्रॉपर्टीज़:
Polygon Tool पॉलीगोन टूल
Polygonal Lasso बहुभुज लैस्सो
Polygonal Lasso Tool बहुभुज लैस्सो टूल
Portrait पोर्ट्रेट
Portrait (flipped) पोर्ट्रेट (फ्लिप)
Portuguese पुर्तगाली
@@ -4685,6 +4687,9 @@ antiAlias Sharp शार्प
Show Center Mark शो सेंटर मार्क
Show Code कोड दिखाएं
Show color bars रंग सलाखों दिखाएँ
Add Color Tool रंग जोड़ें टूल
Remove Color Tool रंग हटाएँ टूल
Remove Color रंग हटाएँ
Find the selected colors in the artwork चयनित रंगों को आर्टवर्क में खोजें
Show Color Groups रंग समूह दिखाएँ
Show Color Swatches रंग स्वॉचेस दिखाएँ
Can't render this file because it is too large.
+5
View File
@@ -1972,6 +1972,9 @@ file-filter Templates Sablonok
Show smooth color wheel Folytonos színkör megjelenítése
Show segmented color wheel Szegmentált színkör megjelenítése
Show color bars Színsávok megjelenítése
Add Color Tool Szín hozzáadása eszköz
Remove Color Tool Szín eltávolítása eszköz
Remove Color Szín eltávolítása
Find the selected colors in the artwork A kijelölt színek keresése a grafikában
Harmony Sets Harmóniakészletek
HDTV 1080p HDTV 1080p
@@ -2372,6 +2375,8 @@ file-filter Templates Sablonok
Lasso Tool Lasszó
Enclosing Lasso Tool Körülzáró lasszó
Enclosing Lasso Körülzáró lasszó
Polygonal Lasso Tool Sokszöglasszó
Polygonal Lasso Sokszöglasszó
Last Utolsó
Last commit Utolsó commit
Last Effect: {name} Legutóbbi effektus: {name}
Can't render this file because it is too large.
+5
View File
@@ -1340,6 +1340,8 @@ lighting Light Cahaya
Lasso Tool Alat lasso
Enclosing Lasso Tool Alat laso pengeliling
Enclosing Lasso Laso pengeliling
Polygonal Lasso Tool Alat laso poligonal
Polygonal Lasso Laso poligonal
Lasso Lasso
Line Cut Tool Alat potong garis
Line Graph Tool Alat grafik garis
@@ -2735,6 +2737,9 @@ digits Malayalam Malayalam
Show smooth color wheel Tampilkan roda warna halus
Show segmented color wheel Tampilkan roda warna bersegmen
Show color bars Tampilkan bilah warna
Add Color Tool Alat Tambah Warna
Remove Color Tool Alat Hapus Warna
Remove Color Hapus Warna
Find the selected colors in the artwork Temukan warna yang dipilih di karya seni
Harmony Rules Aturan harmoni
Keep this row's colors (exclude) Pertahankan warna baris ini (kecualikan)
Can't render this file because it contains an unexpected character in line 2490 and column 5.
+5
View File
@@ -1588,6 +1588,9 @@ file-filter Templates Modelli
Show smooth color wheel Mostra ruota dei colori continua
Show segmented color wheel Mostra ruota dei colori segmentata
Show color bars Mostra barre di colore
Add Color Tool Strumento Aggiungi colore
Remove Color Tool Strumento Rimuovi colore
Remove Color Rimuovi colore
Find the selected colors in the artwork Trova i colori selezionati nella grafica
Harmony Sets Gruppi di armonia
Height Altezza
@@ -1939,6 +1942,8 @@ file-filter Templates Modelli
Lasso Tool Strumento Lazo
Enclosing Lasso Tool Strumento Lazo di inclusione
Enclosing Lasso Lazo di inclusione
Polygonal Lasso Tool Strumento Lazo poligonale
Polygonal Lasso Lazo poligonale
Last Effect: {name} Ultimo effetto: {name}
Last Effect: {} Ultimo effetto: {}
Last Effect… Ultimo effetto…
Can't render this file because it is too large.
+5
View File
@@ -1959,6 +1959,9 @@ antiAlias Sharp シャープ
Show smooth color wheel 滑らかなカラーホイールを表示
Show segmented color wheel 分割カラーホイールを表示
Show color bars カラーバーを表示
Add Color Tool カラー追加ツール
Remove Color Tool カラー削除ツール
Remove Color カラーを削除
Find the selected colors in the artwork 選択したカラーをアートワーク内で検索
Height 高さ
Height: 高さ:
@@ -2230,6 +2233,8 @@ antiAlias Sharp シャープ
Lasso Tool なげなわツール
Enclosing Lasso Tool 囲みなげなわツール
Enclosing Lasso 囲みなげなわ
Polygonal Lasso Tool 多角形なげなわツール
Polygonal Lasso 多角形なげなわ
Last Effect: {name} 最後の効果:{name}
Last Page 最後のページ
Layer Options… レイヤーオプション…
Can't render this file because it is too large.
+5
View File
@@ -3376,6 +3376,8 @@ lighting Light სინათლე
Lasso Tool ლასოს ხელსაწყო
Enclosing Lasso Tool შემომსაზღვრელი ლასოს ხელსაწყო
Enclosing Lasso შემომსაზღვრელი ლასო
Polygonal Lasso Tool მრავალკუთხა ლასოს ხელსაწყო
Polygonal Lasso მრავალკუთხა ლასო
Line Cut Tool ხაზით ჭრის ხელსაწყო
Line Graph Tool ხაზოვანი დიაგრამის ხელსაწყო
Line Segment Tool ხაზის სეგმენტის ხელსაწყო
@@ -4786,6 +4788,9 @@ digits Malayalam მალაიალამური
Show smooth color wheel გლუვი ფერთა წრის ჩვენება
Show segmented color wheel სეგმენტირებული ფერთა წრის ჩვენება
Show color bars ფერთა ზოლების ჩვენება
Add Color Tool ფერის დამატების ხელსაწყო
Remove Color Tool ფერის წაშლის ხელსაწყო
Remove Color ფერის წაშლა
Find the selected colors in the artwork არჩეული ფერების პოვნა ნახატში
Keep this row's colors (exclude) ამ სტრიქონის ფერების შენარჩუნება (გამორიცხვა)
Limit to Library: ბიბლიოთეკით შეზღუდვა:
Can't render this file because it is too large.
+5
View File
@@ -1949,6 +1949,9 @@ antiAlias Sharp 날카롭게
Show smooth color wheel 부드러운 색상환 표시
Show segmented color wheel 분할 색상환 표시
Show color bars 색상 막대 표시
Add Color Tool 색상 추가 도구
Remove Color Tool 색상 제거 도구
Remove Color 색상 제거
Find the selected colors in the artwork 선택한 색상을 아트웍에서 찾기
Height 높이
Height: 높이:
@@ -2220,6 +2223,8 @@ antiAlias Sharp 날카롭게
Lasso Tool 올가미 도구
Enclosing Lasso Tool 둘러싸기 올가미 도구
Enclosing Lasso 둘러싸기 올가미
Polygonal Lasso Tool 다각형 올가미 도구
Polygonal Lasso 다각형 올가미
Last Effect: {name} 마지막 효과: {name}
Last Page 마지막 페이지
Layer Options… 레이어 옵션…
Can't render this file because it is too large.
+5
View File
@@ -1908,6 +1908,8 @@ lighting Light Licht
Lasso Tool Lasso-gereedschap
Enclosing Lasso Tool Omsluitend lassogereedschap
Enclosing Lasso Omsluitende lasso
Polygonal Lasso Tool Veelhoekig lassogereedschap
Polygonal Lasso Veelhoekige lasso
Lasso Lasso
Line Cut Tool Lijnknip-gereedschap
Line Graph Tool Lijndiagram-gereedschap
@@ -3352,6 +3354,9 @@ digits Malayalam Malayalam
Show smooth color wheel Vloeiend kleurenwiel tonen
Show segmented color wheel Gesegmenteerd kleurenwiel tonen
Show color bars Kleurbalken tonen
Add Color Tool Gereedschap Kleur toevoegen
Remove Color Tool Gereedschap Kleur verwijderen
Remove Color Kleur verwijderen
Find the selected colors in the artwork De geselecteerde kleuren zoeken in de artwork
Harmony Rules Harmonieregels
Keep this row's colors (exclude) De kleuren van deze rij behouden (uitsluiten)
Can't render this file because it is too large.
+5
View File
@@ -1362,6 +1362,8 @@ lighting Light Światło
Lasso Tool Narzędzie Lasso
Enclosing Lasso Tool Narzędzie lassa obejmującego
Enclosing Lasso Lasso obejmujące
Polygonal Lasso Tool Narzędzie lassa wielokątnego
Polygonal Lasso Lasso wielokątne
Line Cut Tool Narzędzie Cięcie linią
Line Graph Tool Narzędzie Wykres liniowy
Line Segment Tool Narzędzie Odcinek
@@ -2920,6 +2922,9 @@ digits Malayalam Malajalam
Show smooth color wheel Pokaż płynne koło kolorów
Show segmented color wheel Pokaż segmentowe koło kolorów
Show color bars Pokaż paski kolorów
Add Color Tool Narzędzie Dodaj kolor
Remove Color Tool Narzędzie Usuń kolor
Remove Color Usuń kolor
Find the selected colors in the artwork Znajdź zaznaczone kolory w kompozycji
Keep this row's colors (exclude) Zachowaj kolory tego wiersza (wyklucz)
Limit to Library: Ogranicz do biblioteki:
Can't render this file because it is too large.
+5
View File
@@ -1354,6 +1354,9 @@ antiAlias Sharp Nítido
Show smooth color wheel Mostrar roda de cores contínua
Show segmented color wheel Mostrar roda de cores segmentada
Show color bars Mostrar barras de cores
Add Color Tool Ferramenta Adicionar cor
Remove Color Tool Ferramenta Remover cor
Remove Color Remover cor
Find the selected colors in the artwork Localizar as cores selecionadas na arte
Harmony Sets Conjuntos de Harmonia
Height Altura
@@ -1603,6 +1606,8 @@ antiAlias Sharp Nítido
Lasso Tool Ferramenta Laço
Enclosing Lasso Tool Ferramenta Laço envolvente
Enclosing Lasso Laço envolvente
Polygonal Lasso Tool Ferramenta Laço poligonal
Polygonal Lasso Laço poligonal
Last Effect: {name} Último Efeito: {name}
Last Effect… Último Efeito…
Last Page Última Página
Can't render this file because it is too large.
+5
View File
@@ -1579,6 +1579,9 @@ file-filter Templates Шаблоны
Show smooth color wheel Показать плавный цветовой круг
Show segmented color wheel Показать сегментированный цветовой круг
Show color bars Показать цветовые полосы
Add Color Tool Инструмент «Добавить цвет»
Remove Color Tool Инструмент «Удалить цвет»
Remove Color Удалить цвет
Find the selected colors in the artwork Найти выбранные цвета в рисунке
Harmony Sets Наборы гармонии
Height Высота
@@ -1930,6 +1933,8 @@ file-filter Templates Шаблоны
Lasso Tool Инструмент «Лассо»
Enclosing Lasso Tool Инструмент «Охватывающее лассо»
Enclosing Lasso Охватывающее лассо
Polygonal Lasso Tool Инструмент «Многоугольное лассо»
Polygonal Lasso Многоугольное лассо
Last Effect: {name} Последний эффект: {name}
Last Effect: {} Последний эффект: {}
Last Effect… Последний эффект…
Can't render this file because it is too large.
+5
View File
@@ -1522,6 +1522,9 @@ font-technology Variable Variabla
Show smooth color wheel Visa steglöst färghjul
Show segmented color wheel Visa segmenterat färghjul
Show color bars Visa färgstaplar
Add Color Tool Verktyget Lägg till färg
Remove Color Tool Verktyget Ta bort färg
Remove Color Ta bort färg
Find the selected colors in the artwork Hitta de markerade färgerna i teckningen
Harmony Sets Harmoniuppsättningar
Height Höjd
@@ -1852,6 +1855,8 @@ font-technology Variable Variabla
Lasso Tool Lassoverktyg
Enclosing Lasso Tool Omslutande lassoverktyg
Enclosing Lasso Omslutande lasso
Polygonal Lasso Tool Polygonlassoverktyg
Polygonal Lasso Polygonlasso
Last Effect: {name} Senaste effekten: {name}
Last Effect: {} Senaste effekten: {}
Last Effect… Senaste effekten…
Can't render this file because it is too large.
+45 -1
View File
@@ -1931,6 +1931,50 @@ fn georgian_rows_have_no_mtavruli() {
assert!(caps.is_empty(), "Mtavruli in ka.tsv: {caps:?}");
}
/// French rows follow the typography fr.tsv's header sets: a no-break space before : ; ? ! and inside
/// « », and the typographic apostrophe ’ in elisions. Text in backticks is code and is not checked, and
/// a straight apostrophe inside double quotes is a literal value.
#[test]
fn french_catalog_uses_nonbreaking_prose_punctuation() {
let (entries, _) = parse_entries(fr().0.source);
let letter = |c: Option<char>| c.is_some_and(char::is_alphabetic);
let mut bad = Vec::new();
for (ctx, src, tr) in &entries {
let mut code = false;
let prose: Vec<char> = tr
.chars()
.map(|c| {
if c == '`' {
code = !code;
}
if code || c == '`' { '\0' } else { c }
})
.collect();
let mut quoted = false;
for (i, &c) in prose.iter().enumerate() {
let prev = i.checked_sub(1).map(|j| prose[j]);
let next = prose.get(i + 1).copied();
if c == '"' {
quoted = !quoted;
}
let fault = match c {
':' | ';' | '?' | '!' if prev == Some(' ') => "has an ordinary space before it",
';' | '?' | '!' if letter(prev) && next.is_none_or(|n| n == ' ') => "has no space before it",
'«' if next == Some(' ') => "has an ordinary space after it",
'»' if prev == Some(' ') => "has an ordinary space before it",
'\'' if !quoted && letter(prev) && letter(next) => "is a straight apostrophe where an elision takes ’",
_ => continue,
};
bad.push(format!("{ctx}\t{src}: `{c}` {fault}"));
}
}
assert!(bad.is_empty(), "{} French spacing faults:\n{}", bad.len(), bad.join("\n"));
}
fn fr() -> Lang {
Lang::from_code("fr").expect("fr registered")
}
fn de() -> Lang {
Lang::from_code("de").expect("de registered")
}
@@ -2750,7 +2794,7 @@ fn plugin_errors_translate_with_their_values() {
}
assert_eq!(message(de(), &errors[1].0), "Plug-in-Manifest: das Manifest ist 65537 Byte groß (Grenze 65536)");
let fr = Lang::from_code("fr").expect("registered");
assert!(message(fr, &errors[3].0).ends_with(r#"attendu : {"objects": [...]}"#), "{}", message(fr, &errors[3].0));
assert!(message(fr, &errors[3].0).ends_with("attendu\u{a0}: {\"objects\": [...]}"), "{}", message(fr, &errors[3].0));
}
/// The reasons the plug-in host puts inside its errors (what is wrong with a parameter's spec or
+5
View File
@@ -1479,6 +1479,9 @@ font-technology Variable Değişken
Show smooth color wheel Kesintisiz renk tekerleğini göster
Show segmented color wheel Bölümlü renk tekerleğini göster
Show color bars Renk çubuklarını göster
Add Color Tool Renk Ekle aracı
Remove Color Tool Renk Kaldır aracı
Remove Color Rengi kaldır
Find the selected colors in the artwork Seçili renkleri resimde bul
Harmony Sets Armoni Setleri
Height Yükseklik
@@ -1725,6 +1728,8 @@ font-technology Variable Değişken
Lasso Tool Kement Aracı
Enclosing Lasso Tool Çevreleyen Kement Aracı
Enclosing Lasso Çevreleyen Kement
Polygonal Lasso Tool Çokgen Kement Aracı
Polygonal Lasso Çokgen Kement
Last Effect: {name} Son Etki: {name}
Last Effect: {} Son Etki: {}
Last Effect… Son Etki…
Can't render this file because it is too large.
+5
View File
@@ -1582,6 +1582,9 @@ file-filter Templates Шаблони
Show smooth color wheel Показати плавне колірне коло
Show segmented color wheel Показати сегментоване колірне коло
Show color bars Показати колірні смуги
Add Color Tool Інструмент «Додати колір»
Remove Color Tool Інструмент «Вилучити колір»
Remove Color Вилучити колір
Find the selected colors in the artwork Знайти вибрані кольори в малюнку
Harmony Sets Набори гармонії
Height Висота
@@ -1933,6 +1936,8 @@ file-filter Templates Шаблони
Lasso Tool Інструмент «Ласо»
Enclosing Lasso Tool Інструмент «Охоплювальне ласо»
Enclosing Lasso Охоплювальне ласо
Polygonal Lasso Tool Інструмент «Багатокутне ласо»
Polygonal Lasso Багатокутне ласо
Last Effect: {name} Останній ефект: {name}
Last Effect: {} Останній ефект: {}
Last Effect… Останній ефект…
Can't render this file because it is too large.
+5
View File
@@ -1819,6 +1819,9 @@ file-filter Templates Mẫu
Show smooth color wheel Hiện bánh xe màu liền mạch
Show segmented color wheel Hiện bánh xe màu phân đoạn
Show color bars Hiện các thanh màu
Add Color Tool Công cụ Thêm màu
Remove Color Tool Công cụ Xóa màu
Remove Color Xóa màu
Find the selected colors in the artwork Tìm các màu đã chọn trong tác phẩm
Harmony Sets Bộ hài hòa màu
Height Chiều cao
@@ -2214,6 +2217,8 @@ digits Hindi Hindi
Lasso Tool Công cụ Lasso
Enclosing Lasso Tool Công cụ Lasso bao quanh
Enclosing Lasso Lasso bao quanh
Polygonal Lasso Tool Công cụ Lasso đa giác
Polygonal Lasso Lasso đa giác
Last Cuối cùng
Last commit Commit cuối cùng
Last Effect: {name} Hiệu ứng vừa dùng: {name}
Can't render this file because it contains an unexpected character in line 205 and column 5.
+5
View File
@@ -1516,6 +1516,9 @@ file-filter Templates 模板
Show smooth color wheel 显示平滑色轮
Show segmented color wheel 显示分段色轮
Show color bars 显示颜色条
Add Color Tool 添加颜色工具
Remove Color Tool 删除颜色工具
Remove Color 删除颜色
Find the selected colors in the artwork 在图稿中查找所选颜色
Harmony Sets 色彩调和组
Height 高度
@@ -1815,6 +1818,8 @@ file-filter Templates 模板
Lasso Tool 套索工具
Enclosing Lasso Tool 包围套索工具
Enclosing Lasso 包围套索
Polygonal Lasso Tool 多边形套索工具
Polygonal Lasso 多边形套索
Last Effect: {name} 最后一次效果:{name}
Last Effect: {} 上次效果:{}
Last Effect… 上次效果…
Can't render this file because it is too large.
+5
View File
@@ -1553,6 +1553,9 @@ file-filter Templates 範本
Show smooth color wheel 顯示平滑色輪
Show segmented color wheel 顯示分段色輪
Show color bars 顯示顏色條
Add Color Tool 新增顏色工具
Remove Color Tool 移除顏色工具
Remove Color 移除顏色
Find the selected colors in the artwork 在圖稿中尋找所選顏色
Harmony Sets 色彩調和組
Height 高度
@@ -3046,6 +3049,8 @@ liquify-list-end {0}, {1} {0}和{1}
Lasso Tool 套索工具
Enclosing Lasso Tool 包圍套索工具
Enclosing Lasso 包圍套索
Polygonal Lasso Tool 多邊形套索工具
Polygonal Lasso 多邊形套索
Last Effect: {name} 最後一次效果:{name}
Last Effect: {} 上次效果:{}
Last Effect… 最後一次效果…
Can't render this file because it is too large.
+3 -1
View File
@@ -73,7 +73,9 @@ pub fn export(app: &mut VectorcraftApp, format: Option<&str>, path: Option<Strin
// A `.ai` file names the view's active artboard.
remember_active_artboard(app);
let st = app.session.active().ok_or("no document")?;
fileio::check_linked_scripts("file.exportAs", f.id, st).map_err(|e| e.to_string())?;
// With a saved PDF preset written out, as the encoder reads it.
let checked = fileio::pdf::expand_preset(&app.session, "file.exportAs", params).unwrap_or(std::borrow::Cow::Borrowed(params));
fileio::check_linked_scripts("file.exportAs", f.id, st, &checked).map_err(|e| e.to_string())?;
let doc = if selection {
std::sync::Arc::new(fileio::selection_doc(st, "document.exportSelection", f.id == "txt").map_err(|e| e.to_string())?.0)
} else {
+1 -1
View File
@@ -1391,7 +1391,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"file.exportAs",
"Export As…",
"",
"{format?, useArtboards?, range?} opens Export As (then the format's options); with {path, …document.export options} writes the file(s) → {path, warnings, files?}; exportSelection: true writes the selection alone, cropped to it, as document.exportSelection writes it (artboard options are not used); under automation read roots, an SVG or SVGZ is refused while the document links a JavaScript file outside them, or while the file would name a linked image's file outside them, as document.export refuses it",
"{format?, useArtboards?, range?} opens Export As (then the format's options); with {path, …document.export options} writes the file(s) → {path, warnings, files?}; exportSelection: true writes the selection alone, cropped to it, as document.exportSelection writes it (artboard options are not used); under automation read roots, an SVG or SVGZ, or a file that carries the native document, is refused while the document links a JavaScript file outside them, or while the file would name a linked image's file outside them, as document.export refuses it",
),
(
"ui.fileInfoDialog",
+42
View File
@@ -1255,6 +1255,48 @@ fn enclosing_lasso_escape_cancels_and_q_returns_to_anchor_lasso() {
assert_eq!(app.session.tool_id(), "lasso");
}
/// While a Polygonal Lasso loop is open, Backspace and Delete remove its last vertex instead of
/// deleting the selected art, Enter closes it, and Escape drops it and leaves the selection.
#[test]
fn polygonal_lasso_takes_backspace_delete_enter_and_escape_while_a_loop_is_open() {
use vectorcraft_doc::NodeId;
use vectorcraft_tools::{PointerEvent, PointerKind};
let mut app = VectorcraftApp::new(vectorcraft_engine::Session::new(), Default::default());
crate::shortcut_editor::sync(&app.ui);
app.run("file.new", json!({"width": 400, "height": 300})).unwrap();
let id = NodeId(app.run("shape.rectangle", json!({"x": 100, "y": 100, "width": 100, "height": 100})).unwrap()["id"].as_u64().unwrap());
app.run("select.set", json!({"ids": [id.0]})).unwrap();
app.select_tool(vectorcraft_tools::addons::polygonal_lasso::ID);
let view = app.view_info();
let click = |app: &mut VectorcraftApp, x: f64, y: f64| {
app.session.pointer(&PointerEvent::new(PointerKind::Down, x, y), view).unwrap();
app.session.pointer(&PointerEvent::new(PointerKind::Up, x, y), view).unwrap();
};
for (x, y) in [(80.0, 80.0), (140.0, 80.0), (300.0, 300.0)] {
click(&mut app, x, y);
}
frame(&mut app, press(Key::Backspace, Modifiers::NONE));
assert!(app.session.active().unwrap().doc.node(id).is_some(), "Backspace leaves the selected art");
click(&mut app, 300.0, 300.0);
frame(&mut app, press(Key::Delete, Modifiers::NONE));
assert!(app.session.active().unwrap().doc.node(id).is_some(), "Delete leaves the selected art");
assert!(app.session.tool_ends_on_escape(view));
frame(&mut app, press(Key::Escape, Modifiers::NONE));
assert!(!app.session.tool_ends_on_escape(view));
assert_eq!(app.session.active().unwrap().selection.objects, vec![id]);
for (x, y) in [(80.0, 80.0), (140.0, 80.0), (300.0, 300.0)] {
click(&mut app, x, y);
}
frame(&mut app, press(Key::Backspace, Modifiers::NONE));
click(&mut app, 80.0, 140.0);
frame(&mut app, press(Key::Enter, Modifiers::NONE));
assert!(!app.session.tool_ends_on_escape(view));
let sel = &app.session.active().unwrap().selection;
assert_eq!(sel.objects, vec![id]);
assert_eq!(sel.anchors.get(&id).map(|a| a.len()), Some(1), "only the corner inside the loop");
}
/// Binds Show Grid to `chord`, or with `None` leaves every command its default shortcut.
fn bind_grid(app: &mut VectorcraftApp, chord: Option<&str>) {
app.ui.shortcut_overrides.clear();
+33
View File
@@ -272,6 +272,39 @@ fn control_svg_export_refuses_a_linked_javascript_file_outside_the_read_root() {
let _ = std::fs::remove_dir_all(base);
}
/// `app.export`, and `file.exportAs` run as a command, write no file that carries the native
/// document (a PDF with Preserve Editing, a native file, a `.ai` or EPS file) of a document that
/// links a JavaScript file outside the read root, and the error names no file or folder; a PDF
/// without Preserve Editing is written, and the person at the keyboard exports the native file.
#[test]
fn control_native_export_refuses_a_linked_javascript_file_outside_the_read_root() {
let (mut app, tx, base) = confined("native-script");
app.run("file.new", json!({"width": 100, "height": 50})).unwrap();
app.run("shape.rectangle", json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap();
let script = s(base.join("outside/menu.js"));
app.run("svgInteractivity.addFile", json!({"file": script})).unwrap();
let out = |name: &str| s(base.join("out").join(name));
for (method, params) in [
("app.export", json!({"path": out("a.pdf"), "wait": true})),
("app.export", json!({"path": out("a.ai"), "wait": true})),
("app.export", json!({"format": "eps"})),
("engine.execute", json!({"command": "file.exportAs", "params": {"path": out("a.vectorcraft"), "format": "vectorcraft"}})),
] {
let r = request(&mut app, &tx, method, params.clone());
let e = r["error"].as_str().unwrap_or_default();
assert!(e.contains("a linked JavaScript file is outside the read roots"), "{method} {params}: {r}");
assert!(!e.contains("menu.js") && !e.contains(&s(base.clone())), "{method} {params}: {r}");
}
assert_eq!(std::fs::read_dir(base.join("out")).unwrap().count(), 0, "nothing written");
let r = request(&mut app, &tx, "app.export", json!({"path": out("b.pdf"), "preserveEditing": false, "wait": true}));
assert_eq!(r["ok"], true, "{r}");
// The person at the keyboard isn't confined.
app.run("file.exportAs", json!({"path": out("a.vectorcraft"), "format": "vectorcraft"})).unwrap();
let native = vectorcraft_format::load(&std::fs::read(out("a.vectorcraft")).unwrap()).unwrap();
assert_eq!(native.svg_scripts, [script]);
let _ = std::fs::remove_dir_all(base);
}
/// `app.export`, and `file.exportAs` run as a command, write no SVG that would name a linked
/// image's file outside the read root (Images: Link, Preserve Editing Capabilities), and the error
/// names no file or folder. Embedded pixels are written; the person at the keyboard exports the
+168 -1
View File
@@ -1,7 +1,7 @@
//! Recolor Artwork (M3.78) and Edit or Apply Color Group (M3.79), drawn headlessly.
use egui::{Event, Modifiers, PointerButton, Pos2, Rect, vec2};
use egui_kittest::kittest::Queryable;
use egui_kittest::kittest::{NodeT, Queryable};
use serde_json::{Value, json};
use vectorcraft_color::Color;
use vectorcraft_color::recolor::ColorKey;
@@ -1172,3 +1172,170 @@ fn color_bars_scroll_and_show_when_nothing_is_recolored() {
assert!(h.query_by_role_and_label(egui::accesskit::Role::Button, "Color 1").is_none());
let _ = h.get_by_label("No colors to recolor (preserved colors are left out).");
}
/// Where the Edit tab's wheel draws a marker for hue `hue` and saturation `s`.
fn wheel_at(h: &egui_kittest::Harness<'_, VectorcraftApp>, hue: f32, s: f32) -> Pos2 {
let c = widget_of_size(h, vec2(220.0, 220.0)).center();
c + vec2(hue.to_radians().cos(), -hue.to_radians().sin()) * 100.0 * s
}
/// Clicks the Edit tab's button named `name` and lets the dialog settle.
fn click_button(h: &mut egui_kittest::Harness<'_, VectorcraftApp>, name: &str) {
h.get_by_role_and_label(egui::accesskit::Role::Button, name).click();
h.run_steps(3);
}
/// The Add Color tool: a click on the smooth wheel adds the hue and saturation under it, at the
/// base color's brightness, as a row with no current colors that becomes the selected row; the art
/// keeps its colors, and the Assign tab shows the row without current colors. A second click on the
/// button turns the tool off, and a click on the wheel then adds nothing.
#[test]
fn the_add_color_tool_adds_a_row_with_no_current_colors() {
let mut h = edit_harness(&["rgb 200 100 100", "rgb 100 200 200"]);
set(h.state_mut(), "__sel", json!([0]));
h.run_steps(4);
let (fills_before, v) = (fills(h.state()), new_hsb(h.state())[0][2]);
click_button(&mut h, "Add Color Tool");
assert_eq!(field(h.state(), "wheelTool"), json!("add"));
let at = wheel_at(&h, 120.0, 0.5);
h.input_mut().events.extend(press(at, 1));
h.run_steps(3);
let rows = field(h.state(), "rows");
assert_eq!(rows.as_array().unwrap().len(), 3, "a new row: {rows}");
assert_eq!(rows[2]["from"], json!([]), "with no current colors");
assert_eq!(rows[2]["added"], json!(true), "marked as an added color");
let [hue, s, b] = new_hsb(h.state())[2];
assert!((hue - 120.0).abs() < 1.0 && (s - 0.5).abs() < 0.01 && (b - v).abs() < 0.01, "{:?}", [hue, s, b]);
assert_eq!(field(h.state(), "__sel"), json!([2]), "the new color is selected");
assert_eq!(fills(h.state()), fills_before, "a color with no current colors recolors no art");
// A second click adds another color; the tool stays on.
let next = wheel_at(&h, 240.0, 0.75);
h.input_mut().events.extend(press(next, 1));
h.run_steps(3);
assert_eq!(field(h.state(), "rows").as_array().unwrap().len(), 4);
click_button(&mut h, "Add Color Tool");
assert_eq!(field(h.state(), "wheelTool"), Value::Null, "a second click turns the tool off");
h.input_mut().events.extend(press(at, 1));
h.run_steps(3);
assert_eq!(field(h.state(), "rows").as_array().unwrap().len(), 4, "without the tool a click adds nothing");
assert_eq!(field(h.state(), "__sel"), json!([2]), "it selects the marker clicked");
set(h.state_mut(), "tab", json!("assign"));
h.run_steps(3);
let _ = h.get_by_label("Current Colors (2)");
assert!(h.query_by_label("Color 4").is_some(), "the Assign tab has a row for each added color");
let app = h.state_mut();
let undo = app.session.doc().unwrap().history.undo.len();
dialogs::confirm(app).unwrap();
assert_eq!(fills(app), fills_before, "OK leaves the art's colors");
assert_eq!(app.session.doc().unwrap().history.undo.len(), undo, "and records no undo step");
}
/// On the segmented wheel the Add Color tool adds the patch's color. Opened on a color group without
/// art, OK adds the added color to the group, as one undo step.
#[test]
fn an_added_color_joins_the_color_group() {
let app = app();
let before = group_keys(&app, "Brights");
let mut h = assign_harness(app, json!({"group": "Brights"}));
set(h.state_mut(), "tab", json!("edit"));
h.run_steps(4);
show_display(&mut h, "Show segmented color wheel");
let v = new_hsb(h.state())[0][2];
click_button(&mut h, "Add Color Tool");
let patch = wheel_at(&h, 187.0, 0.95);
h.input_mut().events.extend(press(patch, 1));
h.run_steps(3);
let added = field(h.state(), "rows").as_array().unwrap().last().unwrap()["to"].clone();
let [hue, s, b] = vectorcraft_engine::cmd::color_value(&added).unwrap().to_hsb();
assert!((hue - 180.0).abs() < 1.0 && (s - 0.9).abs() < 0.01 && (b - v).abs() < 0.01, "the patch's color: {:?}", [hue, s, b]);
let app = h.state_mut();
let undo = app.session.doc().unwrap().history.undo.len();
dialogs::confirm(app).unwrap();
let mut want = before.clone();
want.push(added);
assert_eq!(group_keys(app, "Brights"), want);
assert_eq!(app.session.doc().unwrap().history.undo.len(), undo + 1, "one undo step");
}
/// The Remove Color tool: a click on the base color's marker removes nothing; a click on another
/// marker leaves its row of art's colors with no new color, so OK leaves that art's colors as they
/// were while the other rows recolor theirs. The tools are off for the color bars.
#[test]
fn the_remove_color_tool_removes_a_marker_but_not_the_base_colors() {
let mut h = edit_harness(&["rgb 200 100 100", "rgb 100 200 200", "rgb 20 160 20"]);
let fills_before = fills(h.state());
let mut rows = field(h.state(), "rows");
let tos = ["rgb 255 0 0", "rgb 0 255 0", "rgb 0 0 255"];
for (r, to) in rows.as_array_mut().unwrap().iter_mut().zip(tos) {
r["to"] = json!(to);
}
set(h.state_mut(), "rows", rows.clone());
set(h.state_mut(), "linked", json!(false));
set(h.state_mut(), "__sel", json!([0]));
h.run_steps(4);
click_button(&mut h, "Remove Color Tool");
assert_eq!(field(h.state(), "wheelTool"), json!("remove"));
let (red, green) = (wheel_at(&h, 0.0, 1.0), wheel_at(&h, 120.0, 1.0));
h.input_mut().events.extend(press(red, 1));
h.run_steps(3);
assert_eq!(field(h.state(), "rows"), rows, "the base color stays");
h.input_mut().events.extend(press(green, 1));
h.run_steps(3);
let now = field(h.state(), "rows");
assert_eq!(now.as_array().unwrap().len(), 3, "the row of art's colors stays");
assert_eq!((&now[0], &now[1]["to"], &now[2]), (&rows[0], &Value::Null, &rows[2]), "with no new color: {now}");
assert_eq!(field(h.state(), "__sel"), json!([0]), "the base color stays selected");
show_display(&mut h, "Show color bars");
let tool = h.get_by_role_and_label(egui::accesskit::Role::Button, "Remove Color Tool");
assert!(tool.accesskit_node().is_disabled(), "the tools are for the wheels");
let kept = rows[1]["from"][0].clone();
let app = h.state_mut();
dialogs::confirm(app).unwrap();
let after = fills(app);
for (b, a) in fills_before.iter().zip(&after) {
let was = json!(ColorKey::of(&b.unwrap()).to_string());
if was == kept {
assert_eq!(a, b, "the art of the removed color keeps it");
} else {
assert_ne!(a, b, "the other art takes its new color");
}
}
}
/// Right-clicks the color bar named `name`.
fn right_click_bar(h: &mut egui_kittest::Harness<'_, VectorcraftApp>, name: &str) {
let at = h.get_by_role_and_label(egui::accesskit::Role::Button, name).rect().center();
h.event(Event::PointerMoved(at));
h.event(Event::PointerButton { pos: at, button: PointerButton::Secondary, pressed: true, modifiers: Modifiers::NONE });
h.event(Event::PointerButton { pos: at, button: PointerButton::Secondary, pressed: false, modifiers: Modifiers::NONE });
h.run_steps(2);
}
/// A color bar's right-click menu has Remove Color: off for the base color's bar; on an added
/// color's bar it removes the row, and on a bar of art's colors it leaves the row with no new color
/// and no bar.
#[test]
fn a_color_bars_menu_removes_its_color() {
let mut h = edit_harness(&["#ff0000", "#0000ff", "#00ff00"]);
let mut rows = field(h.state(), "rows");
rows.as_array_mut().unwrap().push(json!({"from": [], "to": "rgb 10 20 30", "added": true}));
set(h.state_mut(), "rows", rows.clone());
set(h.state_mut(), "__sel", json!([0]));
h.run_steps(4);
show_display(&mut h, "Show color bars");
right_click_bar(&mut h, "Color 1");
assert!(h.get_by_label(" Remove Color").accesskit_node().is_disabled(), "the base color can't be removed");
h.key_press(egui::Key::Escape);
h.run_steps(2);
right_click_bar(&mut h, "Color 4");
h.get_by_label(" Remove Color").click();
h.run_steps(3);
assert_eq!(field(h.state(), "rows").as_array().unwrap()[..], rows.as_array().unwrap()[..3], "the added row goes");
right_click_bar(&mut h, "Color 2");
h.get_by_label(" Remove Color").click();
h.run_steps(3);
let now = field(h.state(), "rows");
assert_eq!((&now[1]["from"], &now[1]["to"]), (&rows[1]["from"], &Value::Null), "{now}");
assert!(h.query_by_role_and_label(egui::accesskit::Role::Button, "Color 2").is_none(), "its bar goes");
assert_eq!(field(h.state(), "__sel"), json!([0]));
}
+4 -2
View File
@@ -142,7 +142,8 @@ pub const FIRST_DRAWING_TOOL: &str = "pencil";
/// A tool of selection mode: one that selects objects or parts of them.
fn selects(id: &str) -> bool {
vectorcraft_tools::catalog::is_selection_tool(id) || matches!(id, "magicWand" | "lasso" | "perspectiveSelection")
vectorcraft_tools::catalog::is_selection_tool(id)
|| matches!(id, "magicWand" | "lasso" | "enclosingLasso" | "polygonalLasso" | "perspectiveSelection")
}
/// A tool of drawing mode: any tool but those of selection mode and those that only move, turn or
@@ -203,7 +204,8 @@ mod tests {
for id in ["pencil", "pen", "rectangle", "paintbrush", "type", "eraser", "shapeBuilder"] {
assert!(is_drawing_tool(id), "{id}");
}
let selecting = ["selection", "directSelection", "groupSelection", "magicWand", "lasso", "perspectiveSelection"];
let selecting =
["selection", "directSelection", "groupSelection", "magicWand", "lasso", "enclosingLasso", "polygonalLasso", "perspectiveSelection"];
for id in selecting.into_iter().chain(["hand", "rotateView", "zoom", "printTiling"]) {
assert!(!is_drawing_tool(id), "{id}");
}
+9
View File
@@ -923,6 +923,9 @@ pub struct WheelResponse {
/// A colour moved by dragging its marker (a new hue and saturation) or, the selected colour,
/// the brightness slider (a new brightness): `[h°, s, v]`, `None` where the control kept it.
pub moved: Option<(usize, [Option<f32>; 3])>,
/// A click on the wheel: the color whose marker is within reach of it (if any), and the hue
/// (degrees) and saturation under the pointer (1 for a marker past the wheel's edge).
pub clicked: Option<(Option<usize>, [f32; 2])>,
}
/// The harmony wheel of Recolor Artwork's Edit tab and the Color Themes panel: a hue and saturation
@@ -971,6 +974,12 @@ fn wheel(ui: &mut Ui, id: &str, size: f32, colors: &[Color], base: Option<usize>
let near = colors.iter().map(at).enumerate().map(|(i, m)| (i, m.distance(p))).filter(|x| x.1 <= 14.0).min_by(|a, b| a.1.total_cmp(&b.1));
out.pressed = near.map(|x| x.0);
ui.data_mut(|m| m.insert_temp(drag, out.pressed));
// A click inside the wheel, or on a marker, gives the hue and saturation under it.
let dv = p - c;
if resp.clicked() && (dv.length() <= r || out.pressed.is_some()) {
let h = (-dv.y).atan2(dv.x).to_degrees().rem_euclid(360.0);
out.clicked = Some((out.pressed, [h, (dv.length() / r).clamp(0.0, 1.0)]));
}
}
if resp.dragged()
&& let (Some(i), Some(p)) = (ui.data(|m| m.get_temp::<Option<usize>>(drag)).flatten(), resp.interact_pointer_pos())
+9 -2
View File
@@ -290,8 +290,15 @@ luminosity}`, percent from -100 to 100, 0 by default). The dialog sends a non-ze
colors; colors opened alone are saved as a group with the change. `display` sets how the Edit tab shows the new
colors: `smooth` (the smooth wheel, also when unset; each opening starts there), `segmented` (a wheel of solid patches,
24 hues by 5 saturations, whose markers move as freely) or `bars` (a solid bar per recolored color in row order; a click
selects its row for the sliders and a drag moves the row without changing a color). Setting
`colors`, a preserve flag or `limitTo` reduces the rows again (also on `ui.dialog.confirm`). The dialog previews
selects its row for the sliders and a drag moves the row without changing a color). `wheelTool` turns on a wheel tool
on either wheel: `add` (the Add Color tool) adds a click as a new color, the hue and saturation clicked at the base
color's brightness (the patch's color on the segmented wheel), in a new row with no current colors (`from: []`) and
`added: true` that becomes the selected row; `remove` (the Remove Color tool) removes the color of the marker clicked. A color bar's
right-click menu has Remove Color too. The base color can't be removed. A removed color's row is dropped, unless it
has current colors and art or a group is open: it then keeps them with `to: null`, that art keeps its colors, and the
group's swatch at that place is removed. A row with no current colors recolors no art; with a group, the new color of
one with `added: true` that is not excluded is added to the group after the group's other colors, and a row made with New Row adds none.
Setting `colors`, a preserve flag or `limitTo` reduces the rows again (also on `ui.dialog.confirm`). The dialog previews
`recolor.apply` on the canvas; confirm keeps it as one undo step (with a group, the group is rewritten in the same
step; with no art selected only the group changes). In the Swatches panel, double-clicking a colour group's folder,
or the options button while a group is selected, opens it.
+1 -1
View File
@@ -180,7 +180,7 @@ VectorCraft choices; an original approximation, never compared with another appl
|---|---|
| Revolve | initial: live, editable profile, rotation and light gizmos, default-on Cap with continuous curved rims that also closes a partial sweep's cut sides, smooth vector shading and round seam joins, overlapping faces drawn in the order of their depths where they overlap, SVG/PDF output, Expand Appearance ([revolve.md](revolve.md), #846) |
| Extrude & Bevel, Inflate, Rotate | initial: live, round seam joins, depth, twist, taper, solid or hollow caps, five original bevel shapes, Inflate volume, both sides, twist, taper and cap, Rotate of every fill and stroke, groups and layers turned about one shared axis (#4506), contours that cross, touch or overlap merged first ([three-d.md](three-d.md)), Position presets, rotation and light gizmos, SVG/PDF output, Expand Appearance ([three-d.md](three-d.md)) |
| Materials panel, lighting, ray-traced render | Window › 3D and Materials panel with the object types (Plane, Extrude, Revolve, Inflate) and the Object, Rotation and Lighting settings of the applied effect, Render Settings › Wireframe, which draws the live effect as the edges of its faces, and Quick Actions › Expand as Wireframes ([three-d.md](three-d.md#3d-and-materials-panel)); one to ten directional lights with per-light Color (opaque RGB, white by default), Intensity, Rotation, Height, Softness and neutral Ambient Light, Revolve and colored Inflate use smooth vector shading; Extrude & Bevel and Rotate retain planar shading; original Standard, Diffuse, Top Left and Right lighting rigs; hard-edged shadows behind or below the object from the first light ([three-d.md](three-d.md#shadows)); the Materials tab's Graphics, document symbols mapped onto Extrude & Bevel's caps and onto a plane, moved with an artboard handle, and wrapped around Revolve's side ([three-d.md](three-d.md#graphics)); no base materials, graphics on Inflate or on Extrude & Bevel's walls and bevels, soft shadows or ray tracing |
| Materials panel, lighting, ray-traced render | Window › 3D and Materials panel with the object types (Plane, Extrude, Revolve, Inflate) and the Object, Rotation and Lighting settings of the applied effect, Render Settings › Wireframe, which draws the live effect as the edges of its faces, and Quick Actions › Expand as Wireframes ([three-d.md](three-d.md#3d-and-materials-panel)); one to ten directional lights with per-light Color (opaque RGB, white by default), Intensity, Rotation, Height, Softness and neutral Ambient Light, Revolve and colored Inflate use smooth vector shading; Extrude & Bevel and Rotate retain planar shading; original Standard, Diffuse, Top Left and Right lighting rigs; shadows behind or below the object from the first light, blurred by its Softness ([three-d.md](three-d.md#shadows)); the Materials tab's Graphics, document symbols mapped onto Extrude & Bevel's caps and onto a plane, moved with an artboard handle, and wrapped around Revolve's side ([three-d.md](three-d.md#graphics)); no base materials, graphics on Inflate or on Extrude & Bevel's walls and bevels, or ray tracing |
| 3D (Classic): Extrude & Bevel, Revolve, Rotate | Extrude & Bevel (Classic) initial: live, round seam joins, Extrude Depth, Cap, five original bevel shapes with Height and Bevel Extent In or Out, Position presets and rotation gizmo, Perspective, Wireframe, No Shading, Diffuse and Plastic surfaces with one to ten lights, Light Intensity, Ambient Light, Highlight Intensity and Size, Blend Steps, Black, Custom, Black Overprint or no Shading Color ([Black Overprint](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=188)), Draw Hidden Faces ([create 3D objects](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/create-3d-objects.html)); Revolve (Classic) initial: live, round seam joins, Angle, Cap, Offset from the left or right edge, Position presets and rotation gizmo, Perspective, the same four surfaces, lights, highlight, Blend Steps and Shading Color, groups and layers revolved about one shared axis (same page); Rotate (Classic) initial: live, round seam joins, every fill and stroke turned as one plane, Position presets and rotation gizmo, Perspective, No Shading and Diffuse surfaces with lights, Ambient Light, Blend Steps and Shading Color ([rotate objects in 3D](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/rotate-objects-in-3d.html)); Preserve Spot Colors in all three, unavailable with a Custom Shading Color ([Preserve Spot Color](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=260)); all three: a lighting sphere on the Lighting tab whose lights drag, move to the back or front, and are added at the front center or deleted down to one ([lighting options](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=272)); all three: the track cube (face, edge, Shift and ring drags, keyboard steps; [three-d.md](three-d.md#track-cube)); Map Art: none |
| Turntable (30.0 beta) | none |
| Export 3D objects (OBJ, USDA, glTF) | initial: Asset Export's Export 3D Object, and the 3D and Materials panel's Export 3D Object button (which then shows Asset Export with the new assets selected, [three-d.md](three-d.md#3d-and-materials-panel)), collect an object with Extrude & Bevel, Revolve, Inflate or Rotate as a 3D asset, and Export writes its solids as a USDA (the default), USDZ, glTF or OBJ mesh with a material in each solid's paint color (`assets.add3D`, `assets.set3DFormat`, `assets.export3D`); no textures, map art or shading ([3D export help](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/create-3d-graphics/export-3d-vector-artwork.html)) |
+27 -9
View File
@@ -244,7 +244,13 @@ the suite) keep the agent to the folders you give it:
`export`), `document.exportSelection`, `document.exportForScreens` and `assets.export` (before the folder is
made or any row is written), `document.save`, `file.save`, `file.saveAs` and `file.saveCopy` (also a save
without a path of a document whose own format is SVG or SVGZ), `file.exportAs`, and the SVG Options dialog's
Show Code. A file given as another URL (`https://…`) is not checked. The document keeps the link, and the
Show Code. The same error refuses, before any file is written, every output that carries the native document,
which holds the link: a native file or template, an EPS file, a `.ai` or `.ait` file of every artboard (not a
legacy version 7 `.ai` file; a save of a `.ai` file always has every artboard), a PDF of every artboard with
Preserve Editing on (also from `document.exportPdf`), and `file.package` (also when a linked native document,
or the native document a linked PDF, `.ai` or EPS file carries, links such a file). A PDF or `.ai` file of
some of the artboards or of the art's bounds (`useArtboards: false`), a PDF without Preserve Editing, and an
image are written as before. A file given as another URL (`https://…`) is not checked. The document keeps the link, and the
person at the keyboard exports it as stored.
- The same SVG and SVGZ outputs are refused with "a linked image file is outside the read roots", which names no
file or folder, when the file would name a linked image's file outside the read roots (a path, a `file:` URL,
@@ -991,7 +997,9 @@ when the line still shows different ones until the graph is drawn again. `paint.
`addon.color.fillToStroke` and `addon.color.strokeToFill` also store the paint they write on a line's topmost visible
fill or stroke row when the line already showed it. `appearance.setItem` and an `appearance.copyFrom` of some
attributes store the paint, stroke weight, and row opacity and blend mode they write to that row in the same way, and
`stroke.set` stores the weight it writes there. An `appearance.copyFrom` that does not apply
`stroke.set` stores the weight it writes there. When a kind keeps no stroke paint and a zero weight (a line's stroke was
set to None), a stroke painted on another line of that kind stores that line's weight for the kind; a zero weight set
together with a stroke color, or kept with a painted stroke, stays as set. An `appearance.copyFrom` that does not apply
the object's transparency, and `graphicStyle.apply` with `add`, leave the object opacity and blend mode a kind keeps as
they are, also when the line still shows other ones. `paint.default` stores the default fill and stroke rows for a
line's kind even when the line already showed them, and leaves the object opacity and blend mode the kind keeps. Rows
@@ -1462,7 +1470,9 @@ Preserve Editing (`preserveEditing`, on in the `VectorCraft Default` preset) emb
an embedded file (`vectorcraft-editing.vectorcraft`; files named `drawcraft-editing.drawcraft` are read too) with a
hash of the pages it was written with. `open_file` / `document.open` of such a PDF, `.ai` or `.ait` (no `pages` picked) restores the
document exactly (`restored: true`); when another app changed the pages, or the data can't be read, the artwork is
imported instead and the first warning says why. Choosing a standard turns it off (PDF/A refuses it). Save to a `.ai`
imported instead and the first warning says why. Choosing a standard turns it off (PDF/A refuses it). Under automation
read roots, a PDF that carries the native document is refused while the document links a JavaScript file outside them
(see [Confining file access](#confining-file-access)). Save to a `.ai`
path (`document.save {path: "art.ai"}` or `{format: "ai"}`) writes a PDF-compatible file that always carries the
document, takes the PDF options and keeps its path when reopened, so Save writes `.ai` again; a `.ait` opens untitled.
The restored document opens on the artboard its editing copy names as active. A file saved with `editingData: false` has
@@ -4356,8 +4366,11 @@ The document stores their numeric settings; manual edits remain possible through
Revolve, Extrude & Bevel, Inflate and Rotate take `shadow` (boolean, default false), `shadowPosition` (`"behind"`
or `"below"`, default `"behind"`), `shadowDistance` (0..100%, default 0) and `shadowBounds` (10..400%, default 100),
set with `effect.apply` or `effect.setParams` in one undo step. With `shadow` on, the first light casts a
hard-edged shadow of the solid, drawn behind the solid as one path filled black at 50% opacity times the opacity
of the art that casts it, in that art's blending mode. `"behind"` puts it
shadow of the solid, drawn behind the solid as one path filled black at 50% opacity times the opacity
of the art that casts it, in that art's blending mode. At the first light's `softness` (or `lightSoftness`) 0 the
path is hard-edged; above 0 it carries a Gaussian Blur of radius softness × the object's largest size × (5% + 20% ×
`shadowDistance`), at most 1,000 pt (VectorCraft's own mapping), drawn, measured, exported and expanded (to an
image) as that effect is. `"behind"` puts it
on a plane square to the view behind the object; `"below"` puts it on the floor under the object, square to the
object's own vertical axis and turned with it, so with no X rotation the floor is seen edge-on and draws nothing.
`shadowDistance` moves the plane away from the object by that share of the object's largest size. `shadowBounds`
@@ -4660,8 +4673,10 @@ darker than the row's average become tints and shades) or `hueShift` (the most s
the others turn by the same hue). `limitTo` snaps new colours to a swatch library's nearest colour;
`recolor.randomize {map, order?, saturationBrightness?, seed?}` shuffles or varies new colours; a row with
`exclude: true` keeps its colours. A row's `from` may be an empty list: the row recolors nothing, adds no library swatch with
`limitTo` and gives `group` no color, and `recolor.randomize` and `recolor.weigh` keep it; `recolor.randomize` leaves its
new color as it is and shuffles only the rows that hold current colors. A row without `from`, or with
`limitTo` and gives `group` no color, unless it has `added: true` (a color the Edit tab's Add Color tool added):
without `groupColors`, its new color then joins `group` after the new colors of the rows with current colors.
`recolor.randomize` leaves a row without current colors as it is and shuffles only the rows that hold current colors.
`recolor.randomize` and `recolor.weigh` keep such a row, and `recolor.randomize` keeps its `added`. A row without `from`, or with
a current color that is not a color, is refused. With art selected, the Recolor Artwork dialog's New Row button (beside
Merge) adds such a row above the first selected row, or at the top, with that row's new color, and selects it; Shift-click a row below it and Merge to move that row's colors into it (Merge keeps the topmost selected row's new color). An
empty row does not count toward Colors. While it is empty, the dialog's Edit tab does not show it (its sliders edit
@@ -4671,7 +4686,8 @@ from colors alone leave its new color out. With `limitTo`, a row's `tint` (a per
linked to the global or spot swatch its new color is that share of its tint; `tint` must be a number. `recolor.randomize`
moves a row's `tint` with its new color and removes it from a color it changes, and moves a row's `model` with its new color. `swatch.editGroup {group, colors, rename?}` rewrites a colour group in one undo
step (art linked to its global swatches follows), and `recolor.apply` with `group` recolours the art and rewrites the
group together. Art linked to one of the group's global swatches stays linked when the swatch is rewritten with its
group together. A `null` in `groupColors` removes the group's swatch at that place, and the swatches after it keep
their colors and names; art linked to a removed global swatch keeps its color and is no longer linked to it. Art linked to one of the group's global swatches stays linked when the swatch is rewritten with its
row's new color (the default without `groupColors` when the rows follow the group's order), so a later `swatch.edit` still
reaches it; the reply's `relinked` counts the other linked paints that took the group's new colors. Art in a row that
is linked to a swatch rewritten with another color keeps its row's new color, even an unchanged one, and is no longer
@@ -8292,7 +8308,9 @@ type uses in `Fonts/` (fonts whose licence doesn't allow embedding are listed in
the copies (each file copied once); one that can't be read is copied as it is, and a cycle of placed documents or one
past the nesting limit stops there, each with a line in `warnings` and the report. A `folder/name` where a packaged file
would replace the document or one of its linked files (the document's own folder, say) is an error, and nothing is
written. Every option defaults to true. An option that is not true or false, or a `folder` or `name` that is not a
written. Under automation read roots, the package is refused, and nothing is written, while the document, a linked
native document or the native document a linked PDF, `.ai` or EPS file carries links a JavaScript file outside them
(see [Confining file access](#confining-file-access)). Every option defaults to true. An option that is not true or false, or a `folder` or `name` that is not a
string, is an error naming the key, and nothing is written; null is the same as leaving the key out. Without `folder` (the web, or an agent that wants the bytes) the
result carries the same files as a zip (`{name: "<name>.zip", dataBase64}`, entries under `<name>/`).
+10 -3
View File
@@ -596,8 +596,9 @@ since 2026-10-01.
- 3D lighting presets: `crates/effects/src/lighting_presets.rs`, `crates/engine/src/cmd/effectcmd/lighting_presets_tests.rs` and the pointer tests in `crates/ui-egui/src/dialogs/revolve/tests.rs` cover recognition, atomic targeting, native round trips, preview, Cancel, reset and Undo.
- 3D lighting widget: the Lighting tab of the 3D and Materials panel shows every light on a sphere at its Rotation and Height; a drag moves a light in one undo step, a press selects it, Move Light to Back and Move Light to Front change its side, and the arrow keys move the focused light ([three-d.md](three-d.md#lighting-widget)). `crates/ui-egui/src/panels/tests_three_d.rs` covers the drag, selection, side and keyboard.
- 3D shadows: Revolve, Extrude & Bevel, Inflate and Rotate take a Shadows switch with Position (Behind Object or Below Object), Distance from Object (0–100 %) and Shadow Bounds (10–400 %) on the Lighting tab ([three-d.md](three-d.md#shadows)); the first light casts one hard-edged vector shadow, drawn behind the solids, in exports and kept by Expand Appearance. Evidence: `crates/three-d/src/shadow/tests.rs`, `crates/effects/src/solids/tests_shadow.rs`, `effectcmd::tests::a_3d_shadow_is_one_undo_step_saved_exported_and_expanded`. Softness and the shadows of lights after the first are not built. Scores unchanged.
- 3D shadows: Revolve, Extrude & Bevel, Inflate and Rotate take a Shadows switch with Position (Behind Object or Below Object), Distance from Object (0–100 %) and Shadow Bounds (10–400 %) on the Lighting tab ([three-d.md](three-d.md#shadows)); the first light casts one hard-edged vector shadow, drawn behind the solids, in exports and kept by Expand Appearance. Evidence: `crates/three-d/src/shadow/tests.rs`, `crates/effects/src/solids/tests_shadow.rs`, `effectcmd::tests::a_3d_shadow_is_one_undo_step_saved_exported_and_expanded`. The shadows of lights after the first are not built; the first light's Softness blurs the shadow (next entry). Scores unchanged.
- 3D shadows: with Shadows on, Revolve, Extrude & Bevel, Inflate and Rotate cast the shadow from the faces kept by the build that draws each solid, so drawing an object builds each of its solids once. The art and the shadow are unchanged. Evidence: `crates/three-d/src/shadow/tests.rs` (`a_solid_and_its_shadow_are_built_once` and the tests that compare each solid and its shadow with the two built apart), `solids::tests_shadow::a_shadowed_3d_object_builds_each_solid_once`, `solids::tests_shadow::the_shadow_cast_from_the_solids_drawn_is_the_shadow_of_solids_built_for_it`, `revolve::tests::the_shadow_cast_from_the_surfaces_drawn_is_the_shadow_of_surfaces_swept_for_it`. Scores unchanged.
- 3D shadows: the first light's Softness blurs the shadow of Revolve, Extrude & Bevel, Inflate and Rotate with a Gaussian Blur whose radius grows with Softness and Distance from Object and scales with the object (VectorCraft's own mapping; at 0 % the shadow stays hard-edged), on the canvas, in the art's bounds and in exports, and Expand Appearance keeps it as an image ([three-d.md](three-d.md#shadows)). Evidence: `shadow::tests::softness_blurs_the_shadow_more_the_farther_the_plane_is` (three-d), `solids::tests_shadow::the_first_lights_softness_blurs_the_shadow`, `solids::tests_shadow::a_fills_own_3d_effect_keeps_the_blur_below_its_later_effects`, `effectcmd::tests::a_soft_3d_shadow_is_drawn_measured_exported_and_expanded_blurred`. Scores unchanged.
- 3D shadows: a command that applies or edits Extrude & Bevel, Inflate or Rotate with Shadows on checks the shadow from the faces kept by the builds that check the solids, as drawing casts it, so it builds each solid once instead of building it again for the shadow. A stroke whose solid is left out of the art past its own limits casts no shadow. Evidence: `solids::tests::the_check_builds_each_drawn_solid_once`, `solids::tests_shadow::a_stroke_left_out_of_the_art_casts_no_shadow`, `solids::tests_shadow::the_check_accepts_the_shadowed_objects_that_draw`. Scores unchanged.
- 3D shadows: in Revolve, Extrude & Bevel, Inflate and Rotate, a fill, stroke or member whose opacity is NaN or infinite casts no part of the shadow, as one at 0 % does, whether the shadow is cast from the solids drawn or from solids built for it alone; the art beside it still casts. This is VectorCraft's own rule. Evidence: `solids::tests_shadow::art_whose_opacity_is_not_a_finite_number_casts_no_shadow`, `revolve::tests::a_surface_whose_opacity_is_not_a_finite_number_casts_no_shadow`. Scores unchanged.
- Window › 3D and Materials panel: `crates/ui-egui/src/panels/three_d.rs` applies a 3D effect by object type (Plane, Extrude, Revolve, Inflate), changes an applied one in place (`effect.setParams` `threeDType`) and edits it with the options dialog's Object, Rotation and Lighting controls, one undo step per change; `crates/engine/src/cmd/effectcmd/three_d_type_tests.rs` and `crates/ui-egui/src/panels/tests_three_d.rs` cover it. No Materials tab.
@@ -643,11 +644,12 @@ since 2026-10-01.
- **Selected Mirror Repeat handles:** a headless canvas regression creates the default mirror repeat and drags its Top bounding-box handle where the axis crosses it; the repeat grows vertically while its width stays fixed. Existing mirror-axis checks cover center movement and end-handle hit priority. The focused UI mirror tests pass. Scores and hours unchanged.
- **Transform effect options (#885):** Effect › Distort & Transform › Transform… has visible Transform Objects, Transform Patterns and Scale Strokes & Effects checkboxes (`distort.transform` params `objects`, `patterns`, `strokes`; files without them draw as before). With Transform Objects off the geometry stays and makes no copies; Scale Strokes & Effects scales stroke weights, dashes and the fills' and strokes' effect distances by the mean scale, and Transform Patterns moves pattern tiles, each copy `k` by the transformation `k` times. Such objects draw, export and expand through the same per-copy art, so the canvas and Expand Appearance agree (engine `tests_transformfx`, effects `tests_transformfx`, the dialog test). A Transform effect in a fill's or stroke's own effects applies the same options to that fill or stroke: its weight and dashes and its pattern follow the transformation, and with copies each copy is an object of its own; the canvas, export, Expand Appearance and Use Preview Bounds use the same art (effects `tests_transformfx`). The effects listed after it in that fill's or stroke's list keep their own distances and apply to the transformed art and to each copy, as an object's later effects do after the object's Transform effect: a Drop Shadow after it keeps its offset, an Offset Path after it offsets by its own distance, and an SVG filter after it keeps its scale and the origin of its user space. With Transform Objects off, the effects before it keep their distances too. Before, Scale Strokes & Effects scaled a fill's or stroke's later effects by the mean scale, so existing documents with such effects draw differently. Effects apply in the order they are listed ([Appearance attributes](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-graphic-styles/appearance-attributes-in-illustrator.html)); how the two options treat the effects after a fill's or stroke's own Transform effect is VectorCraft's own rule, following that order (effects `tests::rasterfollow::a_fills_own_transform_leaves_the_shadow_after_it`, `tests::rasterfollow::a_fills_own_transform_leaves_the_offset_after_it`, `tests::rasterfollow::a_fills_own_transform_leaves_the_svg_filter_after_it`, `tests::transformfx::a_fills_own_transform_with_scale_strokes_and_effects_leaves_its_later_effects`; engine `plugins::a_transform_after_a_painted_fill_effect_leaves_the_later_shadow_on_every_paint`). Public reference: [Scale objects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/scale-objects.html), [How to apply effects](https://helpx.adobe.com/illustrator/using/effects.html), [Distort and transform effects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/distort-and-transform-effects-in-illustrator.html). Scores and hours unchanged.
- **Raster effects before a Transform effect:** effects apply in the order they are listed ([Appearance attributes](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-graphic-styles/appearance-attributes-in-illustrator.html)). A Drop Shadow, glow, blur, Feather or pixel filter listed before a Transform effect in the same list (an object's effects, or a fill's or stroke's own) now follows that Transform effect: its sizes scale by the mean scale, and a Drop Shadow's offset turns, reflects and scales with the art. VectorCraft applies this rule with Scale Strokes & Effects on or off. Before, such an effect was drawn at its own distances around the transformed art. The canvas, export, Expand Appearance, Object › Expand, Outline Stroke and the 3D effects use the same values (effects `tests::rasterfollow`; render `a_transform_after_a_drop_shadow_scales_the_shadow_with_the_art`; engine `objexpand::a_shadow_before_a_transform_expands_as_the_canvas_draws_it`, `outlinestroke::a_shadow_before_a_transform_outlines_as_the_canvas_draws_it`). Not yet: a Transform effect that makes copies or moves at random leaves the raster effects before it as they are. The light direction of Underpainting, Rough Pastels, Conté Crayon, Bas Relief, Plaster and Texturizer and the stroke direction of Sprayed Strokes and Graphic Pen now turn and reflect with such a Transform effect, each set to the nearest of its menu's choices (at a tie, the one clockwise of it; VectorCraft's own rule), and Color Halftone's four screen angles turn and reflect with the art ([Distort and transform effects](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/distort-and-transform-effects-in-illustrator.html); effects `tests::rasterfollow::bas_relief_light_follows_rotation_and_reflection` and the tests after it). Not yet: filters whose strokes or patterns run along fixed page axes without a direction setting (Angled Strokes, Crosshatch, Mezzotint's lines, Halftone Pattern's lines, Grain's horizontal and vertical types, De-Interlace) keep those axes, and an uneven scale or a shear sets a direction from the one vector it maps, not a skewed pattern. Scores and hours unchanged.
- **Raster effects before a Transform effect that makes copies:** the Transform effect can make copies with its transformation applied ([the help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/distort-and-transform-effects-in-illustrator.html)). Giving each copy the raster effects listed before that effect is VectorCraft's own rule. On a path or compound path, each copy now carries the Drop Shadow, glow, blur, Feather or pixel filter listed before the last Transform effect that makes copies, with its sizes scaled by that copy's mean scale and a Drop Shadow's offset turned, reflected and scaled with the copy; a raster effect listed after it paints once around all the copies. Before, one shadow was drawn under all the copies at the object's own distances. The canvas, the object's bounds, export and Expand Appearance draw the same copies, and copies that stop at the effect budget each keep their effects (effects `tests::rasterfollow::each_copy_of_a_transform_effect_carries_the_shadow_listed_before_it`, `tests::rasterfollow::a_shadow_after_a_copying_transform_paints_once_around_the_copies`, `tests::rasterfollow::copies_past_the_budget_each_keep_their_shadow`; render `objectfx::each_copy_of_a_transform_effect_draws_its_own_shadow`; engine `objexpand::each_copys_shadow_expands_as_the_canvas_draws_it`). A Transform effect without copies draws as before. Not yet: the copies of groups, and a fill's or stroke's own copying Transform effect, still share one set of raster effects, and so does a path with Rasterize, an SVG filter or another effect that is neither a geometry effect nor one of those raster effects before the copying effect. Scores and hours unchanged.
- **A fill's or stroke's raster effects on copies:** an effect can be applied to only the fill or only the stroke of an object ([the help page](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-filter-effects/vector-and-raster-effects.html)), and the Transform effect can make copies ([the help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/distort-and-transform-effects-in-illustrator.html)). How the copies carry a fill's or stroke's raster effects is VectorCraft's own rule. On a path or compound path, each copy that a fill's or stroke's own Transform effect makes now carries the Drop Shadow, glow, blur, Feather or pixel filter listed before that Transform effect in the fill's or stroke's effects, drawn from that copy's fill area or stroke outline, with its sizes scaled by the copy's mean scale and a Drop Shadow's offset turned, reflected and scaled with the copy; with Transform Patterns or Scale Strokes & Effects on, the shadow is not scaled a second time. A raster effect listed after the Transform effect paints once around all the copies, and with either option on it stays on each copy as before. A Transform effect that makes copies and is listed after another of the fill's or stroke's own Transform effects with either option on gives each of its copies the raster effects listed before it the same way, except when a raster effect is listed before a Transform effect that is itself listed before it and makes copies or moves at random (see Not yet below); without either option of its own, it does so only when no raster effect is listed after it. Each copy of a path's own Transform effect that makes copies now carries the raster effects of its fills and strokes the same way, for a single fill, a single stroke, or several. Type is drawn as its outlines, so each copy that a fill's or stroke's own Transform effect makes of type carries those raster effects the same way. Before, one shadow was drawn around all the copies at the fill's or stroke's own distances. A Transform effect without copies, or with Transform Objects off, draws as before. The canvas, the object's bounds, export and Expand Appearance draw the same copies, and copies that stop at the effect budget each keep their effects (effects `tests::rasterfollow::each_copy_of_a_fills_or_strokes_own_transform_carries_the_shadow_before_it`, `tests::rasterfollow::each_copy_of_a_later_copying_transform_carries_the_shadow_before_it`, `tests::rasterfollow::each_copy_of_an_objects_transform_carries_its_fills_or_strokes_shadow`, `tests::rasterfollow::a_fills_shadow_after_its_own_copying_transform_paints_once_around_the_copies`, `tests::rasterfollow::row_copies_past_the_budget_each_keep_their_shadow`, `tests::rasterfollow::type_carries_its_fills_shadow_on_each_copy`; render `objectfx::each_copy_of_a_fills_or_strokes_transform_draws_its_own_shadow`; engine `objexpand::each_copys_fill_shadow_expands_as_the_canvas_draws_it`). Not yet: a fill's or stroke's raster effects on the copies of groups, images and symbol instances, and a fill or stroke whose effects list raster effects before one of its own Transform effects that make copies and another raster effect after it and before a later Transform effect that makes copies or moves at random (for example Drop Shadow, Transform, Drop Shadow, Transform, with both Transform effects making copies), which still paints its raster effects around all of the copies. Scores and hours unchanged.
- **Raster effects before a Transform effect that makes copies:** the Transform effect can make copies with its transformation applied ([the help page](https://helpx.adobe.com/illustrator/desktop/manage-objects/reshape-transform-objects/distort-and-transform-effects-in-illustrator.html)). Giving each copy the raster effects listed before that effect is VectorCraft's own rule. On a path or compound path, each copy now carries the Drop Shadow, glow, blur, Feather or pixel filter listed before the last Transform effect that makes copies, with its sizes scaled by that copy's mean scale and a Drop Shadow's offset turned, reflected and scaled with the copy; a raster effect listed after it paints once around all the copies. Before, one shadow was drawn under all the copies at the object's own distances. The canvas, the object's bounds, export and Expand Appearance draw the same copies, and copies that stop at the effect budget each keep their effects (effects `tests::rasterfollow::each_copy_of_a_transform_effect_carries_the_shadow_listed_before_it`, `tests::rasterfollow::a_shadow_after_a_copying_transform_paints_once_around_the_copies`, `tests::rasterfollow::copies_past_the_budget_each_keep_their_shadow`; render `objectfx::each_copy_of_a_transform_effect_draws_its_own_shadow`; engine `objexpand::each_copys_shadow_expands_as_the_canvas_draws_it`). A Transform effect without copies draws as before. A fill's or stroke's own Transform effect that makes copies is covered under "A fill's or stroke's raster effects on copies". Not yet: the copies of groups still share one set of raster effects, and so does a path with Rasterize, an SVG filter or another effect that is neither a geometry effect nor one of those raster effects before the copying effect. Scores and hours unchanged.
- **Raster effects before a Transform effect that copies type, an image or a symbol instance:** each copy that a Transform effect makes of type, an image or a symbol instance now carries the Drop Shadow, glow, blur, Feather or pixel filter listed before that effect, under the same VectorCraft rule as for paths: its sizes scale by that copy's mean scale and a Drop Shadow's offset turns, reflects and scales with the copy, while a raster effect listed after the Transform effect paints once around all the copies. Type is copied as its outlines, an image in its frame, and a symbol instance as its symbol's art. Before, one shadow was drawn under all the copies at the object's own distances. The canvas, the object's bounds, export and Expand Appearance draw the same copies; type whose Transform effect only moves its copies is exported as its outlines then, rather than as type under one shadow (effects `tests::rasterfollow::each_copy_of_type_an_image_or_a_symbol_instance_carries_the_shadow_listed_before_it`, `tests::rasterfollow::baked_type_whose_transform_moves_its_copies_keeps_a_shadow_on_each`, `tests::rasterfollow::type_with_a_reshaped_fill_keeps_one_shadow_around_its_copies`; render `objectfx::each_copy_of_an_images_transform_effect_draws_its_own_shadow`, `objectfx::each_copy_of_a_symbol_instances_transform_effect_draws_its_own_shadow`; engine `objexpand::each_copys_shadow_on_type_expands_as_the_canvas_draws_it`). Not yet: type and symbol instances in perspective, type, images and symbol instances whose fill or stroke has geometry effects of its own, and objects with a linked opacity mask keep one set of raster effects around their copies. Scores and hours unchanged.
- **Rasterize before a Transform effect:** effects apply in the order they are listed, each one taking the result of the one before ([the help page](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-graphic-styles/appearance-attributes-in-illustrator.html)). On a path or compound path, a Transform effect listed after the object's own Rasterize effect now moves the image that Rasterize makes: the image is made of the art before the Transform effect, at the Rasterize effect's resolution and with its room around the art, and the Transform effect scales, turns, reflects and moves the image with its pixel grid. Before, the Transform effect moved the art and Rasterize made a new image of the moved art on a grid square to the page. Keeping the image's pixel grid under the Transform effect is VectorCraft's own rule. A hidden Transform effect, or one with Transform Objects off, leaves the image where it is, and one that scales it to nothing leaves nothing drawn. The canvas, the object's bounds, Expand Appearance and PDF export draw the same image (effects `tests::rasterfollow::rasterize_following_ignores_hidden_and_objects_off`, `tests::rasterfollow::the_image_moves_by_each_transform_about_the_art_it_takes`; render `rasterize::rasterize_then_scale_uses_the_pretransform_pixels`, `rasterize::rasterize_then_rotate_and_reflect_moves_the_pixel_grid`, `rasterize::rasterize_then_nonuniform_scale_and_zero_scale_are_bounded`; engine `rastersettings::expand_rasterize_then_transform_matches_canvas`). Not yet: a Transform effect that makes copies or moves at random, a Transform effect followed by another kind of effect, a fill's or stroke's own Rasterize effect, and Rasterize on type, images, symbol instances and groups keep the earlier behavior. Scores and hours unchanged.
- **Raster effects before a Transform effect past the effect budget:** VectorCraft leaves out a Transform effect whose result would pass its geometry budget of 2 million anchors or 8 million lines drawn, and the art stays where it was. The raster effects listed before that Transform effect now stay with the art too: a Drop Shadow keeps its own offset and blur, and the Transform effects after it that fit still move both. Before, the art stayed while the shadow scaled with the Transform effect it did not take. This is VectorCraft's own rule. It applies to a path's own effects and to its fills' and strokes' own, also when the path is in a group whose geometry effects run after its members' own, on the canvas and in its bounds, in export, Expand Appearance, Object › Expand and Outline Stroke, and a hidden shadow keeps its values once shown (effects `tests::rasterfollow::a_transform_past_the_line_budget_moves_the_art_with_its_shadow`, `tests::rasterfollow::only_transforms_that_ran_move_a_preceding_shadow`, `tests::rasterfollow::a_skipped_item_transform_keeps_its_shadow`, `tests::rasterfollow::the_shape_art_of_a_skipped_transform_keeps_its_shadows`, `tests::rasterfollow::a_members_skipped_transform_keeps_its_shadow_under_its_groups_effects`; render `objectfx::a_shadow_before_a_skipped_transform_reaches_as_far_as_it_is_drawn`, `fx::renderer::tests::a_path_paints_from_the_transforms_that_moved_it`; engine `objexpand::a_shadow_before_a_skipped_transform_expands_with_its_own_offset`). Not yet: the shadow of type, an image, a symbol instance or a group whose art a Transform effect leaves in place past the budget still follows that effect. Scores and hours unchanged.
- **Raster effects inside an object or group with a Transform effect:** effects applied to a group affect everything in it ([Appearance attributes](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-graphic-styles/appearance-attributes-in-illustrator.html)). How a Transform effect changes the raster effects inside a group or object is VectorCraft's own rule. A group's Transform effect that moves it once now transforms the raster effects of its members, of their fills and strokes, of nested groups and of the art of the linked opacity masks in it, after the members' own Transform effects. A raster effect that a member's own Transform effect with copies or random holds back keeps its value through that effect and still transforms with the group's. VectorCraft applies the same rule to the raster effects of an object's fills and strokes under the object's Transform effect. Sizes scale by the mean scale and a Drop Shadow's offset turns, reflects and scales, with Scale Strokes & Effects on or off. Before, they kept their values, or with Scale Strokes & Effects on scaled by the mean scale with the offset unturned. A group's or object's Transform effect that makes copies or moves at random leaves them as before. The canvas, the redraw region, export, Expand Appearance, Object › Expand and Outline Stroke use the same values (effects `tests::rasterfollow`, `group::tests::a_compound_shapes_transform_turns_its_fills_shadow`; render `a_transform_scales_the_shadows_of_fills_and_members_with_the_art`; engine `objexpand::a_fills_shadow_under_the_objects_transform_expands_as_the_canvas_draws_it`, `objexpand::shadows_under_a_groups_or_an_objects_transform_expand_appearance_as_the_canvas_draws_them`, `outlinestroke::a_strokes_shadow_under_the_objects_transform_outlines_as_the_canvas_draws_it`). Scores and hours unchanged.
- **Raster effects inside an object or group with a Transform effect:** effects applied to a group affect everything in it ([Appearance attributes](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-graphic-styles/appearance-attributes-in-illustrator.html)). How a Transform effect changes the raster effects inside a group or object is VectorCraft's own rule. A group's Transform effect that moves it once now transforms the raster effects of its members, of their fills and strokes, of nested groups and of the art of the linked opacity masks in it, after the members' own Transform effects. A raster effect that a member's own Transform effect with copies or random holds back keeps its value through that effect and still transforms with the group's. VectorCraft applies the same rule to the raster effects of an object's fills and strokes under the object's Transform effect. Sizes scale by the mean scale and a Drop Shadow's offset turns, reflects and scales, with Scale Strokes & Effects on or off. Before, they kept their values, or with Scale Strokes & Effects on scaled by the mean scale with the offset unturned. A group's or object's Transform effect that makes copies or moves at random leaves them as before, except a path's Transform effect that makes copies (see "A fill's or stroke's raster effects on copies"). The canvas, the redraw region, export, Expand Appearance, Object › Expand and Outline Stroke use the same values (effects `tests::rasterfollow`, `group::tests::a_compound_shapes_transform_turns_its_fills_shadow`; render `a_transform_scales_the_shadows_of_fills_and_members_with_the_art`; engine `objexpand::a_fills_shadow_under_the_objects_transform_expands_as_the_canvas_draws_it`, `objexpand::shadows_under_a_groups_or_an_objects_transform_expand_appearance_as_the_canvas_draws_them`, `outlinestroke::a_strokes_shadow_under_the_objects_transform_outlines_as_the_canvas_draws_it`). Scores and hours unchanged.
- **A group's geometry effects after its members' own:** effects applied to a group affect everything in it, and effects apply in the order they are listed ([Appearance attributes](https://helpx.adobe.com/illustrator/desktop/special-effects-styles/apply-graphic-styles/appearance-attributes-in-illustrator.html)). Running a group's effects after its members' own is VectorCraft's own rule. The geometry effects of a group or layer (the effects that reshape outlines, such as Distort & Transform, Offset Path and Warp) now reshape what its members draw: the geometry effects of each visible path and compound path in it and of their fills and strokes, and a nested group's own geometry and Pathfinder effects, run first, at any depth. A symbol instance's own geometry effects run after those of its symbol's members in the same way. Before, the group's effects reshaped the members' outlines and the members' own effects ran afterwards: a 100 pt square with its own 10 pt Offset Path in a group with a 50% Transform drew 70 pt wide, and it now draws 60 pt wide. Existing documents with such groups draw differently. The canvas, export, Expand Appearance and the art that Pathfinder operations and compound shapes take from such a group use the same order (effects `group::tests::a_members_own_offset_runs_before_its_groups_scale`, `group::tests::a_members_own_scale_runs_before_its_groups_offset`, `group::tests::a_member_of_a_plain_nested_group_takes_its_own_effects_first`, `group::tests::a_nested_groups_own_effects_run_before_its_groups`, `group::tests::a_nested_groups_pathfinder_runs_before_its_groups_effects`, `group::tests::a_members_fill_effects_run_before_its_groups`, `group::tests::shape_art_of_a_group_applies_its_members_effects_first`, `group::tests::a_symbol_instances_effects_run_after_its_symbols_members_own`, `group::tests::a_baked_group_applies_its_members_effects_first`, `group::tests::a_baked_group_that_keeps_its_type_applies_its_members_effects_first`, `tests::rasterfollow::a_groups_transform_applies_after_its_members_own`; engine `objexpand::a_groups_effects_after_its_members_own_expand_as_the_canvas_draws_them`). Not yet: the own geometry effects of images, symbol instances, paths with a linked opacity mask or a 3D effect, and nested groups with a 3D effect in the group still run after the group's. Scores and hours unchanged.
- **Warp Options (#1760):** Effect > Warp and existing Appearance effect links share the fifteen existing styles, original schematic previews, orientation choices and percent Bend/Distortion controls. Focused tests passed for real numeric entry and slider input, Preview/Cancel, immediate Enter/OK, mixed-style edits, target/slot/visibility preservation and Undo/Redo. Each applied style stays unchanged until an explicit Style choice. Original style-menu and live-preview captures were reviewed; their numeric values were supplied programmatically. Public references: [Reshaping with effects](https://helpx.adobe.com/illustrator/using/reshaping-objects-effects.html) and [Using effects](https://helpx.adobe.com/illustrator/using/effects.html). Warp geometry, optional Properties integration and remembered defaults are unchanged; no broader parity claim.
- **Placed gradients follow the Warp effects:** under each of the fifteen Warp styles with a bend or a distortion, a gradient placed with the Gradient tool moves and scales from the object's bounds before the warp to its bounds after it, as under Free Distort; a stroke's gradient uses those bounds inflated by the stroke. This holds for an object's own Warp and for a fill's or stroke's own, on the canvas and in Object › Expand of the fill. In a group with a Warp effect, each path's and compound path's gradients follow its own bounds, a nested group's own fills and strokes follow the nested group's bounds, and the group's own fills and strokes follow the group's bounds. In the art Pathfinder and compound shapes take, a symbol instance's Warp moves the gradients of its symbol's art by the art's bounds, and a compound shape's Warp moves its gradients by the bounds of its area. A gradient fitted to the object still fits the warped outline, and a warp with no bend and no distortion leaves the gradient exactly in place. Existing documents with a Warp effect on art with a placed gradient draw differently: before, the gradient stayed where it was while the outline changed. How gradients follow the warp is VectorCraft's own rule; what the Warp effects do to the object is described in [Reshaping with effects](https://helpx.adobe.com/illustrator/using/reshaping-objects-effects.html) (effects `tests::warp_bends_when_the_warp_moves_the_outline`, `bake::tests::baked_warps_move_placed_gradients_from_the_bounds_to_the_warped_bounds`, `bake::tests::a_warp_with_no_bend_leaves_a_placed_gradient_exactly_in_place`, `bake::tests::a_fills_and_a_strokes_own_warp_move_its_placed_gradient_with_the_bounds`, `group::tests::a_groups_warp_moves_the_gradients_placed_on_its_paths_by_each_paths_bounds`, `group::tests::a_groups_warp_moves_its_own_a_nested_groups_and_a_compound_paths_gradients_by_their_bounds`, `group::tests::shape_art_moves_the_gradients_of_a_symbol_instances_art_and_a_compound_shape_with_a_warp`; render `objectfx::a_paths_gradient_moves_and_scales_with_its_warped_bounds`; engine `objexpand::a_placed_gradient_moved_by_a_warp_expands_as_the_canvas_draws_it`). Scores and hours unchanged.
@@ -893,6 +895,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- Link replies under `--automation-read-root`: `links.list`, `links.check`, `links.info` and `document.open`'s link rows leave out the path, found path and folder of a linked file outside the read roots, and the stored size and date of it in `links.info`; each row keeps its id, file name and status, and the document's links are not changed. `crates/engine/src/tests/linkspanel.rs` (`link_paths_outside_the_read_roots_are_left_out`), `crates/engine/src/tests/placed_document.rs` (`link_info_leaves_out_a_placed_documents_path_outside_the_read_roots`).
- Document replies under `--automation-read-root`: `document.inspect` gives `path` as null for a document file outside the read roots, and `document.json` names a linked image or placed file outside them by its file name alone, without its relative path, size or date, brush art included, leaves out a relative path that leads outside them and a stored brush entry that does not read as a brush, names a data set's image value outside them by its file name, and leaves an Export for Screens folder outside them out of `export_settings`; the document is not changed. `crates/engine/src/tests/placed_document.rs` (`document_replies_leave_out_paths_outside_the_read_roots`, `document_json_checks_brush_art_and_relative_paths_against_the_read_roots`).
- SVG output under `--automation-read-root`: `document.serialize`, `document.export`, `document.exportSelection`, `document.exportForScreens`, `assets.export`, the SVG and SVGZ saves, `file.exportAs` and the SVG Options dialog's Show Code refuse an SVG or SVGZ of a document that links a JavaScript file outside the read roots, before any file or folder is written, with an error that names no file or folder; a URL, a file inside the roots and a relative path that leads inside them are written as stored, and the person at the keyboard exports every link as stored. `crates/engine/src/tests/interactivity.rs` (`confined_svg_output_refuses_a_linked_javascript_file_outside_the_read_roots`, `svg_output_keeps_linked_javascript_files_a_caller_may_read`), `crates/ui-egui/src/tests/automation.rs` (`control_svg_export_refuses_a_linked_javascript_file_outside_the_read_root`), `crates/ui-egui/src/dialogs/svg_options.rs` (`show_code_leaves_out_a_linked_javascript_file_outside_the_read_roots`).
- Native document output under `--automation-read-root`: the same commands, `document.exportPdf` and `file.package` refuse a native file or template, an EPS file, a `.ai` or `.ait` file of every artboard (not a legacy version 7 file), a PDF of every artboard with Preserve Editing on, and a package, of a document that links a JavaScript file outside the read roots, before any file or folder is written, with the same error; a package is refused too when a linked native document, or the native document a linked PDF, `.ai` or EPS file carries, links one. A PDF or `.ai` file of some artboards or of the art's bounds, a PDF without Preserve Editing and an image are written, and linked files the caller may read are kept as stored. `crates/engine/src/tests/interactivity.rs` (`confined_native_output_refuses_a_linked_javascript_file_outside_the_read_roots`, `confined_output_without_the_document_or_with_scripts_the_caller_may_read_is_written`), `crates/engine/src/tests/package.rs` (`a_confined_package_refuses_a_linked_javascript_file_outside_the_read_root`), `crates/ui-egui/src/tests/automation.rs` (`control_native_export_refuses_a_linked_javascript_file_outside_the_read_root`).
- Linked images in SVG output under `--automation-read-root`: the same outputs, and `clipboard.exportSvg`, refuse an SVG or SVGZ that would name a linked image's file outside the read roots (`images: link`, an image whose pixels the document doesn't hold, or `preserveEditing`), before any file or folder is written, with an error that names no file or folder; Copy in a frame a request drives then puts no SVG on the system clipboard. Embedded pixels, a file inside the roots, a relative path that leads inside them and a URL are written as before, and the person at the keyboard exports every link as stored. The check covers the art drawn for placed documents and leaves out what the file leaves out: hidden art in symbols, patterns and graph designs, opacity masks in SVG Tiny 1.2, and objects drawn as images for effects SVG has no filter for. `crates/engine/src/tests/links.rs` (`confined_svg_output_refuses_a_linked_image_file_outside_the_read_roots`, `svg_output_names_linked_image_files_a_caller_may_read`, `confined_clipboard_svg_refuses_a_linked_image_file_outside_the_read_roots`, `confined_preserve_editing_svg_refuses_a_brush_library_entry_it_cannot_read`, `confined_svg_output_checks_only_the_linked_images_it_writes`, `confined_svg_output_writes_a_colorized_gray_image_without_its_file`, `confined_svg_output_checks_the_images_of_placed_documents`, `confined_svg_output_leaves_hidden_symbol_art_unchecked`, `confined_svg_tiny_output_leaves_opacity_mask_images_unchecked`, `confined_svg_output_checks_the_images_drawn_for_pixel_effects`), `crates/ui-egui/src/tests/automation.rs` (`control_svg_export_refuses_a_linked_image_file_outside_the_read_root`), `crates/ui-egui/src/dialogs/svg_options.rs` (`show_code_leaves_out_a_linked_image_file_outside_the_read_roots`).
- Clipboard flavors under `--automation-read-root`: `clipboard.flavours` leaves out the SVG, and its markup as text, that `clipboard.exportSvg` refuses. `crates/engine/src/tests/links.rs` (`confined_clipboard_flavours_leave_out_a_withheld_svg`).
- Preserve Editing SVG under `--automation-read-root`: the native document an SVG or SVGZ carries leaves out an Export for Screens folder outside the read roots, and keeps the other export settings and the art; the open document keeps the folder, and a folder inside the roots is kept. `crates/engine/src/tests/links.rs` (`confined_preserve_editing_svg_leaves_out_an_export_folder_outside_the_read_roots`).
@@ -987,6 +990,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- The Danish catalog (`crates/ui-egui/src/i18n/da.tsv`) has 1,985 more status and error message rows, 3,702 `@msg` rows in all, and the untranslated report's missing Danish messages go from 2,066 to 81: 40 that open pull requests translate, 38 that no catalog has a row for, and three unknown-parameter and range errors (``unknown parameter `{within}{key}`; {why}``, ``unknown parameter `{within}settings.{format}`; {why}`` and `{name} must be {lo}–{hi}{unit} (got {v})`) that open #7353 rewrites so that a catalog row can match them. A native speaker has not reviewed the wording.
- The Traditional Chinese catalog (`crates/ui-egui/src/i18n/zh-hant.tsv`) has an `@msg` row for the status and error messages the untranslated report (`untranslated_report`) finds in the sources, 3,438 `@msg` rows in all: the errors of commands, scripts, file import and export and plug-ins. The report lists 40 Traditional Chinese messages: open #7211, #7116 and #7330 add the rows for 38 of them, and the other 2 have no row in any catalog. A message with two placeholders in a row (`Template::parse` in `crates/ui-egui/src/i18n/catalog.rs`) is still shown in English.
- Localised UI: menus (in-window and native), panels, dialogs, toolbar and Preferences read from per-language catalogs (`crates/ui-egui/src/i18n`, see `docs/development.md`); Traditional Chinese (Taiwan), Simplified Chinese (mainland), Japanese, Korean, Vietnamese, German, Spanish, French, Italian, Polish, Brazilian Portuguese, Russian, Ukrainian, Georgian and Catalan ship complete, and Czech covers every menu label (and more), with system-locale detection on macOS, Windows, Linux and the web (the browser's languages, or `?lang=`), a Language preference and, on macOS, a VectorCraft ▸ Language menu. Names are never translated (fonts and their styles, layers, artboards, saved presets, user libraries, custom workspaces, recent files, plug-ins).
- The French catalog (`crates/ui-egui/src/i18n/fr.tsv`) follows the typography its header sets: a no-break space (U+00A0) before `:`, `;`, `?` and `!` and inside `« »`, and the typographic apostrophe `’` in elisions. Code in backticks and key/value examples keep their own punctuation. Evidence: `french_catalog_uses_nonbreaking_prose_punctuation` in `crates/ui-egui/src/i18n/tests.rs`.
- The Brazilian Portuguese catalog (`crates/ui-egui/src/i18n/pt-br.tsv`) has an `@msg` row for the status and error messages the untranslated report (`untranslated_report`) finds in the sources, 3,563 `@msg` rows in all, including the image export, color profile, color book, swatch exchange file, DXF import and Revolve errors. The report lists 55 Brazilian Portuguese messages: the composite font, SVG filter, read root, graph design, justification order and Blob Brush connect end errors that open #7211, #7378, #7405, #7116 and #7330 translate.
The counts that Package's status and question, the folder search of Missing Fonts and Find Linked Files, the modified and missing linked file prompts and the CSS Properties panel's notes show use the interface language's plural forms instead of a fixed "(s)" form. Evidence: `the_missing_links_note_uses_each_count_form` in `crates/ui-egui/src/dialogs/tests_package.rs`, `the_modified_links_question_uses_each_count_form` in `crates/ui-egui/src/dialogs/missing_links.rs`, `search_counts_use_each_count_form` in `crates/ui-egui/src/dialogs/missing_fonts/tests.rs` and `the_unnamed_objects_note_uses_each_count_form` in `crates/ui-egui/src/panels/tests_css_properties.rs`.
The status bar's messages for relinked, replaced, updated and embedded images, broken links, linked files that can't be read or changed on disk, images that can't be decoded, added and unavailable fonts, copied CSS, downloads and exports with their notes name one item in the singular and more in the plural, in English and in each language's plural forms (`counted_status_messages_take_the_plural_form` in `crates/ui-egui/src/i18n/tests.rs`).
@@ -1146,6 +1150,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
With the Selection or Group Selection tool, pressing E while dragging a marquee makes the marquee select only the objects that lie entirely inside it. Pressing E again switches the marquee back to its default selection.
The Lasso picks anchor points only on art a click can pick, and the Add Anchor Point, Delete Anchor Point, Anchor Point and Scissors tools pick anchor points and segments only on the selected paths and on art a click can pick: not on a Shaper Group's original shapes outside Construction mode, and in isolation mode only inside the isolated group or object. Smart Guides and Snap to Point do not snap to a Shaper Group's original shapes, and the reference point of the transform tools snaps to one only when it is selected, or under the pointer in Construction mode.
Enclosing Lasso provides whole-object enclosure selection under Object › Plug-ins and its own heading in All Tools. It has no default shortcut or Basic toolbar slot. It follows path curves and keeps partially enclosed objects out, including objects crossing a concave part of the loop. Ordinary group members can be selected individually; compound paths remain whole. This is a VectorCraft addition; scores and estimates are unchanged.
Polygonal Lasso selects anchor points (and gradient mesh points) inside a straight-edged loop, with the Lasso's rule for which points are inside, and is listed under Object › Plug-ins and under its own heading in All Tools. It has no default shortcut or Basic toolbar slot. Each click sets a vertex. A double-click, Enter or a click on the first vertex closes the loop, Backspace or Delete removes the last vertex, Escape drops the loop, and Shift keeps the next segment to 45° steps. Shift or Alt held at the first click adds to or subtracts from the selection. This is a VectorCraft addition; scores and estimates are unchanged.
Select by Artboards (Object › Plug-ins › Selection Tools, a VectorCraft addition: #5525, #5548, #5549) selects the objects overlapping, fully inside or fully outside one or more chosen artboards (`addon.select.byArtboards {artboards, relation}`). Overlapping is All on Active Artboard's test, shared as `select::on_artboard`; Fully inside means within one artboard, edges included; Fully outside means on none. It looks at what Select All takes, so hidden, locked and locked-artboard art stays out. Its dialog lists each artboard's number, name and size in the document's units, filters by name, chooses rows with click, Shift-click and Cmd/Ctrl-click, and fits a row's artboard in the window on double-click (`view.goToArtboard`). Tests: `crates/engine/src/cmd/addons/select/tests.rs`, `crates/ui-egui/src/addons/select/tests.rs`, `crates/engine/tests/command_sweep.rs`.
Select by Link Status (Object › Plug-ins › Selection Tools and the Links panel menu, a VectorCraft addition: #5526) selects the image objects and placed documents whose link is linked (its file found unchanged), embedded, missing or modified, as `links.list` reports it (`addon.select.byLinkStatus {status, ids?, add?, zoom?}`); Select Linked, Embedded, Missing and Modified are off when no image has that status and add to the selection with Shift. Objects that are hidden or locked, inside a hidden or locked object or layer, on a template layer, on a locked artboard, or outside the isolated group are left out (the `select::is_selectable` test) and returned with the reason, and the status bar says how many, in plural forms of every catalog. Select by Link Status… lists each image and placed document with its name, status and format, searches by name, filters by status, picks rows with checkboxes and All / None, and zooms to the selection with the existing Zoom to Selection (`addon.arrange.zoomSelection`). Missing-link markers on the canvas are #5547. Tests: `crates/engine/src/cmd/addons/select/tests.rs` (`by_link_status`), `crates/ui-egui/src/addons/select/link_status/tests.rs`, `crates/engine/tests/command_sweep.rs`.
A marquee selects a clip group, or an object on a layer with a clipping mask, only when it reaches the area inside the clipping path, and it measures the art only within that path's bounds. Within the bounds of a mask that is not a rectangle, it can still select art that the mask hides. Direct Selection's marquee still selects the hidden anchor points inside it (#2345).
@@ -1669,6 +1674,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- **Document Color Mode for effects and graphs:** File › Document Color Mode and `document.open {colorMode}` convert the colors of effects (Drop Shadow, Inner Glow, Outer Glow and the other effects with a color, on objects, their fills and strokes and in graphic styles) and the series paints and label styles that a graph keeps, so a graph drawn again from new data keeps the converted colors; File › Document Color Mode also converts the fill and stroke that new art takes. Undo restores the original new-art fill and stroke and Redo applies the conversion again.
- **Recolor Artwork layout (#3416):** the Edit chip list uses the modal scroll helper and its actual remaining height; the tab's minimum-height space scrolls with the chips. `tests_recolor` covers 5/20/200/400 colors, window resizing, 100/125/150/200% UI scaling, scrolling to and editing the final chip, Preview, Cancel, Confirm and Undo, alongside the existing #1733 drag regressions. Scores and estimates unchanged.
- **Recolor Artwork Edit displays:** buttons beside the Edit tab's wheel show the colors on a smooth color wheel, a segmented color wheel or as color bars ([Edit colors using Recolor Artwork](https://helpx.adobe.com/illustrator/desktop/manage-colors/modify-colors/edit-colors-using-edit-colors-dialog.html)). The segmented wheel draws 24 hues by 5 saturations as solid patches, and its markers move freely as on the smooth wheel. The bars show one solid bar per recolored color in row order: a click selects a bar for the color sliders, and a drag moves its row without changing a color ([Advanced recolor options overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/learn-color-basics/edit-colors-dialog-overview.html)). The dialog opens on the smooth wheel; `display` (`smooth`, `segmented`, `bars`) is the dialog field. `tests_recolor` covers switching, the dialog height, segmented dragging and Brightness, and bar selection, editing, reordering, scrolling, Preview, Cancel and OK. Scores and estimates unchanged.
- **Recolor Artwork Add Color and Remove Color tools:** under the display buttons beside the Edit tab's wheel, the Add Color tool adds the color clicked on either wheel to the color group, and the Remove Color tool removes the color whose marker is clicked; a color bar's right-click menu has Remove Color, and the base color can't be removed ([Advanced recolor options overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/learn-color-basics/edit-colors-dialog-overview.html), [Edit swatch groups using the color wheel](https://helpx.adobe.com/illustrator/desktop/manage-colors/modify-colors/edit-color-groups-using-the-color-wheel.html)). An added color is a new row with no current colors and `added: true`; unlike a row made with New Row, it adds its new color to a rewritten color group, after the group's other colors. VectorCraft's own rules: an added color takes the base color's brightness, and with art or a group a removed color's row stays with its current colors and no new color, so that art keeps its colors and the group's swatch at that place is removed. `wheelTool` (`add`, `remove`) is the dialog field. Tests: `the_add_color_tool_adds_a_row_with_no_current_colors`, `an_added_color_joins_the_color_group`, `the_remove_color_tool_removes_a_marker_but_not_the_base_colors` and `a_color_bars_menu_removes_its_color` in `crates/ui-egui/src/tests/recolor.rs`, `apply_params_give_the_group_added_colors_and_keep_its_other_colors` in `crates/ui-egui/src/dialogs/recolor.rs`, and `an_added_empty_row_gives_the_group_its_color_after_the_others` in `crates/engine/src/tests/recolor.rs`. Scores and estimates unchanged.
- **Recolor Artwork Find:** the Assign tab's Find button finds the colors of the selected rows in the art ([Advanced recolor options overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/learn-color-basics/edit-colors-dialog-overview.html)): while it is on, their art shows as the preview shows it and the rest of the selected art shows dimmed, until a second click ([archived help, Recolor Artwork](https://help.adobe.com/archive/en_US/illustrator/cs5/illustrator_cs5_help.pdf#page=149)). VectorCraft's own rules: a dimmed color is a 25% tint of its current color (or the nearest lighter tint when that one is a color a selected row lists), a color a selected row also lists is not dimmed, and Find records no undo step. `findColors` is the dialog field. Tests: `find_dims_the_colors_of_the_rows_not_selected` and `find_shows_the_selected_rows_art_and_dims_the_rest` in `crates/ui-egui/src/dialogs/recolor.rs`. Scores and estimates unchanged.
- **Recolor Artwork New Row:** the Assign tab's New Row button adds a row with no current colors, so current colors can be moved into it and take its new color ([Advanced recolor options overview](https://helpx.adobe.com/illustrator/desktop/manage-colors/learn-color-basics/edit-colors-dialog-overview.html), [Assign new colors to selected artworks](https://helpx.adobe.com/illustrator/desktop/manage-colors/modify-colors/assign-new-colors-to-selected-artwork.html)). VectorCraft's own rules: the row goes above the first selected row (at the top when none is selected) with that row's new color and becomes the selection, and Merge with it as the first selected row moves the other rows' colors into it. The button needs selected art. An empty row recolors nothing, does not count toward Colors, adds no library swatch and gives a rewritten color group no color. While it is empty, Save All Colors and a new color group saved from colors alone leave its new color out, the Edit tab's wheel, bars and chips do not show it and its sliders edit the base color instead, the harmony rules and linked moves leave its new color as it is, and the Color Theme Picker gives it no color. Tests: `a_new_row_goes_above_the_selection_and_takes_merged_colors`, `an_empty_row_gives_the_group_no_color`, `an_empty_row_gives_a_new_group_no_color`, `an_empty_row_takes_no_harmony_or_wheel_color`, `theme_picks_leave_an_empty_row_out`, `save_all_colors_leaves_an_empty_row_out` and `colors_merged_into_a_new_row_take_its_new_color` in `crates/ui-egui/src/dialogs/recolor.rs`, `an_empty_row_recolors_nothing` and `an_empty_row_adds_no_swatch_and_no_group_color` in `crates/engine/src/tests/recolor.rs`.
- **Edit Colors parameters:** `edit.colors.saturate` needs a number `intensity`, the value from -100% to 100% that Saturate takes ([Adjusting colors](https://web.archive.org/web/20230128232631/https://helpx.adobe.com/illustrator/using/adjusting-colors.html)), and answers "missing number `intensity`" without one; a number outside the range counts as its nearest end. A value that is not a number, such as `"40"`, is refused with `` `intensity` must be a number, not "40" ``, as in every command that needs a number (`tests::params::a_malformed_required_number_is_not_reported_as_missing`). `edit.colors.adjustBalance` refuses a channel and `color.harmony` refuses `steps` or `amount` that is not a number; both read `null` as a value left out. `tests::editcolors` and `tests::colorguide` cover them.
@@ -1850,6 +1856,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
A PDF-compatible `.ai` saved with Include Editing Data for Other Apps keeps the document's variables, data sets and the bindings of objects to variables in its editing copy, in the form the variable library reader above reads, so they come back when the file is opened. Bindings to layers, to type written as outlines, to graphs and to linked images written as other objects, data set values of graphs, and variables, data sets, bindings and values past the writer's limits are left out with a warning (#6024; `crates/eps/src/ai_editing/tests.rs` `variables_data_sets_and_bindings_are_read_back`; `crates/eps/src/ai_editing/writer/variables.rs` lists what is left out).
A PDF-compatible `.ai` saved with Include Editing Data for Other Apps keeps each wrap object's Text Wrap Options in its editing copy: the Offset, positive or negative, and Invert Wrap ([the help page](https://helpx.adobe.com/illustrator/desktop/design-with-text/add-manage-text/wrap-or-unwrap-text-around-objects.html)), in the form the `.ai` reader reads them (`text_wrap` in `crates/eps/src/import/ai/read/document.rs`), so they come back when the file is opened. An offset past the -1000 to 1000 pt the reader keeps is written as the nearer end of that range. On a large canvas the offset is written at the art's scale and comes back at its size. Art the writer draws for an object, such as a blend's steps or a symbol instance written as its art, has only that object's options, and a clipping path written as its fills and its strokes has its options once (`crates/eps/src/ai_editing/tests.rs` `text_wrap_options_are_written_and_read_back`, `drawn_art_keeps_only_its_objects_text_wrap`, `text_wrap_offsets_on_a_large_canvas_come_back_at_their_size`, `text_wrap_options_of_type_and_envelopes_are_read_back`, `a_clipping_path_written_as_its_paint_keeps_one_text_wrap`).
A clipping object whose clipped art is written cut to it (a group, an image, a symbol instance, type, or a path or compound path inside art cut to another clipping object) keeps its Text Wrap Options in the editing copy on an unpainted path, or compound path, of the outline area type wraps around, under the art it clips and locked or hidden as the object is. The `.ai` reader reads an unpainted path (`paint` in `crates/eps/src/import/ai/read/art.rs`) and gives it the options of the dictionary after it (`text_wrap` in `crates/eps/src/import/ai/read/document.rs`), so area type below the object wraps the same way when the file is opened. Without room for that path under the object limit, the options are left out (`crates/eps/src/ai_editing/tests.rs` `a_clipping_object_not_written_whole_keeps_its_text_wrap`, `a_clipping_objects_text_wrap_is_left_out_without_room`).
The same unpainted path also carries that clipping object's name, opacity mask and visibility variables, so a group, image, symbol instance, live object, type or path used as a clipping object and written cut to it opens with one object of its name, its opacity mask, and its visibility variables bound to it. The clipping object's fills and strokes keep the opacity mask they are drawn through, without the name. The `.ai` reader gives the unpainted path the name, mask and XML id of the dictionary after it (`art_dictionary` at `crates/eps/src/import/ai/read/document.rs:752`) and binds the variable library's `docRef` to that XML id (`doc_ref` at `crates/eps/src/import/ai/read/document.rs:1731`). Text and image variables of such a clipping object are left out with a warning, since the reader binds them only to type and linked images. Without room for the path the dictionary is left out, and without room for the mask's art only the mask is left out (`crates/eps/src/ai_editing/tests.rs` `a_cut_clipping_object_keeps_its_name_mask_and_variables`, `a_cut_clipping_objects_dictionary_is_left_out_without_room`, `a_cut_clipping_object_without_room_for_its_mask_gets_no_carrier`).
Area type wrapped only by plain saved paths, compound paths or groups remains editable in the `.ai` editing copy when each frame's wrap recomputes unchanged; other wrapped area type remains outlines. The `.ai` reader works the wrap out again from the objects above the type (`resolve_text_wrap` in `crates/eps/src/import/native/build.rs`), so the writer keeps type only where each wrap object is written as itself (one path with no paint, a solid fill or a plain solid stroke, a compound path of visible members, or a group of such objects, without effects, an opacity mask or clipping), its offset is within -1000 to 1000 pt, and the shapes of every area type in the file stay within the 2,000,000 anchors the reader copies; when art is left out at the object limit, such type is written as outlines. This is VectorCraft's own round-trip rule (`crates/eps/src/ai_editing/tests.rs` `area_type_wrapped_by_plain_objects_stays_type`, `area_type_wrapped_by_other_objects_stays_outlines`, `threaded_area_type_wrapped_by_plain_objects_stays_type`, `area_type_wrapped_on_a_large_canvas_stays_type`, `area_type_wrapped_past_the_reader_limit_stays_outlines`, `area_type_wrapped_past_the_object_limit_is_written_as_outlines`).
Type written as its outlines in the editing copy still wraps area type by its bounds, not by its glyphs, when the file is opened: the outlines' group ends with an unpainted rectangle at the type's bounds that carries its Text Wrap Options, in the form the `.ai` reader reads a path's options (`text_wrap` in `crates/eps/src/import/ai/read/document.rs`), and the group keeps the type's name (`crates/eps/src/ai_editing/tests.rs` `type_written_as_outlines_keeps_wrapping_by_its_bounds`).
A symbol instance written as its art, and a blend, mesh, repeat, placed document, intertwine or envelope written as a group of its art, likewise still wraps area type by its bounds when the file is opened, as it did before saving, not by the members of that art: the group starts with the same unpainted rectangle, which takes the object's lock and visibility, and the group keeps the object's name and transparency without options of its own. Area type in that art is above the rectangle, so the rectangle does not wrap it. The rectangle takes its place in the object limit before the art; without room for it, the options are left out with the limit's warning. An object without finite bounds keeps the options on its group. This is VectorCraft's own round-trip rule (`crates/eps/src/ai_editing/tests.rs` `live_art_written_as_a_group_keeps_wrapping_by_its_bounds`, `wrap_bounds_of_live_art_fit_the_object_limit_and_leave_area_type_in_the_art_unwrapped`, `live_art_without_bounds_keeps_its_text_wrap_on_the_group`).
+12 -7
View File
@@ -432,7 +432,7 @@ Inflate and Rotate has a **Shadows** switch with those three settings below it.
| Option | |
|---|---|
| Shadows | Off by default. On, the first light casts a hard-edged shadow of the solid, drawn behind it. |
| Shadows | Off by default. On, the first light casts a shadow of the solid, drawn behind it: hard-edged at the light's Softness 0 %, blurred above it. |
| Position | **Behind Object** (the default): on a plane square to the view, behind the object. **Below Object**: on the floor under the object, square to its own vertical axis and turned with it. |
| Distance from Object | 0–100 %, default 0 %: how far the plane is from the object, as a share of the object's largest size. |
| Shadow Bounds | 10–400 %, default 100 %: how far the plane reaches. At 100 % it is a square four times the object's largest size across, about the foot of the object's center; the shadow is cut at its edges. |
@@ -449,14 +449,19 @@ Our reading:
Intensity is 0 %, or when it does not reach the plane: a light behind the object casts none behind it, and a
light from under the floor casts none below it. A fill, stroke or group member at 0 % opacity casts none. With no X rotation the floor is seen edge-on, so a
shadow below draws nothing until the object is tilted (the default Off-Axis Front position shows it).
- Softness is not applied to the shadow, and only the first light casts one.
- The first light's Softness blurs the shadow with a Gaussian Blur: at 0 % it stays the hard-edged path, and above
it the blur radius is Softness × the object's largest size × (5 % + 20 % × Distance from Object), at most
1,000 pt. At 100 % Softness a 100 pt object casts a shadow blurred by 5 pt on a plane that touches it and by
25 pt at 100 % Distance. This mapping is our own. The blur scales with the object, and it draws, takes room and
exports as a Gaussian Blur effect does. Only the first light casts a
shadow.
- A shadow is cast from at most 327,680 faces, the solids of one object together (our own limit). Past it, a
command is refused with "The 3D shadow is too complex; turn Shadows off or simplify the art", and a loaded
file draws the source path. A command checks the shadow from the same builds that check the solids, as
drawing casts it, so each solid is built once. A stroke whose solid is left out of the art (past its own
limits) casts no shadow.
- Canvas, SVG and PDF exports draw the shadow, the art's bounds take it in, and Expand Appearance keeps it as a
path below the faces. Extrude & Bevel (Classic), Revolve (Classic) and Rotate (Classic) have no shadow.
- Canvas, SVG and PDF exports draw the shadow, the art's bounds take it in (with its blur), and Expand Appearance
keeps it below the faces: a hard shadow as a path, a blurred one as an image. Extrude & Bevel (Classic), Revolve (Classic) and Rotate (Classic) have no shadow.
## Graphics
@@ -562,10 +567,10 @@ and [Create 3D objects](https://helpx.adobe.com/illustrator/desktop/special-effe
pages, and the archived Extrude & Bevel option list (depth 0–2,000, cap on/off, bevel height, bevel extent in or
out, perspective). No Adobe software, assets, presets or bevel shapes were used.
- **Materials** (base and Adobe Substance), graphics on Inflate and on Extrude & Bevel's walls and bevels, soft
shadows, shadows of lights after the first, and **ray-traced rendering** are not built: shading uses directional
- **Materials** (base and Adobe Substance), graphics on Inflate and on Extrude & Bevel's walls and bevels,
shadows of lights after the first, and **ray-traced rendering** are not built: shading uses directional
lights, in the paint of the fill or stroke the solid is built for ([Fills and strokes](#fills-and-strokes)), and
the shadow is hard-edged ([Shadows](#shadows)). Graphics map onto planar faces and Revolve's side only
only the first light casts a shadow ([Shadows](#shadows)). Graphics map onto planar faces and Revolve's side only
([Graphics](#graphics)).
- The bevel shapes and their names are our own; custom bevel paths are not supported.
- Visibility is a painter's algorithm: faces of a closed solid turned away are left out, and the rest are drawn