Merge main into feat/cut-order

This commit is contained in:
dotCooCoo
2026-11-11 23:30:59 -08:00
103 changed files with 2972 additions and 353 deletions
+18 -2
View File
@@ -21,7 +21,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Export DXF",
[],
None,
"{path?, dxfPreset?: custom (default)|cnc (CNC / CAM: version 2000, the oldest version that has both lightweight polylines and lineweights; unit mm, scale 1; colors 256, all 2000 holds; preserve editability and alterPaths false, so strokes stay center lines; outlineText true, so type is paths; rasterFormat png; the options given override it), version?: R12|R13|R14|2000|2004|2007|2010|2013|2018 (default), unit?: mm (default; any unit name: pt, in, cm…), scale?: 1 (drawing units per unit), scaleLineweights?: false, colors?: 8|16|256|true (default; true colour needs 2004+, else 256), rasterFormat?: png (default)|jpeg (placed images, written next to the file), preserve?: appearance (default: type as outlines; strokes a CAD line can't draw as filled outlines; brush art)|editability (type as text; every stroke a line with its lineweight and dashes), alterPaths?: false (strokes a CAD line can't draw as their filled outlines, with editability too; also strokes wider than 2.11 mm, and every stroke in R13 and R14), outlineText?: false, selectedOnly?: false (the selected objects, in their layers), artboard?: 0 (the origin is its bottom-left corner), useArtboards?: true (one drawing per chosen artboard, artboards?/range?, holding the art over it: {stem}-{artboard}.dxf) | false (the origin at the art's bounds)} → {path, bytes, warnings, files?, linked?: [image files]}; no path → {dataBase64, …, linked?: [{name, dataBase64}]}. Layers become DXF layers (hidden: off; locked; non-printing: not plotted); paths become polylines and splines, fills their outlines (which laser and cutter software reads) and solid hatches. Same as document.export {format: dxf}. A key DXF doesn't take is refused",
"{path?, dxfPreset?: custom (default)|cnc (CNC / CAM: version 2000, the oldest version that has both lightweight polylines and lineweights; unit mm, scale 1; colors 256, all 2000 holds; preserve editability and alterPaths false, so strokes stay center lines; outlineText true, so type is paths; includeImages and includeHatches false, so fills are their outlines and no image files are written; rasterFormat png; the options given override it), version?: R12|R13|R14|2000|2004|2007|2010|2013|2018 (default), unit?: mm (default; any unit name: pt, in, cm…), scale?: 1 (drawing units per unit), scaleLineweights?: false, colors?: 8|16|256|true (default; true colour needs 2004+, else 256), rasterFormat?: png (default)|jpeg (placed images, written next to the file), includeImages?: true (false: placed images and their files are left out), includeHatches?: true (false: fills are their outlines, without solid hatches), preserve?: appearance (default: type as outlines; strokes a CAD line can't draw as filled outlines; brush art)|editability (type as text; every stroke a line with its lineweight and dashes), alterPaths?: false (strokes a CAD line can't draw as their filled outlines, with editability too; also strokes wider than 2.11 mm, and every stroke in R13 and R14), outlineText?: false, selectedOnly?: false (the selected objects, in their layers), artboard?: 0 (the origin is its bottom-left corner), useArtboards?: true (one drawing per chosen artboard, artboards?/range?, holding the art over it: {stem}-{artboard}.dxf) | false (the origin at the art's bounds)} → {path, bytes, warnings, files?, linked?: [image files]}; no path → {dataBase64, …, linked?: [{name, dataBase64}]}. Layers become DXF layers (hidden: off; locked; non-printing: not plotted); paths become polylines and splines, fills their outlines (which laser and cutter software reads) and solid hatches. Same as document.export {format: dxf}. A key DXF doesn't take is refused",
has_doc,
export_dxf
)]
@@ -37,7 +37,7 @@ pub(crate) const OPTIONS: &[FormatOption] = &[
name: "dxfPreset",
ty: "string",
default: "\"custom\"",
description: "custom, or cnc (CNC / CAM: version 2000, mm, 256 colors, editability, type as outlines, PNG images); the options given override it",
description: "custom, or cnc (CNC / CAM: version 2000, mm, 256 colors, editability, type as outlines, no images, no fill hatches); the options given override it",
},
FormatOption { name: "version", ty: "string", default: "\"2018\"", description: "R12, R13, R14, 2000, 2004, 2007, 2010, 2013 or 2018" },
FormatOption {
@@ -60,6 +60,18 @@ pub(crate) const OPTIONS: &[FormatOption] = &[
default: "\"png\"",
description: "png or jpeg: the files placed images are written to, next to the drawing",
},
FormatOption {
name: "includeImages",
ty: "boolean",
default: "true",
description: "placed images are written, linked to their files; false leaves them and their files out",
},
FormatOption {
name: "includeHatches",
ty: "boolean",
default: "true",
description: "filled areas get a solid hatch after their outlines; false writes the outlines alone",
},
FormatOption {
name: "preserve",
ty: "string",
@@ -133,6 +145,8 @@ struct Params {
scale_lineweights: Option<bool>,
colors: Option<Value>,
raster_format: Option<String>,
include_images: Option<bool>,
include_hatches: Option<bool>,
preserve: Option<String>,
alter_paths: Option<bool>,
outline_text: Option<bool>,
@@ -176,6 +190,8 @@ fn parse(p: &Value) -> Result<(DxfOptions, ArtboardPick)> {
scale_lineweights: q.scale_lineweights.unwrap_or(d.scale_lineweights),
colors: choice("colors", q.colors.as_ref().map(text), ColorDepth::from_id, d.colors, "8, 16, 256 or true")?,
raster: choice("rasterFormat", q.raster_format, RasterFormat::from_id, d.raster, "png or jpeg")?,
include_images: q.include_images.unwrap_or(d.include_images),
include_hatches: q.include_hatches.unwrap_or(d.include_hatches),
preserve: choice("preserve", q.preserve, Preserve::from_id, d.preserve, "appearance or editability")?,
alter_paths: q.alter_paths.unwrap_or(d.alter_paths),
outline_text: q.outline_text.unwrap_or(d.outline_text),
+47
View File
@@ -84,6 +84,11 @@ fn the_cnc_preset_sets_the_options_that_are_not_given() {
true
)
);
assert_eq!((o.include_images, o.include_hatches), (false, false), "CNC / CAM leaves out images and fill hatches");
let given = dxf::options(&json!({"dxfPreset": "cnc", "includeImages": true, "includeHatches": true})).unwrap();
assert_eq!((given.include_images, given.include_hatches), (true, true), "the options given override it");
let custom = dxf::options(&json!({})).unwrap();
assert_eq!((custom.include_images, custom.include_hatches), (true, true), "Custom keeps both");
assert_eq!(dxf::options(&json!({})).unwrap().version, vectorcraft_cad::DxfVersion::R2018, "custom by default");
let e = s.execute("document.exportDxf", &json!({"dxfPreset": "laser"})).unwrap_err().to_string();
assert!(e.contains("custom or cnc"), "{e}");
@@ -151,6 +156,44 @@ fn placed_images_come_back_as_linked_files() {
let _ = std::fs::remove_dir_all(dir);
}
/// `includeImages` and `includeHatches` leave out placed images (with their files) and fill
/// hatches, each on its own, through both commands, with and without a path; CNC / CAM leaves
/// out both, and the options given override it.
#[test]
fn placed_images_and_fill_hatches_can_be_left_out() {
let mut s = super::tests_svg::image_session();
s.execute("paint.setFill", &json!({"color": "#ff0000"})).unwrap();
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 1, "height": 1})).unwrap();
let counts = |r: &Value| {
let e = entities(&text(r));
let n = |k: &str| e.iter().filter(|x| *x == k).count();
(n("LWPOLYLINE"), n("HATCH"), n("IMAGE"), r.get("linked").and_then(Value::as_array).map_or(0, Vec::len))
};
let warned = |r: &Value, w: &str| r["warnings"].as_array().unwrap().iter().any(|x| x.as_str().is_some_and(|x| x.starts_with(w)));
let all = s.execute("document.export", &json!({"format": "dxf"})).unwrap();
assert_eq!(counts(&all), (1, 1, 1, 1));
let r = s.execute("document.export", &json!({"format": "dxf", "includeImages": false})).unwrap();
assert_eq!(counts(&r), (1, 1, 0, 0));
assert!(warned(&r, "placed images are left out") && !warned(&r, "fill hatches"), "{r}");
let r = s.execute("document.exportDxf", &json!({"includeHatches": false})).unwrap();
assert_eq!(counts(&r), (1, 0, 1, 1));
assert!(warned(&r, "fill hatches are left out") && !warned(&r, "placed images"), "{r}");
let r = s.execute("document.exportDxf", &json!({"dxfPreset": "cnc"})).unwrap();
assert_eq!(counts(&r), (1, 0, 0, 0));
let r = s.execute("document.export", &json!({"format": "dxf", "dxfPreset": "cnc", "includeImages": true})).unwrap();
assert_eq!(counts(&r), (1, 0, 1, 1));
// With a path, no image file is written next to the drawing.
let dir = std::env::temp_dir().join(format!("vc-dxf-out-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("cut.dxf").to_string_lossy().to_string();
let r = s.execute("document.exportDxf", &json!({"path": path, "dxfPreset": "cnc"})).unwrap();
assert!(r.get("linked").is_none(), "{r}");
let files: Vec<String> = std::fs::read_dir(&dir).unwrap().filter_map(|e| e.ok()).map(|e| e.file_name().to_string_lossy().to_string()).collect();
assert_eq!(files, ["cut.dxf"]);
let _ = std::fs::remove_dir_all(dir);
}
/// Two placed images whose pixel data can't be decoded are left out of the drawing and get no
/// linked file, and `warnings` holds the note raster exports give, once, without naming either
/// image's key.
@@ -181,6 +224,8 @@ fn bad_dxf_options_are_refused() {
json!({"rasterFormat": "gif"}),
json!({"preserve": "both"}),
json!({"alterPaths": "yes"}),
json!({"includeImages": "no"}),
json!({"includeHatches": 0}),
] {
let e = s.execute("document.exportDxf", &p).unwrap_err().to_string();
assert!(e.contains("DXF"), "{p}: {e}");
@@ -203,6 +248,8 @@ fn formats_list_dxf_and_what_can_not_be_written() {
"scaleLineweights",
"colors",
"rasterFormat",
"includeImages",
"includeHatches",
"preserve",
"alterPaths",
"outlineText",
+56 -7
View File
@@ -1,5 +1,7 @@
use std::collections::BTreeSet;
use vectorcraft_doc::live::BlendSpineMode;
use super::common::{
DEFAULT_DISTANCE, DEFAULT_STEPS, ease_param, fix_ids, ids_json, is_blend, orientation_param, percent_param, roots_param, selected_of,
spacing_param, starts_param, wrap,
@@ -61,6 +63,19 @@ fn extend_spine(spec: &mut BlendSpec, old: &[Arc<Node>], old_spec: &BlendSpec, k
spec.spine = Some(path);
}
/// Does `p` set easing (`easingType` or `ramp`)? Easing needs a spine.
fn gives_easing(p: &Value) -> bool {
["easingType", "ramp"].iter().any(|key| p.get(*key).is_some_and(|v| !v.is_null()))
}
/// The Create Spine mode `p` gives as `key`, or `current` when it is omitted or null.
fn spine_mode_param(p: &Value, cmd: &str, key: &str, current: BlendSpineMode) -> Result<BlendSpineMode> {
match p.get(key).filter(|v| !v.is_null()) {
None => Ok(current),
Some(v) => v.as_str().and_then(BlendSpineMode::from_id).ok_or_else(|| bad(cmd, format!("`{key}` must be one of auto, always, never"))),
}
}
pub(super) fn blend_make(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "object.blend.make";
let roots = roots_param(s, p)?;
@@ -69,16 +84,22 @@ pub(super) fn blend_make(s: &mut Session, p: &Value) -> Result<Value> {
}
let starts = starts_param(p, &roots)?;
let base = first_blend(&s.doc()?.doc, &roots);
let defaults = s.prefs.blend_options.unwrap_or_default();
// Create Spine applies to a new blend; one taking more keys keeps whether it has a spine.
let create_spine = spine_mode_param(p, C, "createSpine", defaults.create_spine)?;
let cur = match base.as_ref().map(|n| &n.kind) {
Some(NodeKind::Blend { spec, .. }) => BlendDefaults { spacing: spec.spacing, orientation: spec.orientation },
_ => s.prefs.blend_options.unwrap_or_default(),
Some(NodeKind::Blend { spec, .. }) => BlendDefaults { spacing: spec.spacing, orientation: spec.orientation, ..defaults },
_ => defaults,
};
let spacing = spacing_param(p, C, cur.spacing)?;
let orientation = orientation_param(p, cur.orientation);
let (ease0, color0) = match base.as_ref().map(|n| &n.kind) {
Some(NodeKind::Blend { spec, .. }) => (spec.ease, spec.color_shift),
_ => Default::default(),
let (ease0, color0, no_spine) = match base.as_ref().map(|n| &n.kind) {
Some(NodeKind::Blend { spec, .. }) => (spec.ease, spec.color_shift, spec.no_spine),
_ => (Default::default(), 0.0, !create_spine.creates_spine()),
};
if no_spine && gives_easing(p) {
return Err(bad(C, "the blend has no spine"));
}
let ease = ease_param(p, C, ease0)?;
let color_shift = percent_param(p, C, "colorShift", color0, -100.0)?;
let id = s.edit("Make Blend", |d, sel| {
@@ -91,7 +112,7 @@ pub(super) fn blend_make(s: &mut Session, p: &Value) -> Result<Value> {
n.knockout = vectorcraft_doc::Knockout::On;
n
});
let mut spec = BlendSpec { spacing, orientation, ease, color_shift, starts, ..Default::default() };
let mut spec = BlendSpec { spacing, orientation, ease, color_shift, starts, no_spine, ..Default::default() };
if let NodeKind::Blend { children: old, spec: old_spec } = &n.kind {
extend_spine(&mut spec, old, old_spec, &children);
}
@@ -346,9 +367,12 @@ pub(super) fn blend_options(s: &mut Session, p: &Value) -> Result<Value> {
// Nothing to set them on: the options new blends start with (easing is per blend).
let d = s.prefs.blend_options.unwrap_or_default();
let spacing = spacing_param(p, C, d.spacing)?;
s.prefs.blend_options = Some(BlendDefaults { spacing, orientation: orientation_param(p, d.orientation) });
s.prefs.blend_options = Some(BlendDefaults { spacing, orientation: orientation_param(p, d.orientation), ..d });
return Ok(json!({ "defaults": true }));
};
if gives_easing(p) && any_without_spine(s) {
return Err(bad(C, "the blend has no spine"));
}
let spacing = spacing_param(p, C, cur.spacing)?;
let orientation = orientation_param(p, cur.orientation);
let ease = ease_param(p, C, cur.ease)?;
@@ -384,6 +408,7 @@ pub(super) fn blend_info(s: &mut Session, _: &Value) -> Result<Value> {
v["colorShift"] = json!(spec.color_shift);
v["starts"] = json!((0..keys.len()).map(|i| spec.start(i)).collect::<Vec<_>>());
v["keys"] = json!(keys.iter().map(|k| k.0).collect::<Vec<_>>());
v["hasSpine"] = json!(!spec.no_spine);
if let Some(NodeKind::Blend { children, .. }) = s.doc()?.doc.node(id).map(|n| &n.kind)
&& let Some((path, anchors)) = live::blend_spine(children, &spec)
&& let Some(sp) = path.subpaths.first()
@@ -403,6 +428,19 @@ pub(super) fn blend_info(s: &mut Session, _: &Value) -> Result<Value> {
})
}
/// The Blend panel's Create Spine: with `mode`, sets whether new blends get a spine; without, reads
/// it. A tool setting kept with the preferences, not an undo step; blends already made keep theirs.
pub(super) fn blend_create_spine(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "object.blend.createSpine";
let mut d = s.prefs.blend_options.unwrap_or_default();
let mode = spine_mode_param(p, C, "mode", d.create_spine)?;
if mode != d.create_spine {
d.create_spine = mode;
s.prefs.blend_options = Some(d);
}
Ok(json!({ "mode": mode.id() }))
}
pub(super) fn blend_expand(s: &mut Session, _: &Value) -> Result<Value> {
let blends = selected_of(s, is_blend);
let ids = s.edit("Expand Blend", |d, sel| {
@@ -507,6 +545,8 @@ pub(super) fn blend_replace_spine(s: &mut Session, _: &Value) -> Result<Value> {
let spine = d.node(path).and_then(|n| n.path_data().cloned()).ok_or(EngineError::NoNode(path))?;
d.remove(path)?;
if let Some(NodeKind::Blend { children, spec }) = d.node_mut(b).map(|n| &mut n.kind) {
// A blend made without a spine gets this one.
spec.no_spine = false;
spec.spine = Some(spine);
spec.key_anchors.clear();
keys_to_spine(children, spec);
@@ -517,7 +557,16 @@ pub(super) fn blend_replace_spine(s: &mut Session, _: &Value) -> Result<Value> {
ok()
}
/// Is any selected blend one made without a spine?
fn any_without_spine(s: &Session) -> bool {
let Ok(st) = s.doc() else { return false };
selected_of(s, is_blend).iter().any(|b| matches!(st.doc.node(*b).map(|n| &n.kind), Some(NodeKind::Blend { spec, .. }) if spec.no_spine))
}
pub(super) fn blend_reverse_spine(s: &mut Session, _: &Value) -> Result<Value> {
if any_without_spine(s) {
return Err(bad("object.blend.reverseSpine", "the blend has no spine"));
}
edit_blends(s, "Reverse Spine", |children, spec| {
if spec.spine.is_some() && pin(children, spec) {
// The keys keep their anchors, which now count from the other end.
+16 -7
View File
@@ -1,6 +1,6 @@
use super::blend::{
blend_expand, blend_info, blend_make, blend_options, blend_release, blend_replace_spine, blend_reverse_spine, blend_reverse_stack,
spine_add_anchor, spine_convert_anchor, spine_move_anchor, spine_remove_anchor, spine_reshape_segment,
blend_create_spine, blend_expand, blend_info, blend_make, blend_options, blend_release, blend_replace_spine, blend_reverse_spine,
blend_reverse_stack, spine_add_anchor, spine_convert_anchor, spine_move_anchor, spine_remove_anchor, spine_reshape_segment,
};
use super::common::{has_blend, has_envelope, has_mesh};
use super::envelope::{
@@ -18,7 +18,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Make",
["Object", "Blend"],
Some("Cmd+Alt+B"),
"{ids?, steps?: n | distance?: pt | smooth?: bool, orientation?: page|path (default: the Blend Options set with nothing selected, else smooth colour and page), starts?: [anchor index | null, …] (per object of `ids`, else of the selection in paint order: the anchor of its first subpath the blend starts from; an open path's last anchor runs it the other way), spacing?: smooth|steps|distance (with value), value?: n, easingType?: easeIn|easeOut|easeInOut|easeOutIn, ramp?: pct (0..100), colorShift?: pct (-100..100; 0: even)} blend the selected objects (paint order) into a live blend; a blend among them takes the others in as more key objects (keeping its options, name and transparency) instead of nesting → {id}",
"{ids?, steps?: n | distance?: pt | smooth?: bool, orientation?: page|path (default: the Blend Options set with nothing selected, else smooth colour and page), starts?: [anchor index | null, …] (per object of `ids`, else of the selection in paint order: the anchor of its first subpath the blend starts from; an open path's last anchor runs it the other way), spacing?: smooth|steps|distance (with value), value?: n, easingType?: easeIn|easeOut|easeInOut|easeOutIn, ramp?: pct (0..100), colorShift?: pct (-100..100; 0: even), createSpine?: auto|always|never (default: the mode object.blend.createSpine sets; never: a blend without a spine, which takes no easing)} blend the selected objects (paint order) into a live blend; a blend among them takes the others in as more key objects (keeping its options, name, transparency and whether it has a spine) instead of nesting → {id}",
has_doc,
blend_make
),
@@ -27,7 +27,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Release",
["Object", "Blend"],
Some("Cmd+Alt+Shift+B"),
"{} release the selected blends: the key objects come back and the spine stays as a path with no fill or stroke, below them; a blend with a name, opacity, blend mode, isolation, opacity mask or appearance of its own comes back as a group keeping them (and its knockout) → {ids (the keys), spines: [ids], groups: [ids]}",
"{} release the selected blends: the key objects come back and the spine (if the blend has one) stays as a path with no fill or stroke, below them; a blend with a name, opacity, blend mode, isolation, opacity mask or appearance of its own comes back as a group keeping them (and its knockout) → {ids (the keys), spines: [ids], groups: [ids]}",
has_blend,
blend_release
),
@@ -40,6 +40,15 @@ pub fn specs() -> Vec<CommandSpec> {
always,
blend_options
),
cmd!(
"object.blend.createSpine",
"Create Spine",
[],
None,
"{mode?: auto|always|never} the Blend panel's Create Spine: whether new blends get a spine (auto and always: the straight lines between the key centers, as before; never: no spine to show, edit, reverse or release, and no easing, until Replace Spine gives one); with no `mode`, reads it; blends already made keep theirs (a tool setting kept with the preferences, not an undo step) → {mode}",
always,
blend_create_spine
),
cmd!(
"object.blend.expand",
"Expand",
@@ -54,7 +63,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Replace Spine",
["Object", "Blend"],
None,
"{} use the selected path as the spine of the selected blend (the path is consumed)",
"{} use the selected path as the spine of the selected blend (the path is consumed); a blend made without a spine gets this one",
has_blend,
blend_replace_spine
),
@@ -63,7 +72,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Reverse Spine",
["Object", "Blend"],
None,
"{} reverse the order of the key objects along the spine",
"{} reverse the order of the key objects along the spine; an error when a selected blend has no spine",
has_blend,
blend_reverse_spine
),
@@ -72,7 +81,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Blend Info",
[],
None,
"{} the options of the first selected blend, else those new blends start with → {target: blend|defaults, id?, spacing: smooth|steps|distance, steps, distance, orientation: page|path, easingType?: easeIn|easeOut|easeInOut|easeOutIn, ramp?: pct, colorShift?: pct, keys?: [ids], starts?: [anchor|null], spine?: {anchors: [{x, y, in: [x, y], out: [x, y]}], closed, keyAnchors: [anchor each key sits on] | null (keys spread evenly: a spine from Replace Spine), explicit: false for the straight lines between the key centres}}",
"{} the options of the first selected blend, else those new blends start with → {target: blend|defaults, id?, spacing: smooth|steps|distance, steps, distance, orientation: page|path, easingType?: easeIn|easeOut|easeInOut|easeOutIn, ramp?: pct, colorShift?: pct, keys?: [ids], starts?: [anchor|null], hasSpine?: false for a blend made without a spine (no `spine` then), spine?: {anchors: [{x, y, in: [x, y], out: [x, y]}], closed, keyAnchors: [anchor each key sits on] | null (keys spread evenly: a spine from Replace Spine), explicit: false for the straight lines between the key centres}}",
always,
blend_info
),
+1 -1
View File
@@ -52,7 +52,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Reflect…",
["Object", "Transform"],
None,
"{ids?: [id…] (selected first; default: the selection), axis: \"vertical\"|\"horizontal\"|deg, origin?, copy?, objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size)}. With anchors selected with Direct Selection (and no copy), only those anchors and their handles transform, about the centre of their own box.",
"{ids?: [id…] (selected first; default: the selection), axis: \"vertical\"|\"horizontal\"|deg (the mirror line, counter-clockwise from horizontal; 0: horizontal; omitted: vertical), origin?, copy?, objects?: bool (Transform Objects, default true; false: the art stays and, with patterns, only its pattern tiles transform), patterns?: bool (Transform Patterns: pattern fills and strokes transform with the art; default: prefs transformPatternTiles), typeAreas?: bool (area type: the frame is reshaped and the text reflows at its size)}. With anchors selected with Direct Selection (and no copy), only those anchors and their handles transform, about the centre of their own box.",
has_selection,
reflect
),
+6 -4
View File
@@ -760,14 +760,16 @@ fn install(s: &mut Session, p: &Value) -> Result<Value> {
// When the write failed, the old stored module stays in the folder and needs its grant at
// the next launch. A grant that can't be removed still approves the old bytes, so the store
// gets the module it held back. When that module can't be read or written back, or there
// was none, no module goes with the grant, and the grant stops counting for this session. A
// grants file that is too large or doesn't hold a list approves nothing, and the new module
// stays; one that can't be opened or read may approve the old bytes once it reads again.
// was none, no module goes with the grant, and the grant stops counting for every session in
// the process attached to the folder. A grants file that is too large or doesn't hold a list
// approves nothing, and the new module stays; one that can't be opened or read may approve
// the old bytes once it reads again.
let writes = s.grant_writes();
if stored && !s.store_grant(&m.id, None) && s.holds_plugin_grant(&m.id) {
let back = previous.as_ref().is_ok_and(|held| s.put_back_plugin(plugin.id(), held.as_deref()));
stored = !back && holds_new(s);
if !back || matches!(previous, Ok(None)) {
s.ignore_stored_grant(&m.id);
s.ignore_stored_grant(&m.id, writes);
}
}
}
@@ -676,6 +676,7 @@ pub(super) const DENIED: &[&str] = &[
"addon.pen.nextSegment",
"effect.refreshDeferred",
"graphicStyle.setOptions",
"object.blend.createSpine",
"object.blend.options",
"object.liquify",
"object.pathfinder.options",
+40 -6
View File
@@ -769,7 +769,7 @@ impl Session {
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!(query "prefs.get", "Get Preferences", [], None, "{key?} → the value of one preference (or preference group: eyedropper), or {prefs: {…all…}}", always, get),
cmd!(query "prefs.get", "Get Preferences", [], None, "{key?} → the value of one preference (or preference group: eyedropper), or {prefs: {…all…}}; under automation read roots a folder preference outside them is null, and an export preset's folder outside them is left out", always, get),
cmd!(
query "prefs.set",
"Set Preference",
@@ -780,7 +780,7 @@ pub fn specs() -> Vec<CommandSpec> {
set
),
cmd!(query "prefs.reset", "Reset Preferences", [], None, "{category?} reset one category (or everything) to defaults", always, reset),
cmd!(query "prefs.list", "List Preferences", [], None, "{} → [{key, category, section, label, kind, value, …}] every preference", always, list),
cmd!(query "prefs.list", "List Preferences", [], None, "{} → [{key, category, section, label, kind, value, …}] every preference; under automation read roots a folder preference's value outside them is null", always, list),
cmd!(
query "prefs.export",
"Export Preferences",
@@ -886,8 +886,42 @@ fn import(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({ "imported": values.len() }))
}
/// The preferences that name a folder: the [`FOLDER_PREFS`] and the scratch disks.
const PATH_PREFS: [&str; 6] = ["fontsFolder", "pluginsFolder", "scratchPrimary", "scratchSecondary", "recoveryFolder", "templatesFolder"];
/// The scratch disk choices that are not folders.
const SCRATCH_CHOICES: [&str; 2] = ["Startup", "None"];
/// The preferences as `prefs.get`, `prefs.list`, `prefs.set` and `prefs.reset` show them to the
/// request being served. Under automation read roots, a folder preference ([`PATH_PREFS`]) outside
/// them is `null`, as `ui.inspect` leaves it out, and an export preset's `folder` outside them is
/// left out. An empty value (the default folder) and a scratch
/// disk choice ([`SCRATCH_CHOICES`]) are shown. Without roots the preferences are shown as they are.
fn shown_prefs(prefs: &Prefs) -> Value {
let mut all = prefs.to_json();
if crate::file_access::current().is_none() {
return all;
}
// The app trims a folder before it uses it.
let hidden = |path: &str| !path.trim().is_empty() && crate::file_access::check_read(path.trim()).is_err();
for key in PATH_PREFS {
let Some(path) = all[key].as_str() else { continue };
if hidden(path) && !(key.starts_with("scratch") && SCRATCH_CHOICES.contains(&path.trim())) {
all[key] = Value::Null;
}
}
if let Some(presets) = all.get_mut("screenExportPresets").and_then(Value::as_array_mut) {
for settings in presets.iter_mut().filter_map(|p| p.get_mut("settings").and_then(Value::as_object_mut)) {
if settings.get("folder").and_then(Value::as_str).is_some_and(hidden) {
settings.remove("folder");
}
}
}
all
}
fn get(s: &mut Session, p: &Value) -> Result<Value> {
let all = s.prefs.to_json();
let all = shown_prefs(&s.prefs);
match str_param(p, "key") {
Some(k) if spec(k).is_some() || PREF_GROUPS.contains(&k) => Ok(all[k].clone()),
Some(k) => Err(bad("prefs.get", format!("unknown preference `{k}`"))),
@@ -915,7 +949,7 @@ fn set(s: &mut Session, p: &Value) -> Result<Value> {
if document_units && values.contains_key("unitsGeneral") && s.active().is_some() {
s.set_document_units(s.default_units())?;
}
let all = s.prefs.to_json();
let all = shown_prefs(&s.prefs);
Ok(Value::Object(values.keys().map(|k| (k.clone(), all[k.as_str()].clone())).collect()))
}
@@ -929,11 +963,11 @@ fn reset(s: &mut Session, p: &Value) -> Result<Value> {
let mut next = s.prefs.clone();
next.reset(cat);
s.apply_prefs(next);
Ok(json!({ "prefs": s.prefs.to_json() }))
Ok(json!({ "prefs": shown_prefs(&s.prefs) }))
}
fn list(s: &mut Session, _: &Value) -> Result<Value> {
let all = s.prefs.to_json();
let all = shown_prefs(&s.prefs);
Ok(Value::Array(
PREF_SPECS
.iter()
@@ -140,6 +140,35 @@ fn block_turns_off_keeping_its_sizes_and_records_nothing_when_nothing_changes()
assert_eq!(undo_len(&s), n + 2, "already off: no undo step");
}
#[test]
fn convert_to_point_type_turns_block_off_keeping_its_sizes() {
let mut s = session();
let id = area(&mut s, 300.0, 400.0, "BIG\na much longer second line");
s.execute("type.dynamicText", &json!({"on": true})).unwrap();
let sizes = |t: &TextObject| t.runs.iter().map(|r| (r.text.clone(), r.style.size, r.style.leading)).collect::<Vec<_>>();
let fitted = sizes(&text(&s, id));
let n = undo_len(&s);
s.execute("type.convertToPointType", &json!({})).unwrap();
assert_eq!(undo_len(&s), n + 1, "one undo step");
let t = text(&s, id);
assert!(matches!(t.kind, TextKind::Point));
assert!(!t.dynamic_text, "point type has Dynamic Text off");
assert_eq!(sizes(&t), fitted, "point type keeps the sizes Block set");
assert!(serde_json::to_value(&t).unwrap().get("dynamicText").is_none(), "saved without dynamicText");
// Back to area type, the frame is not refitted: Block stays off.
s.execute("type.convertToAreaType", &json!({})).unwrap();
let t = text(&s, id);
assert!(matches!(t.kind, TextKind::Area { .. }));
assert!(!t.dynamic_text, "Block does not come on again");
assert_eq!(sizes(&t), fitted);
// Undo gives the Block frame back.
s.execute("edit.undo", &json!({})).unwrap();
s.execute("edit.undo", &json!({})).unwrap();
let t = text(&s, id);
assert!(t.dynamic_text && matches!(t.kind, TextKind::Area { .. }));
assert_eq!(sizes(&t), fitted);
}
#[test]
fn bad_params_and_other_type_are_refused() {
let mut s = session();
+4 -1
View File
@@ -47,7 +47,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Convert To Point Type",
["Type"],
None,
"{ids?|id?} area type → point type; soft line wraps become line breaks, and a frame of threaded text leaves its thread with the text it holds → {ids}",
"{ids?|id?} area type → point type; soft line wraps become line breaks, a frame of threaded text leaves its thread with the text it holds, and Dynamic Text (Block) is turned off, keeping the sizes it set → {ids}",
has_selection,
to_point
),
@@ -410,6 +410,9 @@ fn to_point(s: &mut Session, p: &Value) -> Result<Value> {
Justify::Auto if lay.lines.first().is_some_and(|l| l.rtl) => x1,
_ => x0,
};
// Point type has no Dynamic Text: Block is turned off, keeping the sizes it set, so
// converting back to area type does not turn it on again.
t.dynamic_text = false;
t.kind = TextKind::Point;
t.xf *= Affine::translate((ox, baseline));
refresh_bounds(t);
-4
View File
@@ -171,10 +171,6 @@ pub struct Session {
/// The Scripts folder, whose scripts File › Scripts lists; `None`: no folder
/// ([`Session::attach_scripts_dir`]).
scripts_dir: Option<std::path::PathBuf>,
/// The plug-in ids whose grant in the plug-in store should be gone but could not be removed:
/// [`Session::plugin_approver`] and a load of the store do not count those grants, and a successful
/// [`Session::store_grant`] for the id takes it out.
ignored_plugin_grants: std::sync::Mutex<std::collections::BTreeSet<String>>,
/// A filter's output that a run made in the background handed in for `plugin.run` to apply
/// ([`cmd::plugin::FilterRun::hand_in`]); the next `plugin.run` takes it.
plugin_output: Option<cmd::plugin::HandedIn>,
-1
View File
@@ -87,7 +87,6 @@ impl Session {
color_settings_file: None,
plugin_dir: None,
scripts_dir: None,
ignored_plugin_grants: Default::default(),
plugin_output: None,
plugin_install_approval: None,
plugin_grants_from_requests: false,
+105 -18
View File
@@ -89,6 +89,24 @@ static PLUGIN_DATA_LOCK: Mutex<()> = Mutex::new(());
/// The state of each plug-in folder's storage, shared by every storage made for the folder until
/// the plug-in is removed, which closes it and drops it.
static PLUGIN_DATA_OPEN: Mutex<BTreeMap<PathBuf, Arc<PluginData>>> = Mutex::new(BTreeMap::new());
/// The grants of plug-in stores that the sessions of the process don't count, and when each was
/// last written ([`IgnoredGrants`]). Another process reads `grants.json` as it is.
static IGNORED_PLUGIN_GRANTS: Mutex<IgnoredGrants> = Mutex::new(IgnoredGrants { ignored: BTreeSet::new(), written: BTreeMap::new(), writes: 0 });
/// How many of the latest grant writes [`IgnoredGrants`] keeps.
const MAX_GRANT_WRITES_KEPT: usize = 256;
/// Grants of plug-in stores, by the store's folder ([`plugin_store_key`]) and the plug-in id.
struct IgnoredGrants {
/// The grants that should be gone but could not be removed: no session in the process counts
/// them ([`Session::ignore_stored_grant`]) until one writes the store's grants for the id
/// ([`Session::store_grant`]).
ignored: BTreeSet<(PathBuf, String)>,
/// The latest grant writes of the process, at most [`MAX_GRANT_WRITES_KEPT`], each with the
/// count of writes it made ([`IgnoredGrants::writes`]).
written: BTreeMap<(PathBuf, String), u64>,
/// How many grant writes the sessions of the process have made ([`Session::grant_writes`]).
writes: u64,
}
/// The file name (without extension) a stored item called `name` gets: its name made safe for any
/// file system, then a hash of the name, so that names that differ only in characters a file name
@@ -100,6 +118,37 @@ pub(crate) fn file_stem(name: &str) -> String {
format!("{}-{hash:016x}", safe.trim())
}
/// The folder `dir` spelled one way for every path to it, so that sessions attached to it by
/// different paths share [`IGNORED_PLUGIN_GRANTS`]: the canonical path when the folder exists, else
/// the canonical path of its nearest folder that exists followed by the rest of the path, with `.`
/// and `..` taken out by name. The path as given when it has no absolute form (the current folder
/// can't be read).
pub(crate) fn plugin_store_key(dir: &Path) -> PathBuf {
if let Ok(path) = std::fs::canonicalize(dir) {
return path;
}
let Ok(absolute) = std::path::absolute(dir) else { return dir.to_path_buf() };
let mut parts: Vec<std::path::Component> = Vec::new();
for part in absolute.components() {
match part {
std::path::Component::CurDir => {}
std::path::Component::ParentDir => {
if matches!(parts.last(), Some(std::path::Component::Normal(_))) {
parts.pop();
}
}
_ => parts.push(part),
}
}
for kept in (1..=parts.len()).rev() {
let base: PathBuf = parts[..kept].iter().collect();
if let Ok(found) = std::fs::canonicalize(&base) {
return parts[kept..].iter().fold(found, |path, part| path.join(part));
}
}
parts.iter().collect()
}
/// The regular files of `dir` with the extension `ext` (any case), by file name, at most
/// [`MAX_STORE_FILES`]; none when the folder can't be read.
fn list_files(dir: &Path, ext: &str) -> Vec<PathBuf> {
@@ -355,9 +404,6 @@ impl Session {
let disabled =
read_capped(&dir.join(DISABLED_FILE), safe_mode::MAX_DISABLED_FILE_BYTES).map(|b| safe_mode::parse_disabled_file(&b)).unwrap_or_default();
safe_mode::set_disabled(disabled);
if self.plugin_dir.as_ref() != Some(&dir) {
self.ignored_plugin_grants.lock().unwrap_or_else(|e| e.into_inner()).clear();
}
self.plugin_dir = Some(dir);
self.load_stored_plugins();
}
@@ -368,7 +414,8 @@ impl Session {
/// there don't grant that very module ([`grant_covers`]), is skipped with a log record, and
/// stays in the folder with its grant. A grant for an id whose stored module lists no
/// permissions is forgotten; one that can't be removed from the grants file doesn't count for
/// the rest of the session ([`Session::plugin_approver`]).
/// any session in the process attached to the folder until the file can be written for the id
/// ([`Session::ignore_stored_grant`]).
pub fn load_stored_plugins(&mut self) {
let Some(dir) = self.plugin_dir.clone() else { return };
if safe_mode::active() {
@@ -432,8 +479,11 @@ impl Session {
Ok(file) => file.names(id),
Err(e) => e.unread,
};
if named && !self.store_grant(id, None) && self.holds_plugin_grant(id) {
self.ignore_stored_grant(id);
if named {
let writes = self.grant_writes();
if !self.store_grant(id, None) && self.holds_plugin_grant(id) {
self.ignore_stored_grant(id, writes);
}
}
}
}
@@ -515,12 +565,16 @@ impl Session {
}
}
/// The grants kept in the plug-in store `dir` ([`stored_grants`]) without those this session
/// doesn't count ([`Session::ignore_stored_grant`]).
/// The grants kept in the plug-in store `dir` ([`stored_grants`]) without those the process
/// doesn't count for that folder ([`Session::ignore_stored_grant`]). The folder's key is worked
/// out on each call, so a path whose link now leads elsewhere is matched with where it leads.
fn counted_grants(&self, dir: &Path) -> BTreeMap<String, vectorcraft_plugins::permissions::Grant> {
let ignored = self.ignored_plugin_grants.lock().unwrap_or_else(|e| e.into_inner());
let key = plugin_store_key(dir);
let mut grants = stored_grants(dir);
grants.retain(|id, _| !ignored.contains(id));
let shared = IGNORED_PLUGIN_GRANTS.lock().unwrap_or_else(|e| e.into_inner());
for (_, id) in shared.ignored.range((key.clone(), String::new())..).take_while(|(folder, _)| *folder == key) {
grants.remove(id);
}
grants
}
@@ -573,20 +627,53 @@ impl Session {
/// be read or doesn't hold a list is left as it is, with a log record, and nothing is recorded;
/// so is one whose new content would be larger than `MAX_GRANTS_FILE`. → whether the store now
/// holds what was asked (`false` without a folder). When it does, the grant kept for `id` counts
/// again ([`Session::ignore_stored_grant`]).
/// again, for every session in the process attached to the store ([`Session::ignore_stored_grant`]).
pub(crate) fn store_grant(&self, id: &str, grant: Option<vectorcraft_plugins::permissions::Grant>) -> bool {
let done = self.write_grant(id, grant);
if done {
self.ignored_plugin_grants.lock().unwrap_or_else(|e| e.into_inner()).remove(id);
if done && let Some(key) = self.plugin_dir.as_deref().map(plugin_store_key) {
let mut shared = IGNORED_PLUGIN_GRANTS.lock().unwrap_or_else(|e| e.into_inner());
let entry = (key, id.to_string());
shared.ignored.remove(&entry);
shared.writes = shared.writes.saturating_add(1);
let writes = shared.writes;
shared.written.insert(entry, writes);
if shared.written.len() > MAX_GRANT_WRITES_KEPT
&& let Some(oldest) = shared.written.iter().min_by_key(|(_, at)| **at).map(|(entry, _)| entry.clone())
{
shared.written.remove(&oldest);
}
}
done
}
/// Stop counting the store's grant for the plug-in `id` until [`Session::store_grant`] next
/// succeeds for it or another store is attached: for a grant that should be gone and could not
/// be removed, which would otherwise approve the bytes it covers.
pub(crate) fn ignore_stored_grant(&self, id: &str) {
self.ignored_plugin_grants.lock().unwrap_or_else(|e| e.into_inner()).insert(id.to_string());
/// How many grant writes the sessions of the process have made ([`Session::store_grant`]).
/// Taken before a write that may fail, for [`Session::ignore_stored_grant`].
pub(crate) fn grant_writes(&self) -> u64 {
IGNORED_PLUGIN_GRANTS.lock().unwrap_or_else(|e| e.into_inner()).writes
}
/// How many grant writes the process keeps ([`IgnoredGrants::written`]).
#[cfg(test)]
pub(crate) fn grant_writes_kept() -> usize {
IGNORED_PLUGIN_GRANTS.lock().unwrap_or_else(|e| e.into_inner()).written.len()
}
/// Stop counting the attached store's grant for the plug-in `id`, in every session in the
/// process attached to the same folder, until [`Session::store_grant`] next succeeds for it in
/// one of them: for a grant that should be gone and could not be removed, which would otherwise
/// approve the bytes it covers. `writes` is [`Session::grant_writes`] from before the failed
/// write: when a session has written the store's grants for `id` since, the file holds what that
/// write asked for, and the grant keeps counting. A write no longer among the latest
/// [`MAX_GRANT_WRITES_KEPT`] is not seen, and the grant stops counting. Another process on the
/// folder reads `grants.json` as it is.
pub(crate) fn ignore_stored_grant(&self, id: &str, writes: u64) {
if let Some(key) = self.plugin_dir.as_deref().map(plugin_store_key) {
let mut shared = IGNORED_PLUGIN_GRANTS.lock().unwrap_or_else(|e| e.into_inner());
let entry = (key, id.to_string());
if shared.written.get(&entry).is_none_or(|at| *at <= writes) {
shared.ignored.insert(entry);
}
}
}
fn write_grant(&self, id: &str, grant: Option<vectorcraft_plugins::permissions::Grant>) -> bool {
+1
View File
@@ -133,6 +133,7 @@ mod placed_document;
mod plugins;
mod prefs;
mod prefs_file;
mod prefs_roots;
mod previewbounds;
mod print;
mod printadvanced;
+176
View File
@@ -418,3 +418,179 @@ fn native_blend_easing_values_clamp_and_non_finite_become_default() {
assert_eq!((spec.ease.ramp, spec.color_shift), (ramp, shift), "{bad}");
}
}
fn create_spine(s: &mut Session, p: Value) -> Value {
s.execute("object.blend.createSpine", &p).unwrap()["mode"].clone()
}
/// Two squares 100 pt apart blended with `p`; the blend.
fn make(s: &mut Session, y: f64, p: Value) -> NodeId {
let (a, b) = (rect(s, 0.0, y, 10.0), rect(s, 100.0, y, 10.0));
let mut p = p;
p["ids"] = json!([a.0, b.0]);
p["steps"] = json!(3);
id_of(&s.execute("object.blend.make", &p).unwrap())
}
#[test]
fn create_spine_sets_whether_new_blends_get_a_spine() {
let mut s = session();
assert_eq!(create_spine(&mut s, json!({})), "auto", "Auto until one is chosen");
let spined = make(&mut s, 0.0, json!({}));
assert!(!spec(&s, spined).1.no_spine);
let depth = s.doc().unwrap().history.undo.len();
assert_eq!(create_spine(&mut s, json!({"mode": "never"})), "never");
assert_eq!(s.doc().unwrap().history.undo.len(), depth, "a tool setting, not an undo step");
assert_eq!(create_spine(&mut s, json!({})), "never");
// The Blend Options set with nothing selected keep it, and it keeps them.
s.execute("select.none", &json!({})).unwrap();
s.execute("object.blend.options", &json!({"steps": 7})).unwrap();
assert_eq!(create_spine(&mut s, json!({})), "never");
assert_eq!(s.prefs.blend_options.unwrap().spacing, BlendSpacing::Steps(7));
// A new blend has no spine; the blend made before keeps its own.
let bare = make(&mut s, 50.0, json!({}));
assert!(spec(&s, bare).1.no_spine);
assert!(!spec(&s, spined).1.no_spine, "blends already made keep their spine");
sel(&mut s, &[bare]);
let info = s.execute("object.blend.info", &json!({})).unwrap();
assert_eq!(info["hasSpine"], json!(false));
assert!(info.get("spine").is_none(), "{info}");
sel(&mut s, &[spined]);
assert_eq!(s.execute("object.blend.info", &json!({})).unwrap()["hasSpine"], json!(true));
// `createSpine` on Make chooses for that blend only.
let forced = make(&mut s, 100.0, json!({"createSpine": "always"}));
assert!(!spec(&s, forced).1.no_spine);
assert_eq!(create_spine(&mut s, json!({})), "never");
assert_eq!(create_spine(&mut s, json!({"mode": "always"})), "always");
let always = make(&mut s, 150.0, json!({}));
assert!(!spec(&s, always).1.no_spine);
assert!(spec(&s, bare).1.no_spine, "blends already made keep having no spine");
let none = make(&mut s, 200.0, json!({"createSpine": "never"}));
assert!(spec(&s, none).1.no_spine);
// The setting survives a round trip through the preferences file; Auto is not written.
let back: Prefs = serde_json::from_value(s.prefs.to_json()).unwrap();
assert_eq!(back.blend_options.unwrap().create_spine, vectorcraft_doc::live::BlendSpineMode::Always);
assert_eq!(s.prefs.to_json()["blendOptions"]["createSpine"], json!("always"));
create_spine(&mut s, json!({"mode": "auto"}));
assert!(s.prefs.to_json()["blendOptions"].get("createSpine").is_none());
let mut odd = s.prefs.to_json();
odd["blendOptions"]["createSpine"] = json!("sometimes");
let unknown: Prefs = serde_json::from_value(odd).unwrap();
assert_eq!(unknown.blend_options.unwrap().create_spine, vectorcraft_doc::live::BlendSpineMode::Auto, "an unknown value reads as Auto");
}
#[test]
fn create_spine_refuses_bad_values_and_changes_nothing() {
let mut s = session();
create_spine(&mut s, json!({"mode": "never"}));
let prefs = s.prefs.blend_options;
for bad in [json!({"mode": "sometimes"}), json!({"mode": 1}), json!({"mode": true}), json!({"mode": ["never"]}), json!({"mode": "Never"})] {
let e = s.execute("object.blend.createSpine", &bad).unwrap_err().to_string();
assert!(e.contains("`mode` must be one of auto, always, never"), "{bad}: {e}");
assert_eq!(s.prefs.blend_options, prefs, "{bad}");
}
let (a, b) = (rect(&mut s, 0.0, 0.0, 10.0), rect(&mut s, 100.0, 0.0, 10.0));
let depth = s.doc().unwrap().history.undo.len();
for bad in [json!({"createSpine": "x"}), json!({"createSpine": 0}), json!({"createSpine": "never", "easingType": "easeIn"}), json!({"ramp": 30})]
{
let mut p = bad.clone();
p["ids"] = json!([a.0, b.0]);
assert!(s.execute("object.blend.make", &p).is_err(), "{bad}");
assert_eq!(s.doc().unwrap().history.undo.len(), depth, "{bad}: nothing made");
}
assert!(s.execute("object.blend.createSpine", &json!({"spine": "never"})).is_err(), "an unknown key");
}
#[test]
fn a_blend_without_a_spine_has_none_to_edit_reverse_ease_or_release() {
let mut s = session();
let g = make(&mut s, 0.0, json!({"createSpine": "never"}));
sel(&mut s, &[g]);
let before = node(&s, g);
let depth = s.doc().unwrap().history.undo.len();
// Reverse Spine, easing and the spine point commands refuse it and change nothing.
let refused = [
("object.blend.reverseSpine", json!({})),
("object.blend.options", json!({"easingType": "easeOut"})),
("object.blend.options", json!({"ramp": 40})),
("object.blend.spine.addAnchor", json!({"x": 50, "y": 5})),
("object.blend.spine.moveAnchor", json!({"anchor": 0, "x": 0, "y": 50})),
];
for (cmd, p) in refused {
let e = s.execute(cmd, &p).unwrap_err().to_string();
assert!(e.contains("the blend has no spine"), "{cmd}: {e}");
assert_eq!((node(&s, g), s.doc().unwrap().history.undo.len()), (before.clone(), depth), "{cmd}");
}
// Spacing, Orientation and Shift still apply; Align to Path makes no spine.
s.execute("object.blend.options", &json!({"steps": 2, "orientation": "path", "colorShift": 20})).unwrap();
let sp = spec(&s, g).1;
assert_eq!((sp.spacing, sp.orientation, sp.color_shift, sp.no_spine), (BlendSpacing::Steps(2), BlendOrientation::AlignToPath, 20.0, true));
assert!(s.execute("object.blend.info", &json!({})).unwrap().get("spine").is_none());
// Taking in another key keeps it without a spine, whatever Create Spine says.
let c = rect(&mut s, 200.0, 0.0, 10.0);
sel(&mut s, &[g, c]);
create_spine(&mut s, json!({"mode": "always"}));
let g = id_of(&s.execute("object.blend.make", &json!({})).unwrap());
assert_eq!(spec(&s, g).0.len(), 3);
assert!(spec(&s, g).1.no_spine && spec(&s, g).1.spine.is_none());
// Release gives back the keys and no spine path.
sel(&mut s, &[g]);
let r = s.execute("object.blend.release", &json!({})).unwrap();
assert_eq!((r["ids"].as_array().map(Vec::len), &r["spines"]), (Some(3), &json!([])));
s.execute("edit.undo", &json!({})).unwrap();
// Replace Spine gives it one: then it reverses and eases like any other.
let line = id_of(&s.execute("path.create", &json!({"d": "M0 100 L200 150"})).unwrap());
sel(&mut s, &[g, line]);
s.execute("object.blend.replaceSpine", &json!({})).unwrap();
let sp = spec(&s, g).1;
assert!(!sp.no_spine && sp.spine.is_some());
let info = s.execute("object.blend.info", &json!({})).unwrap();
assert_eq!((&info["hasSpine"], &info["spine"]["explicit"]), (&json!(true), &json!(true)));
s.execute("object.blend.reverseSpine", &json!({})).unwrap();
s.execute("object.blend.options", &json!({"easingType": "easeOut", "ramp": 40})).unwrap();
assert_eq!(spec(&s, g).1.ease.ramp, 0.4);
}
#[test]
fn a_blend_without_a_spine_draws_its_steps_where_one_with_a_spine_does() {
let mut s = session();
for orientation in ["page", "path"] {
let spined = make(&mut s, 0.0, json!({"orientation": orientation}));
let bare = make(&mut s, 0.0, json!({"orientation": orientation, "createSpine": "never"}));
let boxes = |g: NodeId| -> Vec<_> { vectorcraft_doc::live::expand_live(&node(&s, g)).iter().map(|n| n.geometric_bounds()).collect() };
assert_eq!(boxes(bare), boxes(spined), "{orientation}");
assert!(boxes(bare).len() >= 3, "the three steps at least");
}
// Easing stored on a blend without a spine (a hand-edited file) leaves its steps evenly spaced.
let bare = make(&mut s, 300.0, json!({"orientation": "path", "createSpine": "never"}));
let even = vectorcraft_doc::live::expand_live(&node(&s, bare));
let mut eased = node(&s, bare);
if let NodeKind::Blend { spec, .. } = &mut eased.kind {
spec.ease = vectorcraft_doc::live::BlendEase { kind: vectorcraft_doc::live::BlendEaseType::In, ramp: 1.0 };
}
let boxes = |v: &[Node]| -> Vec<_> { v.iter().map(|n| n.geometric_bounds()).collect() };
assert_eq!(boxes(&vectorcraft_doc::live::expand_live(&eased)), boxes(&even));
}
#[test]
fn whether_a_blend_has_a_spine_is_saved_and_old_blends_have_one() {
let mut s = session();
let bare = make(&mut s, 0.0, json!({"createSpine": "never"}));
let spined = make(&mut s, 50.0, json!({}));
let d = &s.doc().unwrap().doc;
let back = vectorcraft_format::load(&vectorcraft_format::save(d, false)).unwrap();
assert_eq!(&back.layers, &d.layers);
let saved = |g: NodeId| match &back.node(g).unwrap().kind {
NodeKind::Blend { spec, .. } => spec.no_spine,
_ => panic!("not a blend"),
};
assert!(saved(bare) && !saved(spined));
assert_eq!(serde_json::to_value(spec(&s, bare).1).unwrap()["noSpine"], json!(true));
assert!(serde_json::to_value(spec(&s, spined).1).unwrap().get("noSpine").is_none(), "a spine is not written");
let old: BlendSpec = serde_json::from_value(json!({"spacing": {"steps": 4}})).unwrap();
assert!(!old.no_spine, "a blend saved before Create Spine has a spine");
for odd in [json!("yes"), json!(1), json!(null)] {
let v: BlendSpec = serde_json::from_value(json!({"noSpine": odd.clone()})).unwrap_or_else(|e| panic!("{odd}: {e}"));
assert!(!v.no_spine, "{odd}");
}
}
+183 -5
View File
@@ -1820,11 +1820,11 @@ fn a_grant_that_cannot_be_removed_and_has_no_stored_module_stops_counting() {
run(&mut s, "plugin.remove", json!({"id": id}));
}
/// A grant that a load of the plug-in store should forget and can't stays out of the approvals for
/// the session: both when `grants.json` can't be rewritten and when it can't be read at the load.
/// A grant recorded later counts again, and another store starts with nothing ignored.
/// A grant that a load of the plug-in store should forget and can't stays out of the approvals in
/// the process: both when `grants.json` can't be rewritten and when it can't be read at the load.
/// A grant recorded later counts again, and another store's grant for the id counts.
#[test]
fn a_grant_the_load_cannot_remove_stops_counting_for_the_session() {
fn a_grant_the_load_cannot_remove_stops_counting_in_the_process() {
use vectorcraft_plugins::permissions::sha256_hex;
let folder = crate::tests_links::Folder::new("plugin-store-load-forget");
let elsewhere = crate::tests_links::Folder::new("plugin-store-load-forget-other");
@@ -1856,8 +1856,12 @@ fn a_grant_the_load_cannot_remove_stops_counting_for_the_session() {
next.attach_plugin_store(elsewhere.0.clone());
assert_eq!(run(&mut next, "plugin.inspect", needs_approval.clone())["needsApproval"], false, "that store's grant counts");
// A load that can rewrite the file forgets the grant, and the store has nothing ignored again.
std::fs::write(&grants, &recorded).unwrap();
next.attach_plugin_store(folder.0.clone());
assert!(!grants.exists(), "the load removes the grant");
// A directory at the file's path gives a read error on every platform.
std::fs::remove_file(&grants).unwrap();
std::fs::create_dir(&grants).unwrap();
vectorcraft_plugins::registry::remove(id);
let mut third = session();
@@ -1883,6 +1887,180 @@ fn a_grant_the_load_cannot_remove_stops_counting_for_the_session() {
run(&mut third, "plugin.remove", json!({"id": id}));
}
/// A grant one session stops counting stops counting for every session in the process attached to
/// the same folder, by any path to it: one attached before, one attached after with no stored module
/// to try the removal for, and one that comes back from another folder. A successful write of the
/// grant in any of them makes it count in all of them again.
#[test]
fn an_ignored_stored_grant_is_shared_by_sessions_on_the_same_folder() {
use vectorcraft_plugins::permissions::sha256_hex;
let folder = crate::tests_links::Folder::new("plugin-store-shared-ignore");
let elsewhere = crate::tests_links::Folder::new("plugin-store-shared-ignore-other");
let id = "test.engine.permissions.sharedignore";
let empty = json!({"objects": []});
let approved = asking(id, r#"["doc.read"]"#, &empty);
let approved_data = vectorcraft_format::base64_encode(&approved);
let plain = asking(id, "null", &empty);
let needs_approval = json!({"dataBase64": approved_data});
let grants = folder.0.join("grants.json");
let entry = json!({"id": id, "hash": sha256_hex(&approved), "permissions": ["doc.read"]});
let recorded = serde_json::to_vec(&json!([entry])).unwrap();
std::fs::write(&grants, &recorded).unwrap();
let mut first = session();
first.attach_plugin_store(folder.0.clone());
let inside = folder.0.join("inside");
std::fs::create_dir(&inside).unwrap();
let mut other = session();
other.attach_plugin_store(inside.join(".."));
assert_eq!(run(&mut other, "plugin.inspect", needs_approval.clone())["needsApproval"], false, "the recorded grant counts");
// `1e9` is written back as `1000000000.0`, which makes the rewritten file larger than the 1 MiB that is read.
let full = format!(r#"[{entry},{{"n":[{}]}}]"#, vec!["1e9"; 200_000].join(",")).into_bytes();
std::fs::write(&grants, &full).unwrap();
run(&mut first, "plugin.install", json!({"dataBase64": vectorcraft_format::base64_encode(&plain)}));
let file = first.stored_plugin_file(id).unwrap();
assert!(!std::path::Path::new(&file).exists(), "the store keeps no module");
assert_eq!(std::fs::read(&grants).unwrap(), full);
assert_eq!(run(&mut other, "plugin.inspect", needs_approval.clone())["needsApproval"], true, "the other session doesn't count it");
let refused = other.execute("plugin.install", &json!({"dataBase64": approved_data, "replace": true})).unwrap_err().to_string();
assert!(refused.contains("doc.read"), "{refused}");
std::fs::write(&file, &approved).unwrap();
vectorcraft_plugins::registry::remove(id);
other.load_stored_plugins();
assert!(vectorcraft_plugins::registry::get(id).is_none(), "the formerly approved module isn't loaded");
std::fs::remove_file(&file).unwrap();
let mut later = session();
later.attach_plugin_store(folder.0.clone());
assert_eq!(run(&mut later, "plugin.inspect", needs_approval.clone())["needsApproval"], true, "a session attached later doesn't count it");
std::fs::write(elsewhere.0.join("grants.json"), &recorded).unwrap();
other.attach_plugin_store(elsewhere.0.clone());
assert_eq!(run(&mut other, "plugin.inspect", needs_approval.clone())["needsApproval"], false, "that store's grant counts");
other.attach_plugin_store(folder.0.clone());
assert_eq!(run(&mut other, "plugin.inspect", needs_approval.clone())["needsApproval"], true, "back on the folder, it doesn't");
std::fs::write(&grants, &recorded).unwrap();
assert!(later.store_grant(id, Some(serde_json::from_value(entry).unwrap())), "the file can be written");
for s in [&mut first, &mut other, &mut later] {
assert_eq!(run(s, "plugin.inspect", needs_approval.clone())["needsApproval"], false, "it counts again");
}
std::fs::remove_file(&grants).unwrap();
}
/// A plug-in folder that doesn't exist yet gets the key it gets once it is made, and every path to a
/// folder gets the same key.
#[test]
fn a_plugin_folder_has_one_key_for_every_path_to_it() {
use crate::store::plugin_store_key;
let folder = crate::tests_links::Folder::new("plugin-store-key");
let dir = folder.0.join("Plug-ins");
let before = plugin_store_key(&dir);
assert_eq!(plugin_store_key(&dir.join("sub").join("..")), before);
assert_eq!(plugin_store_key(&folder.0.join(".").join("Plug-ins")), before);
std::fs::create_dir(&dir).unwrap();
assert_eq!(plugin_store_key(&dir), before, "the key stays when the folder is made");
assert_eq!(plugin_store_key(&dir.join(".")), before);
#[cfg(windows)]
{
let plain = std::path::absolute(&dir).unwrap();
let verbatim = std::path::PathBuf::from(format!(r"\\?\{}", plain.display()));
assert_eq!(plugin_store_key(&verbatim), before, "a verbatim path names the same folder");
}
}
/// Sessions attached to a plug-in folder before it exists, by paths that only name the same folder
/// once it is made, share the grants the process doesn't count for it. A grant that one session
/// writes while another fails to remove it keeps counting.
#[test]
fn sessions_attached_before_the_folder_exists_share_its_ignored_grants() {
use vectorcraft_plugins::permissions::sha256_hex;
let folder = crate::tests_links::Folder::new("plugin-store-late-folder");
let id = "test.engine.permissions.latefolder";
let approved = asking(id, r#"["doc.read"]"#, &json!({"objects": []}));
let needs_approval = json!({"dataBase64": vectorcraft_format::base64_encode(&approved)});
let entry = json!({"id": id, "hash": sha256_hex(&approved), "permissions": ["doc.read"]});
std::fs::create_dir_all(folder.0.join("a").join("b")).unwrap();
let dir = folder.0.join("a").join("Plug-ins");
// On disk `link/..` is `a`, so `link/../Plug-ins` is the folder; by name it is a `Plug-ins` beside `a`.
// On Windows the folder is named in other letter case.
#[cfg(unix)]
let alias = {
std::os::unix::fs::symlink(folder.0.join("a").join("b"), folder.0.join("link")).unwrap();
folder.0.join("link").join("..").join("Plug-ins")
};
#[cfg(windows)]
let alias = folder.0.join("A").join("PLUG-INS");
#[cfg(not(any(unix, windows)))]
let alias = dir.clone();
let mut first = session();
first.attach_plugin_store(dir.clone());
let mut other = session();
other.attach_plugin_store(alias);
std::fs::create_dir(&dir).unwrap();
std::fs::write(dir.join("grants.json"), serde_json::to_vec(&json!([entry])).unwrap()).unwrap();
assert_eq!(run(&mut other, "plugin.inspect", needs_approval.clone())["needsApproval"], false, "the recorded grant counts");
first.ignore_stored_grant(id, first.grant_writes());
assert_eq!(run(&mut other, "plugin.inspect", needs_approval.clone())["needsApproval"], true, "the other session doesn't count it");
assert!(other.store_grant(id, Some(serde_json::from_value(entry.clone()).unwrap())), "the file can be written");
assert_eq!(run(&mut first, "plugin.inspect", needs_approval.clone())["needsApproval"], false, "it counts again");
// A write that fails in one session while another writes the grant for the id leaves the grant
// counting.
let before = first.grant_writes();
assert!(other.store_grant(id, Some(serde_json::from_value(entry).unwrap())), "the other session writes the grant");
first.ignore_stored_grant(id, before);
assert_eq!(run(&mut first, "plugin.inspect", needs_approval)["needsApproval"], false, "the written grant counts");
std::fs::remove_file(dir.join("grants.json")).unwrap();
}
/// Grant writes that change nothing, each for another id, don't grow what the process keeps past its
/// limit.
#[test]
fn the_process_keeps_a_bounded_number_of_grant_writes() {
let folder = crate::tests_links::Folder::new("plugin-store-writes-kept");
let mut s = session();
s.attach_plugin_store(folder.0.clone());
for n in 0..300 {
assert!(s.store_grant(&format!("test.engine.permissions.unknown{n}"), None), "nothing to remove is a success");
}
assert!(Session::grant_writes_kept() <= 256, "{}", Session::grant_writes_kept());
}
/// A session attached by a link to a plug-in folder matches the grants the process doesn't count
/// with the folder the link leads to now, not the one it led to when the session was attached.
#[cfg(unix)]
#[test]
fn a_linked_plugin_folder_uses_the_ignored_grants_of_where_the_link_leads() {
use vectorcraft_plugins::permissions::sha256_hex;
let folder = crate::tests_links::Folder::new("plugin-store-relinked");
let id = "test.engine.permissions.relinked";
let approved = asking(id, r#"["doc.read"]"#, &json!({"objects": []}));
let needs_approval = json!({"dataBase64": vectorcraft_format::base64_encode(&approved)});
let entry = json!({"id": id, "hash": sha256_hex(&approved), "permissions": ["doc.read"]});
let recorded = serde_json::to_vec(&json!([entry])).unwrap();
let (old, new, link) = (folder.0.join("old"), folder.0.join("new"), folder.0.join("Plug-ins"));
for dir in [&old, &new] {
std::fs::create_dir(dir).unwrap();
std::fs::write(dir.join("grants.json"), &recorded).unwrap();
}
std::os::unix::fs::symlink(&old, &link).unwrap();
let mut linked = session();
linked.attach_plugin_store(link.clone());
assert_eq!(run(&mut linked, "plugin.inspect", needs_approval.clone())["needsApproval"], false, "the recorded grant counts");
std::fs::remove_file(&link).unwrap();
std::os::unix::fs::symlink(&new, &link).unwrap();
let mut direct = session();
direct.attach_plugin_store(new.clone());
direct.ignore_stored_grant(id, direct.grant_writes());
assert_eq!(run(&mut linked, "plugin.inspect", needs_approval.clone())["needsApproval"], true, "the link leads to the ignored grant");
assert!(linked.store_grant(id, Some(serde_json::from_value(entry).unwrap())), "the file can be written");
assert_eq!(run(&mut direct, "plugin.inspect", needs_approval)["needsApproval"], false, "it counts again");
}
/// A grants file that can't be opened or read may name the old module once it reads again, so
/// neither a module listing no permissions nor `plugin.remove` gets past it. A directory at the
/// file's path gives a read error on every platform.
+107
View File
@@ -0,0 +1,107 @@
//! The preferences commands under automation roots: a confined request sees a folder preference and
//! an export preset's folder only inside its read roots.
use std::path::{Path, PathBuf};
use serde_json::{Value, json};
use crate::cmd::fileio::ScreenExportPreset;
use crate::file_access::{AutomationRoots, confine};
use crate::*;
fn run(s: &mut Session, id: &str, p: Value) -> Value {
s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"))
}
fn text(p: &Path) -> String {
p.to_string_lossy().to_string()
}
/// A fresh scratch folder for one test, with the folders `in` and `out`.
fn folder(name: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("vc-prefs-roots-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
for sub in ["in", "out"] {
std::fs::create_dir_all(dir.join(sub)).unwrap();
}
dir
}
/// The folder preferences that name the folder outside the read root.
const OUTSIDE: [&str; 3] = ["pluginsFolder", "scratchPrimary", "templatesFolder"];
/// A session whose folder preferences name `inside` (fonts, and the Data Recovery folder with
/// spaces around it) and `outside` (the [`OUTSIDE`] ones, the Templates folder with spaces around
/// it), with a scratch disk choice and an export preset kept with each folder.
fn session(inside: &str, outside: &str) -> Session {
let mut s = Session::new();
s.prefs.fonts_folder = inside.to_string();
s.prefs.recovery_folder = format!(" {inside} ");
s.prefs.plugins_folder = outside.to_string();
s.prefs.scratch_primary = outside.to_string();
s.prefs.scratch_secondary = "None".to_string();
s.prefs.templates_folder = format!(" {outside} ");
for (name, folder) in [("Inside", inside), ("Outside", outside)] {
let settings = json!({"formats": [{"format": "svg"}], "folder": folder});
s.prefs.screen_export_presets.push(ScreenExportPreset { name: name.into(), settings: settings.as_object().cloned().unwrap_or_default() });
}
s
}
/// Does a string anywhere in `v` hold `path`?
fn holds(v: &Value, path: &str) -> bool {
v.to_string().contains(&path.replace('\\', "\\\\"))
}
#[test]
fn prefs_commands_leave_out_folders_outside_the_read_root() {
let base = folder("get");
let (inside, outside) = (text(&base.join("in").join("fonts")), text(&base.join("out")));
let roots = AutomationRoots::new(&[&base.join("in")], &[]).unwrap();
let mut s = session(&inside, &outside);
let all = confine(roots.as_ref(), || run(&mut s, "prefs.get", json!({})));
let prefs = &all["prefs"];
assert_eq!(prefs["fontsFolder"], json!(inside), "a folder inside the root is shown");
assert_eq!(prefs["recoveryFolder"], json!(format!(" {inside} ")), "checked without the spaces, shown as kept");
assert_eq!(prefs["scratchSecondary"], json!("None"), "a scratch disk choice is shown");
for key in OUTSIDE {
assert_eq!(prefs[key], Value::Null, "{key}: {all}");
}
let presets = prefs["screenExportPresets"].as_array().unwrap();
assert_eq!(presets[0]["settings"]["folder"], json!(inside));
assert_eq!(presets[1]["name"], json!("Outside"), "the preset stays");
assert!(presets[1]["settings"].get("folder").is_none(), "{all}");
assert!(!holds(&all, &outside), "{all}");
for key in OUTSIDE {
let one = confine(roots.as_ref(), || run(&mut s, "prefs.get", json!({"key": key})));
assert_eq!(one, Value::Null, "{key}");
}
assert_eq!(confine(roots.as_ref(), || run(&mut s, "prefs.get", json!({"key": "fontsFolder"}))), json!(inside));
let list = confine(roots.as_ref(), || run(&mut s, "prefs.list", json!({})));
assert!(!holds(&list, &outside), "{list}");
let row = |key: &str| list.as_array().unwrap().iter().find(|r| r["key"] == key).cloned().unwrap();
assert_eq!(row("fontsFolder")["value"], json!(inside));
assert_eq!(row("pluginsFolder")["value"], Value::Null);
assert_eq!(row("pluginsFolder")["kind"], json!("text"), "the row stays");
// A request that sets another preference, or resets a category without folders.
let set = confine(roots.as_ref(), || run(&mut s, "prefs.set", json!({"values": {"keyboardIncrement": 2, "pluginsFolder": outside}})));
assert_eq!(set, json!({"keyboardIncrement": 2.0, "pluginsFolder": null}), "a folder kept as it was is left out too");
let reset = confine(roots.as_ref(), || run(&mut s, "prefs.reset", json!({"category": "General"})));
assert!(!holds(&reset, &outside), "{reset}");
assert_eq!(reset["prefs"]["fontsFolder"], json!(inside));
// Unconfined and with only a write root.
let all = run(&mut s, "prefs.get", json!({}));
assert_eq!(all["prefs"]["pluginsFolder"], json!(outside), "unconfined, the folder is shown");
assert_eq!(all["prefs"]["screenExportPresets"][1]["settings"]["folder"], json!(outside));
let write_only = AutomationRoots::new(&[], &[&base.join("in")]).unwrap();
let all = confine(write_only.as_ref(), || run(&mut s, "prefs.get", json!({})));
assert_eq!(all["prefs"]["fontsFolder"], Value::Null, "without a read root no folder is shown");
assert_eq!(all["prefs"]["recoveryFolder"], Value::Null);
assert_eq!(s.prefs.plugins_folder, outside, "the preferences are unchanged");
let _ = std::fs::remove_dir_all(&base);
}
@@ -114,3 +114,12 @@ fn keys_named(doc: &str) -> Vec<String> {
}
found.into_iter().map(|(k, _)| k).collect()
}
/// Turn notes the key walk above doesn't reach: a numeric reflection axis and the Scatter brush's
/// `rotation [a, b]` range, whose head isn't a plain key.
#[test]
fn turns_outside_plain_keys_say_which_way() {
let doc = |id: &str| command_specs().iter().find(|c| c.id == id).map(|c| c.params).unwrap_or_default();
assert!(doc("object.reflect").contains("|deg (the mirror line, counter-clockwise from horizontal"), "object.reflect's numeric axis");
assert!(doc("brush.options").contains("rotation [a, b] −180..180° (counter-clockwise)"), "the Scatter brush's rotation");
}