mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-05 05:22:58 -05:00
1468 lines
71 KiB
Rust
1468 lines
71 KiB
Rust
//! Tracing in the script object model: `trace()` on placed and raster items, the `PluginItem`, its
|
||
//! `TracingObject` and its `TracingOptions`, and the checks on what a script gives them.
|
||
|
||
use std::path::{Path, PathBuf};
|
||
|
||
use serde_json::{Value, json};
|
||
|
||
use crate::*;
|
||
|
||
/// A fresh folder for test `name`, with a `main` folder for the script, by its real path.
|
||
fn folder(name: &str) -> PathBuf {
|
||
let base = std::env::temp_dir().join(format!("vc-dom-tracing-{name}-{}", std::process::id()));
|
||
let _ = std::fs::remove_dir_all(&base);
|
||
std::fs::create_dir_all(base.join("main")).unwrap();
|
||
std::fs::canonicalize(&base).unwrap()
|
||
}
|
||
|
||
/// A 60 × 60 PNG of a black disc on white.
|
||
fn disc_png() -> Vec<u8> {
|
||
vectorcraft_trace::Raster::from_fn(60, 60, |x, y| {
|
||
let (dx, dy) = (f64::from(x) + 0.5 - 30.0, f64::from(y) + 0.5 - 30.0);
|
||
if dx * dx + dy * dy <= 400.0 { [0, 0, 0, 255] } else { [255, 255, 255, 255] }
|
||
})
|
||
.encode_png()
|
||
}
|
||
|
||
/// A session with one 400 × 300 pt document holding the disc image, linked (`link`) or embedded.
|
||
fn session(base: &Path, link: bool) -> (Session, NodeId) {
|
||
let png = base.join("main/disc.png");
|
||
std::fs::write(&png, disc_png()).unwrap();
|
||
let mut s = Session::new();
|
||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||
let r = s.execute("file.place", &json!({"path": png.to_string_lossy(), "link": link})).unwrap();
|
||
let id = NodeId(r["ids"][0].as_u64().unwrap());
|
||
(s, id)
|
||
}
|
||
|
||
/// Runs `text` as `main/main.jsx` in `base`.
|
||
fn run(s: &mut Session, base: &Path, text: &str) -> Result<Value> {
|
||
let main = base.join("main/main.jsx");
|
||
std::fs::write(&main, text).unwrap();
|
||
s.execute("script.run", &json!({"path": main.to_string_lossy()}))
|
||
}
|
||
|
||
fn log(s: &mut Session, base: &Path, text: &str) -> Vec<Value> {
|
||
let r = run(s, base, text).unwrap_or_else(|e| panic!("{text}: {e}"));
|
||
r["log"].as_array().cloned().unwrap_or_default()
|
||
}
|
||
|
||
fn undo_steps(s: &Session) -> usize {
|
||
s.active().unwrap().history.undo.len()
|
||
}
|
||
|
||
/// The Image Trace objects of the active document.
|
||
fn traces(s: &Session) -> Vec<NodeId> {
|
||
let mut out = vec![];
|
||
s.active().unwrap().doc.walk(|n| {
|
||
if crate::cmd::is_trace_group(n) {
|
||
out.push(n.id);
|
||
}
|
||
});
|
||
out
|
||
}
|
||
|
||
/// The `trace` settings of the Image Trace object `id`.
|
||
fn trace_of(s: &Session, id: NodeId) -> Value {
|
||
s.active().unwrap().doc.node(id).and_then(|n| n.extras().trace.as_deref().cloned()).unwrap_or(Value::Null)
|
||
}
|
||
|
||
/// Every top-level object of the active document's first layer.
|
||
fn top(s: &Session) -> Vec<NodeId> {
|
||
let d = &s.active().unwrap().doc;
|
||
d.children(Some(d.layers[0].id)).map(|c| c.iter().map(|n| n.id).collect()).unwrap_or_default()
|
||
}
|
||
|
||
/// Traces with the Default preset as a script does, which the script's counts should match: its
|
||
/// `paths` and `anchors`, and the different paints of the result.
|
||
fn command_counts(base: &Path, link: bool) -> (u64, u64, u64) {
|
||
let (mut s, id) = session(base, link);
|
||
let r = s.execute("imageTrace.make", &json!({"id": id.0})).unwrap();
|
||
(r["paths"].as_u64().unwrap(), r["anchors"].as_u64().unwrap(), r["colors"].as_u64().unwrap())
|
||
}
|
||
|
||
#[test]
|
||
fn raster_trace_returns_plugin_with_counts() {
|
||
let base = folder("raster");
|
||
let (mut s, image) = session(&base, false);
|
||
let ppi = s.execute("image.info", &json!({"id": image.0})).unwrap()["ppi"][0].clone();
|
||
let out = log(
|
||
&mut s,
|
||
&base,
|
||
"var d = app.activeDocument, r = d.rasterItems[0]; r.name = 'src'; var p = r.trace(), t = p.tracing;\
|
||
vc.log(p.typename); vc.log(p.isTracing); vc.log(t.typename); vc.log(t.sourceArt.name); vc.log(r.typename);\
|
||
vc.log(t.pathCount); vc.log(t.anchorCount); vc.log(t.usedColorCount); vc.log(t.imageResolution);\
|
||
vc.log(p.tracing.pathCount === t.pathCount); vc.log(t.parent.isTracing); vc.log(t.tracingOptions.typename);\
|
||
vc.log(t.tracingOptions.parent.typename); vc.log(d.pageItems[0].typename); vc.log(t.tracingOptions.preset);",
|
||
);
|
||
assert_eq!(out[..5], [json!("PluginItem"), json!(true), json!("TracingObject"), json!("src"), json!("RasterItem")]);
|
||
let (paths, anchors, colors) = command_counts(&base, false);
|
||
assert!(paths > 0 && anchors > 0, "{paths} {anchors}");
|
||
assert_eq!(out[5], json!(paths));
|
||
assert_eq!(out[6], json!(anchors));
|
||
let used = out[7].as_u64().unwrap();
|
||
assert!(used >= 1 && used <= colors, "{used} of {colors}");
|
||
assert_eq!(out[8].as_f64(), ppi.as_f64());
|
||
assert_eq!(out[9..], [json!(true), json!(true), json!("TracingOptions"), json!("TracingObject"), json!("PluginItem"), json!("Default")]);
|
||
let groups = traces(&s);
|
||
assert_eq!(groups.len(), 1);
|
||
assert_eq!(top(&s), groups);
|
||
assert_eq!(undo_steps(&s), 2, "the place and the run");
|
||
let _ = std::fs::remove_dir_all(base);
|
||
}
|
||
|
||
/// A group moved into a tracing above its paths counts even when its name and contents look like
|
||
/// seam fills: only the tracing's lowest item can be its seam fills.
|
||
#[test]
|
||
fn added_group_named_as_seam_fills_is_counted() {
|
||
let base = folder("seam-name");
|
||
let (mut s, _) = session(&base, false);
|
||
let out = log(
|
||
&mut s,
|
||
&base,
|
||
"var d = app.activeDocument, p = d.rasterItems[0].trace(), t = p.tracing, n = t.pathCount, a = t.anchorCount;\
|
||
var r = d.pathItems.rectangle(0, 0, 10, 10); r.filled = true; r.stroked = false; d.selection = [r]; vc.run('object.group');\
|
||
var g = d.pageItems[0]; g.name = 'Seam Fills'; vc.log(g.typename); g.move(p, ElementPlacement.PLACEATBEGINNING); vc.log(p.tracing.pathCount - n); vc.log(p.tracing.anchorCount - a);\
|
||
var q = d.pathItems.rectangle(0, 0, 10, 10); q.move(p, ElementPlacement.PLACEATEND); vc.log(p.tracing.pathCount - n); vc.log(p.tracing.anchorCount - a);",
|
||
);
|
||
assert_eq!(out, [json!("GroupItem"), json!(1), json!(4), json!(2), json!(8)]);
|
||
let d = &s.active().unwrap().doc;
|
||
let kids = d.children(Some(traces(&s)[0])).unwrap();
|
||
assert!(
|
||
kids.iter().any(|n| matches!(n.kind, NodeKind::Group { clip: true, .. }) && crate::cmd::is_seam_fills(n)),
|
||
"the trace keeps its own seam fills, below the path placed at the end"
|
||
);
|
||
let _ = std::fs::remove_dir_all(base);
|
||
}
|
||
|
||
#[test]
|
||
fn trace_image_resolution_is_one_number_or_none() {
|
||
let base = folder("resolution");
|
||
let (mut s, image) = session(&base, false);
|
||
let ppi = s.execute("image.info", &json!({"id": image.0})).unwrap()["ppi"][0].as_f64().unwrap();
|
||
let out = log(
|
||
&mut s,
|
||
&base,
|
||
"var r = app.activeDocument.rasterItems[0]; r.width = r.width * 2; r.height = r.height * 2;\
|
||
var t = r.trace().tracing; vc.log(t.imageResolution); t.releaseTracing(); r.width = r.width * 2;\
|
||
var m = ''; try { r.trace().tracing.imageResolution; } catch (e) { m = e.message; } vc.log(m);",
|
||
);
|
||
assert!((out[0].as_f64().unwrap() - ppi / 2.0).abs() < 1e-9, "{out:?}");
|
||
assert_eq!(out[1], json!("the source image has no single resolution"));
|
||
let _ = std::fs::remove_dir_all(base);
|
||
}
|
||
|
||
#[test]
|
||
fn placed_trace_returns_plugin_with_source_art() {
|
||
let base = folder("placed");
|
||
let (mut s, image) = session(&base, true);
|
||
let out = log(
|
||
&mut s,
|
||
&base,
|
||
"var d = app.activeDocument, pl = d.placedItems[0]; pl.name = 'src'; var p = pl.trace();\
|
||
vc.log(p.typename); vc.log(p.tracing.sourceArt.name); vc.log(pl.typename); vc.log(pl.file.name);\
|
||
var m = ''; try { pl.trace(); } catch (e) { m = e.message; } vc.log(m);",
|
||
);
|
||
assert_eq!(out, [json!("PluginItem"), json!("src"), json!("PlacedItem"), json!("disc.png"), json!("The image is the source art of a tracing")]);
|
||
let groups = traces(&s);
|
||
assert_eq!(groups.len(), 1);
|
||
let d = &s.active().unwrap().doc;
|
||
assert_eq!(d.parent_of(image), Some(groups[0]), "the image is the tracing's source");
|
||
let _ = std::fs::remove_dir_all(base);
|
||
}
|
||
|
||
#[test]
|
||
fn trace_checks_the_image_first() {
|
||
let base = folder("unbound");
|
||
let (mut s, image) = session(&base, true);
|
||
let out = log(
|
||
&mut s,
|
||
&base,
|
||
"var d = app.activeDocument, p = d.placedItems[0], n = d.placedItems.add(), m = [];\
|
||
try { n.trace(); } catch (e) { m.push(e.message); } p.embed(); try { p.trace(); } catch (e) { m.push(e.message); }\
|
||
try { PlacedItem.prototype.trace.call(d.rasterItems[0]); } catch (e) { m.push(e.message); } vc.log(m);",
|
||
);
|
||
assert_eq!(out, [json!(["PlacedItem.file is required", "Stale page item", "this is not a PlacedItem"])]);
|
||
assert!(traces(&s).is_empty());
|
||
assert!(s.active().unwrap().doc.node(image).is_some());
|
||
let _ = std::fs::remove_dir_all(base);
|
||
}
|
||
|
||
#[test]
|
||
fn trace_missing_link_refuses_preview() {
|
||
let base = folder("missing");
|
||
let (mut s, image) = session(&base, true);
|
||
std::fs::remove_file(base.join("main/disc.png")).unwrap();
|
||
let out = log(&mut s, &base, "var m = ''; try { app.activeDocument.placedItems[0].trace(); } catch (e) { m = e.message; } vc.log(m);");
|
||
assert_eq!(out, [json!("Linked image is missing")]);
|
||
assert!(traces(&s).is_empty());
|
||
assert_eq!(top(&s), [image]);
|
||
assert_eq!(undo_steps(&s), 1);
|
||
let _ = std::fs::remove_dir_all(base);
|
||
}
|
||
|
||
#[test]
|
||
fn trace_release_restores_source_kind() {
|
||
let base = folder("release");
|
||
let (mut s, image) = session(&base, false);
|
||
let out = log(
|
||
&mut s,
|
||
&base,
|
||
"var r = app.activeDocument.rasterItems[0]; r.name = 'src';\
|
||
var p = r.trace(), t = p.tracing, o = t.tracingOptions, back = t.releaseTracing();\
|
||
vc.log(back.name); vc.log(back.typename); vc.log(r.hidden);\
|
||
var m = []; try { p.name; } catch (e) { m.push(e.message); } try { t.pathCount; } catch (e) { m.push(e.message); }\
|
||
try { o.threshold; } catch (e) { m.push(e.message); } vc.log(m);",
|
||
);
|
||
assert_eq!(out[..3], [json!("src"), json!("RasterItem"), json!(false)]);
|
||
assert_eq!(out[3], json!(["Stale page item", "Stale page item", "Stale page item"]));
|
||
assert!(traces(&s).is_empty());
|
||
assert_eq!(top(&s), [image]);
|
||
let _ = std::fs::remove_dir_all(base);
|
||
}
|
||
|
||
#[test]
|
||
fn trace_expand_returns_group_and_stales_plugin() {
|
||
let base = folder("expand");
|
||
let (mut s, image) = session(&base, false);
|
||
let out = log(
|
||
&mut s,
|
||
&base,
|
||
"var r = app.activeDocument.rasterItems[0], p = r.trace(), t = p.tracing, m = [];\
|
||
try { t.expandTracing(true); } catch (e) { m.push(e.message); }\
|
||
try { t.expandTracing('yes'); } catch (e) { m.push(e.name); }\
|
||
vc.log(m); vc.log(p.isTracing);\
|
||
var g = t.expandTracing(); vc.log(g.typename); vc.log(p === g); m = [];\
|
||
try { p.isTracing; } catch (e) { m.push(e.message); } try { t.anchorCount; } catch (e) { m.push(e.message); }\
|
||
try { r.name; } catch (e) { m.push(e.message); } vc.log(m); vc.log(app.activeDocument.pageItems[0] === g);",
|
||
);
|
||
assert_eq!(out[0], json!(["TracingObject.expandTracing(true) is not implemented", "TypeError"]));
|
||
assert_eq!(out[1..4], [json!(true), json!("GroupItem"), json!(false)], "the group is a new object");
|
||
assert_eq!(out[4], json!(["Stale page item", "Stale page item", "Stale page item"]));
|
||
assert_eq!(out[5], json!(true), "the group read again is the object expandTracing gave");
|
||
assert!(traces(&s).is_empty());
|
||
let d = &s.active().unwrap().doc;
|
||
assert!(d.node(image).is_none(), "the expanded group keeps no source image");
|
||
let _ = std::fs::remove_dir_all(base);
|
||
}
|
||
|
||
#[test]
|
||
fn expand_keeps_images_moved_and_duplicated_into_the_tracing() {
|
||
let base = folder("expand-other-images");
|
||
let (mut s, source) = session(&base, false);
|
||
let png = base.join("main/disc.png");
|
||
s.execute("file.place", &json!({"path": png.to_string_lossy(), "link": false})).unwrap();
|
||
let out = log(
|
||
&mut s,
|
||
&base,
|
||
"var d = app.activeDocument, p = d.rasterItems[1].trace(), r = d.rasterItems[0]; r.name = 'other';\
|
||
r.duplicate(p, ElementPlacement.PLACEATEND); r.move(p, ElementPlacement.PLACEATBEGINNING);\
|
||
var g = p.tracing.expandTracing(); vc.log(g.typename); vc.log(d.rasterItems.length); vc.log(r.name);",
|
||
);
|
||
assert_eq!(out, [json!("GroupItem"), json!(2), json!("other")]);
|
||
let d = &s.active().unwrap().doc;
|
||
assert!(d.node(source).is_none());
|
||
let group = top(&s)[0];
|
||
let images: Vec<_> = d.children(Some(group)).unwrap().iter().filter(|n| matches!(n.kind, NodeKind::Image(_))).collect();
|
||
assert_eq!(images.len(), 2);
|
||
assert!(images.iter().all(|n| n.name.as_deref() == Some("other")));
|
||
let _ = std::fs::remove_dir_all(base);
|
||
}
|
||
|
||
#[test]
|
||
fn tracing_replacements_refuse_protected_artwork() {
|
||
let base = folder("protected-replacements");
|
||
for operation in ["trace", "retrace", "expand", "release", "view"] {
|
||
for protection in ["locked", "hidden", "locked-layer", "hidden-layer", "locked-artboard"] {
|
||
let (mut s, image) = session(&base, false);
|
||
let (target, action) = if operation == "trace" {
|
||
(image, "item.trace();")
|
||
} else {
|
||
let r = s.execute("imageTrace.make", &json!({"id": image.0})).unwrap();
|
||
let action = match operation {
|
||
"retrace" => "item.tracing.tracingOptions.threshold = 90;",
|
||
"expand" => "item.tracing.expandTracing();",
|
||
"view" => "item.tracing.tracingOptions.viewVector = ViewVectorType.TRACINGVIEWVECTOROUTLINES;",
|
||
_ => "item.tracing.releaseTracing();",
|
||
};
|
||
(NodeId(r["id"].as_u64().unwrap()), action)
|
||
};
|
||
s.edit("Protect artwork", |d, _| {
|
||
if protection == "locked-artboard" {
|
||
d.artboards[0].locked = true;
|
||
} else {
|
||
let protected = if protection.ends_with("-layer") { d.layers[0].id } else { target };
|
||
let node = d.node_mut(protected).unwrap();
|
||
node.locked = protection.starts_with("locked");
|
||
node.visible = !protection.starts_with("hidden");
|
||
}
|
||
Ok(())
|
||
})
|
||
.unwrap();
|
||
let before = vectorcraft_format::save(&s.active().unwrap().doc, false);
|
||
let selection = s.active().unwrap().selection.clone();
|
||
let steps = undo_steps(&s);
|
||
let out = log(
|
||
&mut s,
|
||
&base,
|
||
&format!("var item = app.activeDocument.pageItems[0], m = ''; try {{ {action} }} catch (e) {{ m = e.message; }} vc.log(m);"),
|
||
);
|
||
assert_eq!(out, [json!(format!("Cannot edit page item {}", target.0))], "{operation}: {protection}");
|
||
assert_eq!(vectorcraft_format::save(&s.active().unwrap().doc, false), before, "{operation}: {protection}");
|
||
assert_eq!(s.active().unwrap().selection, selection);
|
||
assert_eq!(undo_steps(&s), steps);
|
||
}
|
||
}
|
||
let _ = std::fs::remove_dir_all(base);
|
||
}
|
||
|
||
#[test]
|
||
fn retrace_refuses_added_artwork_before_changing_the_document() {
|
||
let base = folder("retrace-added-artwork");
|
||
for artwork in [
|
||
"r.move(p, ElementPlacement.PLACEATEND);",
|
||
"r.duplicate(p, ElementPlacement.PLACEATEND);",
|
||
"d.pathItems.rectangle(20, 20, 10, 10).move(p, ElementPlacement.PLACEATEND);",
|
||
] {
|
||
for action in ["o.threshold = 90;", "o.loadFromPreset('Silhouettes');"] {
|
||
let (mut s, _) = session(&base, false);
|
||
s.execute("file.place", &json!({"path": base.join("main/disc.png").to_string_lossy(), "link": false})).unwrap();
|
||
let setup = format!("var d = app.activeDocument, r = d.rasterItems[0], p = d.rasterItems[1].trace(); {artwork}");
|
||
let mut expected = Session::new();
|
||
expected.docs = s.docs.clone();
|
||
expected.active = s.active;
|
||
log(&mut expected, &base, &setup);
|
||
let before = vectorcraft_format::save(&expected.active().unwrap().doc, false);
|
||
let selection = expected.active().unwrap().selection.clone();
|
||
let steps = undo_steps(&expected);
|
||
let out = log(
|
||
&mut s,
|
||
&base,
|
||
&format!(
|
||
"{setup} var items = app.activeDocument.pageItems;\
|
||
for (var i = 0; i < items.length; i++) if (items[i].typename === 'PluginItem') p = items[i];\
|
||
var o = p.tracing.tracingOptions, m = '';\
|
||
try {{ {action} }} catch (e) {{ m = e.message; }} vc.log(m);"
|
||
),
|
||
);
|
||
assert_eq!(out, [json!("Cannot retrace a tracing containing added artwork")], "{artwork} {action}");
|
||
assert_eq!(vectorcraft_format::save(&s.active().unwrap().doc, false), before);
|
||
assert_eq!(s.active().unwrap().selection, selection);
|
||
assert_eq!(undo_steps(&s), steps);
|
||
}
|
||
}
|
||
let _ = std::fs::remove_dir_all(base);
|
||
}
|
||
|
||
#[test]
|
||
fn copied_traces_remap_child_records_without_accepting_added_artwork() {
|
||
let base = folder("retrace-copied-artwork");
|
||
for (added, retraced) in [(false, false), (true, false), (false, true), (true, true)] {
|
||
let (mut s, _) = session(&base, false);
|
||
let retrace = if retraced { "o.threshold = 100;" } else { "" };
|
||
let artwork = if added { "d.pathItems.rectangle(20, 20, 10, 10).move(copy, ElementPlacement.PLACEATEND);" } else { "" };
|
||
let out = log(
|
||
&mut s,
|
||
&base,
|
||
&format!(
|
||
"var d = app.activeDocument, p = d.rasterItems[0].trace(), copy = p.duplicate(), o = copy.tracing.tracingOptions;\
|
||
{retrace} {artwork}\
|
||
var m = ''; try {{ o.threshold = 90; }} catch (e) {{ m = e.message; }}\
|
||
vc.log(m); vc.log(copy.isTracing); vc.log(o.threshold);"
|
||
),
|
||
);
|
||
let message = if added { "Cannot retrace a tracing containing added artwork" } else { "" };
|
||
assert_eq!(out[..2], [json!(message), json!(true)], "added: {added}, retraced: {retraced}");
|
||
if !added {
|
||
assert_eq!(out[2], json!(90));
|
||
}
|
||
}
|
||
let _ = std::fs::remove_dir_all(base);
|
||
}
|
||
|
||
/// The objects in the object `id` of the active document, without it, in order.
|
||
fn members(s: &Session, id: NodeId) -> Vec<NodeId> {
|
||
let mut out = vec![];
|
||
if let Some(n) = s.active().unwrap().doc.node(id) {
|
||
n.walk(&mut |m| {
|
||
if m.id != id {
|
||
out.push(m.id);
|
||
}
|
||
});
|
||
}
|
||
out
|
||
}
|
||
|
||
/// A new session with the active document of `s`, saved and opened again.
|
||
fn reopened(s: &Session) -> Session {
|
||
let bytes = vectorcraft_format::save(&s.active().unwrap().doc, false);
|
||
let mut o = Session::new();
|
||
o.execute("document.open", &json!({"name": "traced.vectorcraft", "dataBase64": vectorcraft_format::base64_encode(&bytes)})).unwrap();
|
||
o
|
||
}
|
||
|
||
/// Traces the Image Trace object `index` of the active document's page items again with a
|
||
/// threshold of 90, and logs the error, or `""`.
|
||
fn retrace_item(index: usize) -> String {
|
||
format!(
|
||
"(function () {{ var items = app.activeDocument.pageItems, found = [];\
|
||
for (var i = 0; i < items.length; i++) if (items[i].typename === 'PluginItem') found.push(items[i]);\
|
||
var o = found[{index}].tracing.tracingOptions, m = '';\
|
||
try {{ o.threshold = 90; }} catch (e) {{ m = e.message; }} vc.log(m); }})();"
|
||
)
|
||
}
|
||
|
||
const ADDED_ARTWORK: &str = "Cannot retrace a tracing containing added artwork";
|
||
|
||
#[test]
|
||
fn retrace_refuses_artwork_added_before_the_run() {
|
||
let base = folder("retrace-earlier-artwork");
|
||
for by_command in [false, true] {
|
||
for reopen in [false, true] {
|
||
let (mut s, image) = session(&base, false);
|
||
let trace = if by_command {
|
||
s.execute("imageTrace.make", &json!({"id": image.0})).unwrap();
|
||
"var p = app.activeDocument.pageItems[0];"
|
||
} else {
|
||
"var p = app.activeDocument.rasterItems[0].trace();"
|
||
};
|
||
log(&mut s, &base, &format!("{trace} app.activeDocument.pathItems.rectangle(20, 20, 10, 10).move(p, ElementPlacement.PLACEATEND);"));
|
||
let mut s = if reopen { reopened(&s) } else { s };
|
||
let before = vectorcraft_format::save(&s.active().unwrap().doc, false);
|
||
let steps = undo_steps(&s);
|
||
let out = log(&mut s, &base, &retrace_item(0));
|
||
assert_eq!(out, [json!(ADDED_ARTWORK)], "by command: {by_command}, reopened: {reopen}");
|
||
assert_eq!(vectorcraft_format::save(&s.active().unwrap().doc, false), before, "by command: {by_command}, reopened: {reopen}");
|
||
assert_eq!(undo_steps(&s), steps);
|
||
}
|
||
}
|
||
let _ = std::fs::remove_dir_all(base);
|
||
}
|
||
|
||
#[test]
|
||
fn retrace_takes_a_tracing_whose_traced_objects_were_edited() {
|
||
let base = folder("retrace-edited-artwork");
|
||
for reopen in [false, true] {
|
||
let (mut s, image) = session(&base, false);
|
||
let group = NodeId(s.execute("imageTrace.make", &json!({"id": image.0})).unwrap()["id"].as_u64().unwrap());
|
||
let made = s.active().unwrap().doc.node(group).and_then(|g| g.trace_made()).expect("the trace records what it made");
|
||
let held = members(&s, group);
|
||
assert!(held.len() > 1 && held.iter().all(|m| made.contains(*m)), "{held:?} {made:?}");
|
||
assert!(!made.contains(group));
|
||
let path = held[held.len() - 1];
|
||
s.execute("object.move", &json!({"ids": [path.0], "dx": 5, "dy": 0})).unwrap();
|
||
let mut s = if reopen { reopened(&s) } else { s };
|
||
let out = log(&mut s, &base, &format!("{} vc.log(app.activeDocument.pageItems[0].tracing.tracingOptions.threshold);", retrace_item(0)));
|
||
assert_eq!(out, [json!(""), json!(90)], "reopened: {reopen}");
|
||
}
|
||
let _ = std::fs::remove_dir_all(base);
|
||
}
|
||
|
||
#[test]
|
||
fn a_copied_tracing_retraces_in_a_later_run() {
|
||
let base = folder("retrace-copy-later");
|
||
for added in [false, true] {
|
||
for reopen in [false, true] {
|
||
let (mut s, _) = session(&base, false);
|
||
let artwork = if added { "app.activeDocument.pathItems.rectangle(20, 20, 10, 10).move(copy, ElementPlacement.PLACEATEND);" } else { "" };
|
||
log(&mut s, &base, &format!("var p = app.activeDocument.rasterItems[0].trace(), copy = p.duplicate(); {artwork}"));
|
||
let groups = traces(&s);
|
||
assert_eq!(groups.len(), 2);
|
||
let records: Vec<_> = groups.iter().map(|g| s.active().unwrap().doc.node(*g).and_then(|n| n.trace_made()).unwrap()).collect();
|
||
for (k, g) in groups.iter().enumerate() {
|
||
assert!(members(&s, *g).iter().all(|m| !records[1 - k].contains(*m)), "a tracing records none of the other's objects");
|
||
}
|
||
let mut s = if reopen { reopened(&s) } else { s };
|
||
let out = log(&mut s, &base, &format!("{} {}", retrace_item(0), retrace_item(1)));
|
||
let message = if added { ADDED_ARTWORK } else { "" };
|
||
assert_eq!(out, [json!(message), json!("")], "added: {added}, reopened: {reopen}");
|
||
}
|
||
}
|
||
let _ = std::fs::remove_dir_all(base);
|
||
}
|
||
|
||
#[test]
|
||
fn a_tracing_saved_without_its_record_is_checked_only_within_a_run() {
|
||
let base = folder("retrace-legacy");
|
||
for same_run in [false, true] {
|
||
let (mut s, image) = session(&base, false);
|
||
let group = NodeId(s.execute("imageTrace.make", &json!({"id": image.0})).unwrap()["id"].as_u64().unwrap());
|
||
let doc = std::sync::Arc::make_mut(&mut s.active_mut().unwrap().doc);
|
||
let trace = doc.node_mut(group).and_then(|g| g.extras_if_any()).and_then(|e| e.trace.as_deref_mut()).unwrap();
|
||
trace.as_object_mut().unwrap().remove(crate::doc::trace::TRACE_MADE);
|
||
let add = "var r = app.activeDocument.pathItems.rectangle(20, 20, 10, 10); r.name = 'added'; r.move(app.activeDocument.pageItems[1], ElementPlacement.PLACEATEND);";
|
||
let out = if same_run {
|
||
log(&mut s, &base, &format!("{add} {}", retrace_item(0)))
|
||
} else {
|
||
log(&mut s, &base, add);
|
||
log(&mut s, &base, &retrace_item(0))
|
||
};
|
||
let message = if same_run { ADDED_ARTWORK } else { "" };
|
||
assert_eq!(out, [json!(message)], "same run: {same_run}");
|
||
let mut named = false;
|
||
s.active().unwrap().doc.walk(|n| named |= n.name.as_deref() == Some("added"));
|
||
assert_eq!(named, same_run, "tracing again drops what was added, as before");
|
||
}
|
||
let _ = std::fs::remove_dir_all(base);
|
||
}
|
||
|
||
#[test]
|
||
fn a_tracing_saved_without_its_record_counts_artwork_added_through_its_paths() {
|
||
let base = folder("retrace-legacy-paths");
|
||
let (mut s, image) = session(&base, false);
|
||
let group = NodeId(s.execute("imageTrace.make", &json!({"id": image.0})).unwrap()["id"].as_u64().unwrap());
|
||
let doc = std::sync::Arc::make_mut(&mut s.active_mut().unwrap().doc);
|
||
let trace = doc.node_mut(group).and_then(|g| g.extras_if_any()).and_then(|e| e.trace.as_deref_mut()).unwrap();
|
||
trace.as_object_mut().unwrap().remove(crate::doc::trace::TRACE_MADE);
|
||
let held = members(&s, group);
|
||
// The script reaches the tracing's paths before the tracing itself.
|
||
let add = "var d = app.activeDocument, p = d.pathItems[0], r = d.pathItems.rectangle(20, 20, 10, 10);\
|
||
r.name = 'added'; r.move(p, ElementPlacement.PLACEBEFORE);";
|
||
let out = log(&mut s, &base, &format!("{add} {}", retrace_item(0)));
|
||
assert_eq!(out, [json!(ADDED_ARTWORK)]);
|
||
assert_eq!(members(&s, group).len(), held.len() + 1, "the added path stays in the tracing");
|
||
let _ = std::fs::remove_dir_all(base);
|
||
}
|
||
|
||
#[test]
|
||
fn a_tracing_saved_without_its_record_is_checked_again_after_a_revert() {
|
||
let base = folder("retrace-legacy-revert");
|
||
let path = base.join("main/legacy.vectorcraft");
|
||
for seen_first in [false, true] {
|
||
for added in [false, true] {
|
||
let (mut s, image) = session(&base, false);
|
||
let group = NodeId(s.execute("imageTrace.make", &json!({"id": image.0})).unwrap()["id"].as_u64().unwrap());
|
||
let doc = std::sync::Arc::make_mut(&mut s.active_mut().unwrap().doc);
|
||
let trace = doc.node_mut(group).and_then(|g| g.extras_if_any()).and_then(|e| e.trace.as_deref_mut()).unwrap();
|
||
trace.as_object_mut().unwrap().remove(crate::doc::trace::TRACE_MADE);
|
||
s.execute("file.saveAs", &json!({"path": path.to_string_lossy()})).unwrap();
|
||
let held = members(&s, group);
|
||
s.execute("edit.clear", &json!({"ids": [held[held.len() - 1].0]})).unwrap();
|
||
let seen = if seen_first { "var p = app.activeDocument.pageItems[0];" } else { "app.activeDocument.pathItems[0].name = 'x';" };
|
||
let add = if added {
|
||
format!(
|
||
"var d = app.activeDocument, r = d.pathItems.rectangle(20, 20, 10, 10);\
|
||
r.move(d.pageItems[1], ElementPlacement.PLACEATEND); vc.run('file.saveAs', {{path: {}}}); r.name = 'after';",
|
||
json!(path.to_string_lossy())
|
||
)
|
||
} else {
|
||
String::new()
|
||
};
|
||
let out = log(&mut s, &base, &format!("{seen} {add} vc.run('file.revert'); {}", retrace_item(0)));
|
||
// A revert keeps the snapshot taken before it.
|
||
let message = if added || seen_first { ADDED_ARTWORK } else { "" };
|
||
assert_eq!(out, [json!(message)], "seen first: {seen_first}, added: {added}");
|
||
}
|
||
}
|
||
let _ = std::fs::remove_dir_all(base);
|
||
}
|
||
|
||
#[test]
|
||
fn engine_trace_can_be_retraced_by_a_script() {
|
||
let base = folder("retrace-engine-artwork");
|
||
let (mut s, image) = session(&base, false);
|
||
let made = s.execute("imageTrace.make", &json!({"id": image.0})).unwrap();
|
||
let group = NodeId(made["id"].as_u64().unwrap());
|
||
let steps = undo_steps(&s);
|
||
let out = log(
|
||
&mut s,
|
||
&base,
|
||
"var p = app.activeDocument.pageItems[0], o = p.tracing.tracingOptions;\
|
||
o.threshold = 90; vc.log(o.threshold); vc.log(p.isTracing);",
|
||
);
|
||
assert_eq!(out, [json!(90), json!(true)]);
|
||
let groups = traces(&s);
|
||
assert_eq!(groups.len(), 1);
|
||
assert_ne!(groups[0], group);
|
||
assert_eq!(trace_of(&s, groups[0])["params"]["threshold"], json!(90));
|
||
assert_eq!(s.active().unwrap().doc.parent_of(image), Some(groups[0]));
|
||
assert_eq!(undo_steps(&s), steps + 1);
|
||
let _ = std::fs::remove_dir_all(base);
|
||
}
|
||
|
||
#[test]
|
||
fn retrace_limit_counts_retraces_of_an_undone_group() {
|
||
let base = folder("retrace-limit-undo");
|
||
let (mut s, _) = session(&base, false);
|
||
let out = log(
|
||
&mut s,
|
||
&base,
|
||
"var p = app.activeDocument.rasterItems[0].trace(), o = p.tracing.tracingOptions, count = 0, m = '';\
|
||
try { for (; count < 10001; count++) { o.threshold = 90; app.undo(); } } catch (e) { m = e.message; }\
|
||
vc.log(count); vc.log(m); vc.log(p.isTracing);",
|
||
);
|
||
assert_eq!(out, [json!(10000), json!("a run traces a tracing again at most 10000 times"), json!(true)]);
|
||
let _ = std::fs::remove_dir_all(base);
|
||
}
|
||
|
||
#[test]
|
||
fn trace_and_option_changes_log_command_warnings() {
|
||
let base = folder("trace-warnings");
|
||
let (mut s, _) = session(&base, false);
|
||
let png = base.join("main/wide.png");
|
||
std::fs::write(&png, vectorcraft_trace::Raster::from_fn(1501, 2, |_, _| [0, 0, 0, 255]).encode_png()).unwrap();
|
||
let placed = s.execute("file.place", &json!({"path": png.to_string_lossy(), "link": false})).unwrap();
|
||
let image = placed["ids"][0].as_u64().unwrap();
|
||
let made = s.execute("imageTrace.make", &json!({"id": image})).unwrap();
|
||
let warnings = made["warnings"].as_array().unwrap().clone();
|
||
assert!(!warnings.is_empty());
|
||
s.execute("imageTrace.release", &json!({"id": made["id"]})).unwrap();
|
||
let report = run(&mut s, &base, "var p = app.activeDocument.rasterItems[0].trace(); p.tracing.tracingOptions.threshold = 90;").unwrap();
|
||
let lines = report["console"]["lines"].as_array().unwrap();
|
||
let expected: Vec<_> = warnings.iter().map(|w| json!(format!("imageTrace.make: {}", w.as_str().unwrap()))).collect();
|
||
assert_eq!(lines, &expected.iter().chain(&expected).cloned().collect::<Vec<_>>());
|
||
let _ = std::fs::remove_dir_all(base);
|
||
}
|
||
|
||
#[test]
|
||
fn option_changes_log_why_no_paths_were_traced() {
|
||
let base = folder("trace-no-paths-warning");
|
||
let (mut s, image) = session(&base, false);
|
||
let made = s.execute("imageTrace.make", &json!({"id": image.0, "params": {"keepColors": ["#ff00ff"]}})).unwrap();
|
||
assert_eq!(made["paths"], json!(0));
|
||
let warnings = made["warnings"].as_array().unwrap();
|
||
assert!(warnings.iter().any(|w| w.as_str().unwrap().contains("Nothing was traced")));
|
||
let report = run(&mut s, &base, "app.activeDocument.pageItems[0].tracing.tracingOptions.threshold = 90;").unwrap();
|
||
let expected: Vec<_> = warnings.iter().map(|w| json!(format!("imageTrace.make: {}", w.as_str().unwrap()))).collect();
|
||
assert_eq!(report["console"]["lines"], json!(expected));
|
||
let _ = std::fs::remove_dir_all(base);
|
||
}
|
||
|
||
#[test]
|
||
fn tracing_parent_keeps_plugin_identity_after_retracing() {
|
||
let base = folder("parent-identity");
|
||
let (mut s, _) = session(&base, false);
|
||
let out = log(
|
||
&mut s,
|
||
&base,
|
||
"var p = app.activeDocument.rasterItems[0].trace(), t = p.tracing;\
|
||
vc.log(t.parent === p); t.tracingOptions.threshold = 90; vc.log(t.parent === p);\
|
||
vc.log(p.tracing.parent === p); t.tracingOptions.threshold = 100; vc.log(t.parent === p);",
|
||
);
|
||
assert_eq!(out, vec![json!(true); 4]);
|
||
let _ = std::fs::remove_dir_all(base);
|
||
}
|
||
|
||
#[test]
|
||
fn plugin_is_tracing_refuses_a_replaced_source_without_reading_tracing() {
|
||
let base = folder("plugin-replaced-source");
|
||
let (mut s, source) = session(&base, false);
|
||
s.execute("file.place", &json!({"path": base.join("main/disc.png").to_string_lossy(), "link": false})).unwrap();
|
||
let out = log(
|
||
&mut s,
|
||
&base,
|
||
&format!(
|
||
"var d = app.activeDocument, p = d.rasterItems[1].trace(), r = d.rasterItems[0];\
|
||
r.move(p, ElementPlacement.PLACEATEND); vc.run('edit.clear', {{ids: [{}]}}); var m = [];\
|
||
try {{ p.isTracing; }} catch (e) {{ m.push(e.message); }}\
|
||
try {{ p.tracing; }} catch (e) {{ m.push(e.message); }} vc.log(m);",
|
||
source.0
|
||
),
|
||
);
|
||
assert_eq!(out, [json!(["Stale page item", "Stale page item"])]);
|
||
let _ = std::fs::remove_dir_all(base);
|
||
}
|
||
|
||
#[test]
|
||
fn tracing_handle_is_stale_when_another_image_replaces_its_source() {
|
||
let base = folder("replaced-source");
|
||
let (mut s, source) = session(&base, false);
|
||
let png = base.join("main/disc.png");
|
||
s.execute("file.place", &json!({"path": png.to_string_lossy(), "link": false})).unwrap();
|
||
let out = log(
|
||
&mut s,
|
||
&base,
|
||
&format!(
|
||
"var d = app.activeDocument, p = d.rasterItems[1].trace(), t = p.tracing, o = t.tracingOptions, r = d.rasterItems[0];\
|
||
r.move(p, ElementPlacement.PLACEATEND); vc.run('edit.clear', {{ids: [{}]}}); var m = [];\
|
||
try {{ t.sourceArt; }} catch (e) {{ m.push(e.message); }}\
|
||
try {{ t.pathCount; }} catch (e) {{ m.push(e.message); }}\
|
||
try {{ o.threshold; }} catch (e) {{ m.push(e.message); }}\
|
||
try {{ p.isTracing; }} catch (e) {{ m.push(e.message); }} vc.log(m);",
|
||
source.0
|
||
),
|
||
);
|
||
assert_eq!(out, [json!(vec!["Stale page item"; 4])]);
|
||
assert!(s.active().unwrap().doc.node(source).is_none());
|
||
let _ = std::fs::remove_dir_all(base);
|
||
}
|
||
|
||
#[test]
|
||
fn tracing_replacements_preserve_direct_selection_of_other_paths() {
|
||
for (name, finish) in [
|
||
("make", ""),
|
||
("retrace", "p.tracing.tracingOptions.threshold = 90;"),
|
||
("expand", "p.tracing.expandTracing();"),
|
||
("release", "p.tracing.releaseTracing();"),
|
||
] {
|
||
let base = folder(&format!("direct-selection-{name}"));
|
||
let (mut s, image) = session(&base, false);
|
||
let mut paths = vec![];
|
||
for x in [100, 200] {
|
||
let r = s.execute("shape.rectangle", &json!({"x": x, "y": 100, "width": 20, "height": 20})).unwrap();
|
||
paths.push(NodeId(r["id"].as_u64().unwrap()));
|
||
}
|
||
s.execute("select.anchors", &json!({"id": paths[0].0, "anchors": [[0, 1]], "mode": "set"})).unwrap();
|
||
s.execute("select.segments", &json!({"id": paths[1].0, "segments": [[0, 1]], "mode": "add"})).unwrap();
|
||
s.execute("select.add", &json!({"ids": [image.0]})).unwrap();
|
||
let before = s.active().unwrap().selection.clone();
|
||
log(&mut s, &base, &format!("var p = app.activeDocument.rasterItems[0].trace(); {finish}"));
|
||
let after = &s.active().unwrap().selection;
|
||
assert_eq!(after.anchors, before.anchors, "{name}");
|
||
assert_eq!(after.segments, before.segments, "{name}");
|
||
assert_eq!(after.objects.len(), before.objects.len(), "{name}");
|
||
assert_eq!(after.objects[..2], paths, "{name}");
|
||
if name == "release" {
|
||
assert_eq!(after.objects[2], image);
|
||
} else {
|
||
assert_ne!(after.objects[2], image, "{name}");
|
||
assert!(matches!(s.active().unwrap().doc.node(after.objects[2]).unwrap().kind, NodeKind::Group { .. }));
|
||
}
|
||
let _ = std::fs::remove_dir_all(base);
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn trace_options_retrace_preserves_source_and_view() {
|
||
let base = folder("options");
|
||
let (mut s, image) = session(&base, false);
|
||
let defaults = serde_json::to_value(vectorcraft_trace::TraceParams::default()).unwrap();
|
||
let out = log(
|
||
&mut s,
|
||
&base,
|
||
"var r = app.activeDocument.rasterItems[0]; r.name = 'src'; var p = r.trace(), t = p.tracing, o = t.tracingOptions;\
|
||
vc.log([o.tracingMode, o.threshold, o.fills, o.strokes, o.maxColors, o.palette, o.ignoreWhite, o.minArea]);\
|
||
vc.log([o.viewRaster, o.viewVector]);\
|
||
o.viewVector = ViewVectorType.TRACINGVIEWVECTOROUTLINES; o.viewRaster = ViewRasterType.TRACINGVIEWRASTERORIGINALIMAGE;\
|
||
o.threshold = 200; o.minArea = 4;\
|
||
vc.log([o.threshold, o.minArea, o.preset, o.viewRaster, o.viewVector]);\
|
||
vc.log(t.sourceArt.name); vc.log(r.name); vc.log(p.isTracing); vc.log(p.tracing.tracingOptions.threshold); vc.log(t.pathCount > 0);",
|
||
);
|
||
let mode = |m: &str| json!(format!("TracingModeType.TRACINGMODE{m}"));
|
||
let expected_mode = match defaults["mode"].as_str() {
|
||
Some("blackAndWhite") => mode("BLACKANDWHITE"),
|
||
Some("grayscale") => mode("GRAY"),
|
||
_ => mode("COLOR"),
|
||
};
|
||
assert_eq!(
|
||
out[0],
|
||
json!([
|
||
expected_mode,
|
||
defaults["threshold"],
|
||
defaults["fills"],
|
||
defaults["strokes"],
|
||
defaults["colors"],
|
||
"Limited",
|
||
defaults["ignoreWhite"],
|
||
defaults["noise"]
|
||
])
|
||
);
|
||
assert_eq!(out[1], json!(["ViewRasterType.TRACINGVIEWRASTERNOIMAGE", "ViewVectorType.TRACINGVIEWVECTORTRACINGRESULT"]));
|
||
assert_eq!(out[2], json!([200, 4, "Custom", "ViewRasterType.TRACINGVIEWRASTERORIGINALIMAGE", "ViewVectorType.TRACINGVIEWVECTOROUTLINES"]));
|
||
assert_eq!(out[3..], [json!("src"), json!("src"), json!(true), json!(200), json!(true)]);
|
||
let groups = traces(&s);
|
||
assert_eq!(groups.len(), 1);
|
||
let t = trace_of(&s, groups[0]);
|
||
assert_eq!(
|
||
(t["params"]["threshold"].clone(), t["params"]["noise"].clone(), t["view"].clone()),
|
||
(json!(200), json!(4), json!("outlinesWithSourceImage"))
|
||
);
|
||
assert_eq!(s.active().unwrap().doc.parent_of(image), Some(groups[0]));
|
||
|
||
// Assigning the values the options have already changes nothing.
|
||
let before = (undo_steps(&s), traces(&s));
|
||
let out = log(
|
||
&mut s,
|
||
&base,
|
||
"var o = app.activeDocument.pageItems[0].tracing.tracingOptions; o.threshold = 200; o.minArea = 4; o.fills = true;\
|
||
o.viewVector = ViewVectorType.TRACINGVIEWVECTOROUTLINES; vc.log(o.threshold);",
|
||
);
|
||
assert_eq!(out, [json!(200)]);
|
||
assert_eq!((undo_steps(&s), traces(&s)), before);
|
||
let _ = std::fs::remove_dir_all(base);
|
||
}
|
||
|
||
#[test]
|
||
fn trace_invalid_option_is_atomic() {
|
||
let base = folder("invalid");
|
||
let (mut s, _) = session(&base, false);
|
||
log(&mut s, &base, "app.activeDocument.rasterItems[0].trace();");
|
||
let before = (undo_steps(&s), traces(&s), trace_of(&s, traces(&s)[0]));
|
||
let saved = vectorcraft_format::save(&s.active().unwrap().doc, false);
|
||
let cases = [
|
||
("o.threshold = 'x'", "TypeError"),
|
||
("o.threshold = 256", "TracingOptions.threshold is out of range"),
|
||
("o.threshold = -1", "TracingOptions.threshold is out of range"),
|
||
("o.threshold = 1.5", "TracingOptions.threshold is out of range"),
|
||
("o.threshold = NaN", "TypeError"),
|
||
("o.maxColors = 1", "TracingOptions.maxColors is out of range"),
|
||
("o.maxColors = 257", "TracingOptions.maxColors is out of range"),
|
||
("o.minArea = 1e12", "TracingOptions.minArea is out of range"),
|
||
("o.fills = 1", "TypeError"),
|
||
("o.fills = false", "TracingOptions requires fills or strokes"),
|
||
("o.tracingMode = 'color'", "TypeError"),
|
||
("o.palette = 'Spectrum'", "TracingOptions.palette has an invalid value"),
|
||
("o.palette = 3", "TypeError"),
|
||
("o.viewRaster = ViewRasterType.TRACINGVIEWRASTERADJUSTEDIMAGE", "TracingOptions.viewRaster has an invalid value"),
|
||
("o.viewRaster = ViewRasterType.TRACINGVIEWRASTERORIGINALIMAGE", "TracingOptions.viewRaster has an invalid value"),
|
||
("o.viewVector = 'outlines'", "TypeError"),
|
||
("o.pathFitting = 3", "TracingOptions.pathFitting is not implemented"),
|
||
("o.cornerAngle", "TracingOptions.cornerAngle is not implemented"),
|
||
("o.resampleResolution = 72", "TracingOptions.resampleResolution is not implemented"),
|
||
("t.areaCount", "TracingObject.areaCount is not implemented"),
|
||
("o.loadFromPreset('No Such Preset')", "no built-in or saved preset has that name"),
|
||
("o.loadFromPreset('../Default')", "cannot hold"),
|
||
("o.loadFromPreset('C:\\\\x')", "cannot hold"),
|
||
("o.loadFromPreset('a\\u0000b')", "cannot hold"),
|
||
("o.loadFromPreset(new Array(300).join('x'))", "at most 256 bytes"),
|
||
("o.loadFromPreset(' ')", "the preset name is empty"),
|
||
("o.loadFromPreset(5)", "TypeError"),
|
||
("o.storeToPreset('Mine')", "a script cannot run `imageTrace.presets.save`"),
|
||
("o.storeToPreset('../Mine')", "cannot hold"),
|
||
];
|
||
let mut wrong = vec![];
|
||
for (code, message) in cases {
|
||
let out = log(
|
||
&mut s,
|
||
&base,
|
||
&format!(
|
||
"var t = app.activeDocument.pageItems[0].tracing, o = t.tracingOptions, m = 'none';\
|
||
try {{ {code}; }} catch (e) {{ m = e.name + ': ' + e.message; }} vc.log(m); vc.log(o.threshold);"
|
||
),
|
||
);
|
||
let m = out[0].as_str().unwrap_or_default().to_string();
|
||
let now = (undo_steps(&s), traces(&s), trace_of(&s, traces(&s)[0]));
|
||
let unchanged = vectorcraft_format::save(&s.active().unwrap().doc, false) == saved;
|
||
if !m.contains(message) || out[1] != before.2["params"]["threshold"] || now != before || !unchanged {
|
||
wrong.push(format!("{code}: {m}"));
|
||
}
|
||
}
|
||
assert!(wrong.is_empty(), "{wrong:#?}");
|
||
assert!(s.prefs.trace_presets.is_empty(), "no preset was saved");
|
||
let _ = std::fs::remove_dir_all(base);
|
||
}
|
||
|
||
#[test]
|
||
fn trace_presets_load_and_locked_store() {
|
||
let base = folder("presets");
|
||
let (mut s, _) = session(&base, false);
|
||
let silhouettes = serde_json::to_value(vectorcraft_trace::preset("Silhouettes").unwrap()).unwrap();
|
||
let out = log(
|
||
&mut s,
|
||
&base,
|
||
"var p = app.activeDocument.rasterItems[0].trace(), o = p.tracing.tracingOptions;\
|
||
vc.log(o.loadFromPreset('Silhouettes')); vc.log(o.preset); vc.log(o.threshold);\
|
||
vc.log(o.storeToPreset('Default')); vc.log(o.storeToPreset('custom')); vc.log(o.storeToPreset('Silhouettes'));",
|
||
);
|
||
assert_eq!(out, [json!(true), json!("Silhouettes"), silhouettes["threshold"].clone(), json!(false), json!(false), json!(false)]);
|
||
let t = trace_of(&s, traces(&s)[0]);
|
||
assert_eq!(t["params"], silhouettes);
|
||
|
||
// Loading the preset the tracing has already traces nothing again.
|
||
let before = (undo_steps(&s), traces(&s));
|
||
let out = log(&mut s, &base, "vc.log(app.activeDocument.pageItems[0].tracing.tracingOptions.loadFromPreset('silhouettes'));");
|
||
assert_eq!(out, [json!(true)]);
|
||
assert_eq!((undo_steps(&s), traces(&s)), before);
|
||
let _ = std::fs::remove_dir_all(base);
|
||
}
|
||
|
||
#[test]
|
||
fn trace_external_retrace_undo_and_source_delete() {
|
||
let base = folder("stale");
|
||
let (mut s, image) = session(&base, false);
|
||
let threshold = serde_json::to_value(vectorcraft_trace::TraceParams::default()).unwrap()["threshold"].clone();
|
||
let out = log(
|
||
&mut s,
|
||
&base,
|
||
&format!(
|
||
"var d = app.activeDocument, m = [];\
|
||
var p = d.rasterItems[0].trace(), t = p.tracing; d.selection = p; vc.run('imageTrace.make', {{}});\
|
||
try {{ t.pathCount; }} catch (e) {{ m.push(e.message); }} try {{ p.isTracing; }} catch (e) {{ m.push(e.message); }}\
|
||
var q = d.pageItems[0], u = q.tracing, o = u.tracingOptions; o.threshold = 90; vc.log(o.threshold); vc.log(q.isTracing);\
|
||
vc.run('edit.undo'); vc.log(q.isTracing); vc.log(o.threshold); vc.log(u.pathCount > 0);\
|
||
var r = ''; try {{ u.sourceArt.remove(); }} catch (e) {{ r = e.message; }} vc.log(r); vc.log(u.pathCount > 0);\
|
||
vc.run('edit.clear', {{ids: [{}]}});\
|
||
try {{ u.pathCount; }} catch (e) {{ m.push(e.message); }} try {{ q.isTracing; }} catch (e) {{ m.push(e.message); }}\
|
||
vc.log(d.pageItems[0].typename); vc.log(m);",
|
||
image.0
|
||
),
|
||
);
|
||
assert_eq!(out[..5], [json!(90), json!(true), json!(true), threshold, json!(true)], "the undo puts the first tracing back");
|
||
assert!(out[5].as_str().is_some_and(|m| m.starts_with("cannot delete hidden or locked objects")), "{:?}", out[5]);
|
||
assert_eq!(out[6], json!(true), "the refused remove leaves the tracing");
|
||
assert_eq!(out[7], json!("GroupItem"), "a group without its source image is no longer a tracing");
|
||
assert_eq!(out[8], json!(vec!["Stale page item"; 4]));
|
||
let _ = std::fs::remove_dir_all(base);
|
||
}
|
||
|
||
/// After two option changes, an Undo puts back the tracing the first change made, and the objects
|
||
/// of the first tracing follow it there.
|
||
#[test]
|
||
fn trace_undo_of_the_second_retrace_reaches_the_first() {
|
||
let base = folder("chain");
|
||
let (mut s, _) = session(&base, false);
|
||
let out = log(
|
||
&mut s,
|
||
&base,
|
||
"var p = app.activeDocument.rasterItems[0].trace(), o = p.tracing.tracingOptions;\
|
||
o.threshold = 90; o.threshold = 60; vc.log(o.threshold); vc.run('edit.undo');\
|
||
vc.log(o.threshold); vc.log(p.isTracing); vc.log(p.tracing.pathCount > 0);",
|
||
);
|
||
assert_eq!(out, [json!(60), json!(90), json!(true), json!(true)]);
|
||
let groups = traces(&s);
|
||
assert_eq!(groups.len(), 1);
|
||
assert_eq!(trace_of(&s, groups[0])["params"]["threshold"], json!(90));
|
||
let _ = std::fs::remove_dir_all(base);
|
||
}
|
||
|
||
#[test]
|
||
fn trace_deleted_plugin_is_stale() {
|
||
let base = folder("deleted");
|
||
let (mut s, _) = session(&base, false);
|
||
let out = log(
|
||
&mut s,
|
||
&base,
|
||
"var p = app.activeDocument.rasterItems[0].trace(), t = p.tracing, o = t.tracingOptions, m = []; p.remove();\
|
||
try { p.name; } catch (e) { m.push(e.message); } try { t.sourceArt; } catch (e) { m.push(e.message); }\
|
||
try { o.threshold = 10; } catch (e) { m.push(e.message); } try { t.releaseTracing(); } catch (e) { m.push(e.message); }\
|
||
try { o.pathFitting; } catch (e) { m.push(e.message); } try { o.cornerAngle = 1; } catch (e) { m.push(e.message); } vc.log(m);",
|
||
);
|
||
assert_eq!(out, [json!(vec!["Stale page item"; 6])]);
|
||
assert!(traces(&s).is_empty());
|
||
let _ = std::fs::remove_dir_all(base);
|
||
}
|
||
|
||
/// A script's trace of an image past the tracer's source limit (`vectorcraft_trace::MAX_SOURCE_PIXELS`,
|
||
/// 192 megapixels) is refused from the image's header before its pixels are decoded, and the run
|
||
/// leaves the document as it was.
|
||
#[test]
|
||
fn trace_large_image_is_bounded() {
|
||
let base = folder("large");
|
||
let png = base.join("main/wall.png");
|
||
std::fs::write(&png, super::linkspanel::png_header(30_000, 30_000)).unwrap();
|
||
let mut s = Session::new();
|
||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||
let r = s.execute("file.place", &json!({"path": png.to_string_lossy(), "link": false})).unwrap();
|
||
let image = NodeId(r["ids"][0].as_u64().unwrap());
|
||
let steps = undo_steps(&s);
|
||
let out = log(&mut s, &base, "var m = ''; try { app.activeDocument.rasterItems[0].trace(); } catch (e) { m = e.message; } vc.log(m);");
|
||
let m = out[0].as_str().unwrap_or_default();
|
||
assert!(m.contains("30000 × 30000 pixels") && m.contains("(192 megapixels)"), "{m}");
|
||
assert!(traces(&s).is_empty());
|
||
assert_eq!(top(&s), [image]);
|
||
assert_eq!(undo_steps(&s), steps);
|
||
let _ = std::fs::remove_dir_all(base);
|
||
}
|
||
|
||
#[test]
|
||
fn trace_remove_all_takes_the_tracing() {
|
||
let base = folder("remove-all");
|
||
let (mut s, _) = session(&base, false);
|
||
let out = log(&mut s, &base, "var d = app.activeDocument; d.rasterItems[0].trace(); d.pageItems.removeAll(); vc.log(d.pageItems.length);");
|
||
assert_eq!(out, [json!(0)]);
|
||
assert!(traces(&s).is_empty());
|
||
assert!(top(&s).is_empty());
|
||
let _ = std::fs::remove_dir_all(base);
|
||
}
|
||
|
||
#[test]
|
||
fn trace_stop_rolls_back_long_work() {
|
||
let base = folder("stop");
|
||
let (mut s, image) = session(&base, false);
|
||
let before = top(&s);
|
||
s.script_in_run = true;
|
||
let stop = s.script_interrupt();
|
||
stop.set();
|
||
let r = s.execute("imageTrace.make", &json!({"id": image.0}));
|
||
stop.clear();
|
||
s.script_in_run = false;
|
||
assert!(matches!(r, Err(EngineError::Cancelled)), "{r:?}");
|
||
assert_eq!(top(&s), before);
|
||
assert!(traces(&s).is_empty());
|
||
let _ = std::fs::remove_dir_all(base);
|
||
}
|
||
|
||
#[test]
|
||
fn trace_stop_rolls_back_a_handed_in_trace() {
|
||
let base = folder("stop-hand-off");
|
||
let (mut s, image) = session(&base, false);
|
||
let before = top(&s);
|
||
let p = json!({"id": image.0});
|
||
let run = cmd::TraceRun::prepare(&s, "imageTrace.make", &p).unwrap();
|
||
run.run(&|_, _| true).unwrap().hand_in(&mut s);
|
||
s.script_in_run = true;
|
||
let stop = s.script_interrupt();
|
||
stop.set();
|
||
let r = s.execute("imageTrace.make", &p);
|
||
stop.clear();
|
||
s.script_in_run = false;
|
||
assert!(matches!(r, Err(EngineError::Cancelled)), "{r:?}");
|
||
assert_eq!(top(&s), before);
|
||
assert!(traces(&s).is_empty());
|
||
let _ = std::fs::remove_dir_all(base);
|
||
}
|
||
|
||
#[test]
|
||
fn image_trace_refuses_the_source_image_of_a_trace() {
|
||
let base = folder("source");
|
||
let (mut s, image) = session(&base, false);
|
||
let group = NodeId(s.execute("imageTrace.make", &json!({"id": image.0})).unwrap()["id"].as_u64().unwrap());
|
||
let e = s.execute("imageTrace.make", &json!({"id": image.0})).unwrap_err().to_string();
|
||
assert!(e.contains("source image of an Image Trace object"), "{e}");
|
||
assert_eq!(traces(&s), [group]);
|
||
assert_eq!(s.active().unwrap().doc.parent_of(image), Some(group));
|
||
|
||
// With another image named after the source image, that other image is traced.
|
||
let png = base.join("main/disc.png");
|
||
let other = s.execute("file.place", &json!({"path": png.to_string_lossy(), "link": false})).unwrap();
|
||
let other = NodeId(other["ids"][0].as_u64().unwrap());
|
||
let r = s.execute("imageTrace.make", &json!({"ids": [image.0, other.0]})).unwrap();
|
||
let second = NodeId(r["id"].as_u64().unwrap());
|
||
let d = &s.active().unwrap().doc;
|
||
assert_eq!(d.parent_of(other), Some(second));
|
||
assert_eq!(d.parent_of(image), Some(group));
|
||
assert_eq!(traces(&s).len(), 2);
|
||
let _ = std::fs::remove_dir_all(base);
|
||
}
|
||
|
||
#[test]
|
||
fn trace_of_another_image_inside_a_tracing() {
|
||
let base = folder("inside");
|
||
let (mut s, image) = session(&base, false);
|
||
let png = base.join("main/disc.png");
|
||
let other = s.execute("file.place", &json!({"path": png.to_string_lossy(), "link": false})).unwrap();
|
||
let other = NodeId(other["ids"][0].as_u64().unwrap());
|
||
let out = log(
|
||
&mut s,
|
||
&base,
|
||
"var d = app.activeDocument, p = d.rasterItems[1].trace(), r = d.rasterItems[0]; r.move(p, ElementPlacement.PLACEATBEGINNING);\
|
||
var q = r.trace(); vc.log(q.typename); vc.log(q.tracing.sourceArt === r); vc.log(p.tracing.pathCount > 0);\
|
||
vc.log(p.tracing.pathCount === 2 * q.tracing.pathCount); vc.log(p.tracing.anchorCount === 2 * q.tracing.anchorCount);",
|
||
);
|
||
// The two traces are of the same image with the same settings: the outer counts take in the
|
||
// inner trace's paths without its seam fills.
|
||
assert_eq!(out, [json!("PluginItem"), json!(true), json!(true), json!(true), json!(true)]);
|
||
let groups = traces(&s);
|
||
assert_eq!(groups.len(), 2);
|
||
let d = &s.active().unwrap().doc;
|
||
let (a, b) = (d.parent_of(image).unwrap(), d.parent_of(other).unwrap());
|
||
assert!(groups.contains(&a) && groups.contains(&b) && a != b, "each image is the source of its own tracing");
|
||
assert!(d.parent_of(a) == Some(b) || d.parent_of(b) == Some(a), "one tracing is inside the other");
|
||
let _ = std::fs::remove_dir_all(base);
|
||
}
|
||
|
||
/// An object moved or duplicated to the end of a tracing goes directly above its source image,
|
||
/// which stays the tracing's first child.
|
||
#[test]
|
||
fn an_object_placed_at_the_end_of_a_tracing_stays_above_its_source() {
|
||
let base = folder("at-end");
|
||
let (mut s, _) = session(&base, false);
|
||
let png = base.join("main/disc.png");
|
||
s.execute("file.place", &json!({"path": png.to_string_lossy(), "link": false})).unwrap();
|
||
let out = log(
|
||
&mut s,
|
||
&base,
|
||
"var d = app.activeDocument, a = d.rasterItems[1]; a.name = 'src'; var p = a.trace(), r = d.rasterItems[0]; r.name = 'moved';\
|
||
r.duplicate(p, ElementPlacement.PLACEATEND); r.move(p, ElementPlacement.PLACEATEND);\
|
||
var s = p.tracing.sourceArt; s.hidden = false; s.move(p, ElementPlacement.PLACEATEND);\
|
||
vc.log(p.tracing.sourceArt.name); vc.log(d.rasterItems.length); vc.log(p.isTracing);",
|
||
);
|
||
assert_eq!(out, [json!("src"), json!(2), json!(true)]);
|
||
let groups = traces(&s);
|
||
assert_eq!(groups.len(), 1);
|
||
let d = &s.active().unwrap().doc;
|
||
let names: Vec<Option<String>> = d.children(Some(groups[0])).unwrap().iter().map(|n| n.name.clone()).collect();
|
||
let name = |n: &str| Some(n.to_string());
|
||
assert_eq!(names[..3], [name("src"), name("moved"), name("moved")], "the source stays first: {names:?}");
|
||
let _ = std::fs::remove_dir_all(base);
|
||
}
|
||
|
||
/// The source image stays a tracing's first child when it goes to the front of the tracing, and
|
||
/// when another object in the tracing is sent to the back or the source is brought to the front.
|
||
#[test]
|
||
fn reordering_inside_a_tracing_keeps_the_source_first() {
|
||
let base = folder("reorder");
|
||
let (mut s, _) = session(&base, false);
|
||
let png = base.join("main/disc.png");
|
||
s.execute("file.place", &json!({"path": png.to_string_lossy(), "link": false})).unwrap();
|
||
let out = log(
|
||
&mut s,
|
||
&base,
|
||
"var d = app.activeDocument, a = d.rasterItems[1]; a.name = 'src'; var p = a.trace(), r = d.rasterItems[0]; r.name = 'moved';\
|
||
r.move(p, ElementPlacement.PLACEATBEGINNING);\
|
||
var s = p.tracing.sourceArt; s.hidden = false; s.move(p, ElementPlacement.PLACEATBEGINNING); vc.log(p.isTracing);\
|
||
r.zOrder(ZOrderMethod.SENDTOBACK); vc.log(p.isTracing); r.zOrder(ZOrderMethod.SENDBACKWARD); vc.log(p.isTracing);\
|
||
s.zOrder(ZOrderMethod.BRINGTOFRONT); s.zOrder(ZOrderMethod.BRINGFORWARD); vc.log(p.isTracing); vc.log(p.tracing.sourceArt.name);",
|
||
);
|
||
assert_eq!(out, [json!(true), json!(true), json!(true), json!(true), json!("src")]);
|
||
let groups = traces(&s);
|
||
assert_eq!(groups.len(), 1);
|
||
let d = &s.active().unwrap().doc;
|
||
let names: Vec<Option<String>> = d.children(Some(groups[0])).unwrap().iter().map(|n| n.name.clone()).collect();
|
||
assert_eq!(names[..2], [Some("src".to_string()), Some("moved".to_string())], "the source stays first: {names:?}");
|
||
let _ = std::fs::remove_dir_all(base);
|
||
}
|
||
|
||
/// A tracing's source image cannot be moved out of its tracing, and the refused move leaves the
|
||
/// document as it was.
|
||
#[test]
|
||
fn the_source_image_cannot_leave_its_tracing() {
|
||
let base = folder("source-leaves");
|
||
let (mut s, _) = session(&base, false);
|
||
log(&mut s, &base, "app.activeDocument.rasterItems[0].trace().tracing.sourceArt.hidden = false;");
|
||
let saved = vectorcraft_format::save(&s.active().unwrap().doc, false);
|
||
let steps = undo_steps(&s);
|
||
let out = log(
|
||
&mut s,
|
||
&base,
|
||
"var d = app.activeDocument, p = d.pageItems[0], m = 'none';\
|
||
try { p.tracing.sourceArt.move(p, ElementPlacement.PLACEBEFORE); } catch (e) { m = e.message; }\
|
||
vc.log(m); vc.log(p.isTracing);",
|
||
);
|
||
assert_eq!(out, [json!("a tracing's source image cannot leave its tracing"), json!(true)]);
|
||
assert_eq!(vectorcraft_format::save(&s.active().unwrap().doc, false), saved);
|
||
assert_eq!(undo_steps(&s), steps);
|
||
let _ = std::fs::remove_dir_all(base);
|
||
}
|
||
|
||
#[test]
|
||
fn trace_source_art_is_not_listed_with_the_images() {
|
||
let base = folder("lists");
|
||
let (mut s, _) = session(&base, false);
|
||
let png = base.join("main/disc.png");
|
||
s.execute("file.place", &json!({"path": png.to_string_lossy(), "link": false})).unwrap();
|
||
let out = log(
|
||
&mut s,
|
||
&base,
|
||
"var d = app.activeDocument; d.rasterItems[0].trace(); var n = d.rasterItems.length, k = 0;\
|
||
for (var i = 0; i < d.pageItems.length; i++) { if (d.pageItems[i].typename === 'RasterItem') k++; }\
|
||
d.rasterItems.removeAll(); vc.log(n); vc.log(k); vc.log(d.rasterItems.length); vc.log(d.pageItems[0].typename);",
|
||
);
|
||
assert_eq!(out, [json!(1), json!(1), json!(0), json!("PluginItem")]);
|
||
assert_eq!(traces(&s).len(), 1, "removing the raster items leaves the tracing");
|
||
let _ = std::fs::remove_dir_all(base);
|
||
}
|
||
|
||
#[test]
|
||
fn trace_plugin_keeps_its_name() {
|
||
let base = folder("renamed");
|
||
let (mut s, _) = session(&base, false);
|
||
let out = log(
|
||
&mut s,
|
||
&base,
|
||
"var d = app.activeDocument, p = d.rasterItems[0].trace(), t = p.tracing, m = '', n = p.name; p.name = n;\
|
||
try { p.name = 'logo'; } catch (e) { m = e.message; } vc.log(m); vc.log(p.name === n); vc.log(p.typename); vc.log(t.pathCount > 0);",
|
||
);
|
||
assert_eq!(out, [json!("The name of a tracing cannot be changed"), json!(true), json!("PluginItem"), json!(true)]);
|
||
assert_eq!(traces(&s).len(), 1);
|
||
assert_eq!(undo_steps(&s), 2, "the place and the run");
|
||
let _ = std::fs::remove_dir_all(base);
|
||
}
|
||
|
||
#[test]
|
||
fn a_group_holding_an_image_cannot_take_the_tracing_name() {
|
||
let base = folder("rename-to-trace");
|
||
let (mut s, _) = session(&base, false);
|
||
let out = log(
|
||
&mut s,
|
||
&base,
|
||
"var d = app.activeDocument, m = ''; d.selection = [d.rasterItems[0]]; vc.run('object.group'); var g = d.pageItems[0];\
|
||
try { g.name = 'Image Trace'; } catch (e) { m = e.message; } vc.log(m); vc.log(g.typename); g.name = 'Logo'; vc.log(g.name);",
|
||
);
|
||
assert_eq!(out, [json!("Only Image Trace can make a tracing"), json!("GroupItem"), json!("Logo")]);
|
||
assert!(traces(&s).is_empty());
|
||
let _ = std::fs::remove_dir_all(base);
|
||
}
|
||
|
||
#[test]
|
||
fn an_image_cannot_move_first_into_a_group_named_as_a_tracing() {
|
||
let base = folder("move-into-trace-name");
|
||
let (mut s, _) = session(&base, false);
|
||
let before = undo_steps(&s);
|
||
let out = log(
|
||
&mut s,
|
||
&base,
|
||
"var d = app.activeDocument, r = d.rasterItems[0], m = [];\
|
||
d.selection = [d.pathItems.rectangle(10, 10, 20, 20)]; vc.run('object.group'); var g = d.pageItems[0];\
|
||
g.name = 'Image Trace';\
|
||
try { r.move(g, ElementPlacement.PLACEATEND); m.push('moved'); } catch (e) { m.push(e.message); }\
|
||
try { r.duplicate(g, ElementPlacement.PLACEATEND); m.push('copied'); } catch (e) { m.push(e.message); }\
|
||
vc.log(m); vc.log(d.rasterItems.length); vc.log(g.typename);\
|
||
r.move(g, ElementPlacement.PLACEATBEGINNING); vc.log(g.typename);",
|
||
);
|
||
let refused = json!("Only Image Trace can make a tracing");
|
||
assert_eq!(out, [json!([refused, refused]), json!(1), json!("GroupItem"), json!("GroupItem")]);
|
||
assert!(traces(&s).is_empty());
|
||
let d = &s.active().unwrap().doc;
|
||
let g = top(&s)[0];
|
||
let kids: Vec<bool> = d.children(Some(g)).unwrap().iter().map(|n| matches!(n.kind, crate::doc::NodeKind::Image(_))).collect();
|
||
assert_eq!(kids, [false, true], "the image went in above the rectangle");
|
||
assert_eq!(undo_steps(&s), before + 1, "the run is one step");
|
||
let _ = std::fs::remove_dir_all(base);
|
||
}
|
||
|
||
/// `move`, `remove()` and `zOrder` refuse to leave an image at the bottom of an ordinary group named
|
||
/// as a tracing, before the document changes, and allow the same moves when another object stays
|
||
/// at the bottom.
|
||
#[test]
|
||
fn an_image_cannot_be_left_first_in_a_group_named_as_a_tracing() {
|
||
let base = folder("leave-trace-name");
|
||
let (mut s, _) = session(&base, false);
|
||
log(
|
||
&mut s,
|
||
&base,
|
||
"var d = app.activeDocument; d.selection = [d.pathItems.rectangle(10, 10, 20, 20)]; vc.run('object.group');\
|
||
var g = d.pageItems[0]; g.name = 'Image Trace'; d.rasterItems[0].move(g, ElementPlacement.PLACEATBEGINNING);",
|
||
);
|
||
let before = vectorcraft_format::save(&s.active().unwrap().doc, false);
|
||
let steps = undo_steps(&s);
|
||
let out = log(
|
||
&mut s,
|
||
&base,
|
||
"var d = app.activeDocument, g = d.pageItems[0], r = d.rasterItems[0], p = d.pathItems[0], m = [];\
|
||
function t(f) { try { f(); m.push('done'); } catch (e) { m.push(e.message); } }\
|
||
t(function () { p.move(g, ElementPlacement.PLACEBEFORE); });\
|
||
t(function () { p.move(g, ElementPlacement.PLACEATBEGINNING); });\
|
||
t(function () { p.remove(); });\
|
||
t(function () { p.zOrder(ZOrderMethod.BRINGTOFRONT); });\
|
||
t(function () { p.zOrder(ZOrderMethod.BRINGFORWARD); });\
|
||
t(function () { r.zOrder(ZOrderMethod.SENDTOBACK); });\
|
||
t(function () { r.zOrder(ZOrderMethod.SENDBACKWARD); });\
|
||
vc.log(m); vc.log(g.typename);",
|
||
);
|
||
assert_eq!(out, [json!(vec!["Only Image Trace can make a tracing"; 7]), json!("GroupItem")]);
|
||
assert_eq!(vectorcraft_format::save(&s.active().unwrap().doc, false), before);
|
||
assert_eq!(undo_steps(&s), steps);
|
||
let out = log(
|
||
&mut s,
|
||
&base,
|
||
"var d = app.activeDocument, g = d.pageItems[0], p = d.pathItems[0];\
|
||
d.pathItems.rectangle(40, 40, 5, 5).move(g, ElementPlacement.PLACEATEND);\
|
||
p.move(g, ElementPlacement.PLACEBEFORE); vc.log(g.typename);",
|
||
);
|
||
assert_eq!(out, [json!("GroupItem")]);
|
||
assert!(traces(&s).is_empty());
|
||
let d = &s.active().unwrap().doc;
|
||
let g = top(&s).into_iter().find(|i| d.node(*i).is_some_and(|n| n.name.as_deref() == Some(crate::cmd::TRACE_NAME))).unwrap();
|
||
assert_eq!(d.children(Some(g)).unwrap().len(), 2, "the rectangle left the group");
|
||
let _ = std::fs::remove_dir_all(base);
|
||
}
|
||
|
||
/// Deleting the clipping path of a clip group named as a tracing releases its mask, so `remove()` and
|
||
/// `textFrames.removeAll()` refuse it when an image would be left first in the released group.
|
||
#[test]
|
||
fn removing_a_clipping_path_cannot_leave_an_image_first_in_a_group_named_as_a_tracing() {
|
||
let base = folder("release-trace-name");
|
||
let (mut s, _) = session(&base, false);
|
||
log(
|
||
&mut s,
|
||
&base,
|
||
"var d = app.activeDocument; d.selection = [d.rasterItems[0], d.pathItems.rectangle(10, 10, 20, 20)];\
|
||
vc.run('object.clippingMask.make'); d.pageItems[0].name = 'Image Trace';",
|
||
);
|
||
let before = vectorcraft_format::save(&s.active().unwrap().doc, false);
|
||
let steps = undo_steps(&s);
|
||
let out = log(
|
||
&mut s,
|
||
&base,
|
||
"var d = app.activeDocument, g = d.pageItems[0], m = '';\
|
||
try { d.pathItems[0].remove(); m = 'done'; } catch (e) { m = e.message; } vc.log(m); vc.log(g.clipped);",
|
||
);
|
||
assert_eq!(out, [json!("Only Image Trace can make a tracing"), json!(true)]);
|
||
assert_eq!(vectorcraft_format::save(&s.active().unwrap().doc, false), before);
|
||
assert_eq!(undo_steps(&s), steps);
|
||
let (mut s, _) = session(&base, false);
|
||
log(
|
||
&mut s,
|
||
&base,
|
||
"var d = app.activeDocument, t = d.textFrames.add(); t.contents = 'Clip';\
|
||
d.selection = [d.rasterItems[0], t]; vc.run('object.clippingMask.make'); d.pageItems[0].name = 'Image Trace';",
|
||
);
|
||
let before = vectorcraft_format::save(&s.active().unwrap().doc, false);
|
||
let steps = undo_steps(&s);
|
||
let out = log(
|
||
&mut s,
|
||
&base,
|
||
"var d = app.activeDocument, g = d.pageItems[0], m = '';\
|
||
try { g.textFrames.removeAll(); m = 'done'; } catch (e) { m = e.message; } vc.log(m); vc.log(g.textFrames.length);",
|
||
);
|
||
assert_eq!(out, [json!("Only Image Trace can make a tracing"), json!(1)]);
|
||
assert_eq!(vectorcraft_format::save(&s.active().unwrap().doc, false), before);
|
||
assert_eq!(undo_steps(&s), steps);
|
||
assert!(traces(&s).is_empty());
|
||
let _ = std::fs::remove_dir_all(base);
|
||
}
|
||
|
||
/// `textFrames.removeAll()` and `groupItems.removeAll()` on an ordinary group named as a tracing
|
||
/// refuse to leave an image first in it, before the document changes, and delete when another
|
||
/// object stays first.
|
||
#[test]
|
||
fn remove_all_cannot_leave_an_image_first_in_a_group_named_as_a_tracing() {
|
||
let base = folder("remove-all-trace-name");
|
||
let refused = json!("Only Image Trace can make a tracing");
|
||
for (under, call) in [
|
||
("var u = d.textFrames.add(); u.contents = 'Under';", "g.textFrames.removeAll();"),
|
||
("d.selection = [d.pathItems.rectangle(50, 50, 5, 5)]; vc.run('object.group'); var u = d.pageItems[0];", "g.groupItems.removeAll();"),
|
||
] {
|
||
let (mut s, _) = session(&base, false);
|
||
// The group holds the type or group at the bottom and the image above it.
|
||
log(
|
||
&mut s,
|
||
&base,
|
||
&format!(
|
||
"var d = app.activeDocument; var p = d.pathItems.rectangle(10, 10, 20, 20); d.selection = [p]; vc.run('object.group');\
|
||
var g = d.pageItems[0]; g.name = 'Image Trace'; {under} u.move(g, ElementPlacement.PLACEATEND);\
|
||
d.rasterItems[0].move(g, ElementPlacement.PLACEATBEGINNING); p.remove();"
|
||
),
|
||
);
|
||
let before = vectorcraft_format::save(&s.active().unwrap().doc, false);
|
||
let steps = undo_steps(&s);
|
||
let out = log(
|
||
&mut s,
|
||
&base,
|
||
&format!(
|
||
"var d = app.activeDocument, g = d.pageItems[0], m = ''; try {{ {call} m = 'done'; }} catch (e) {{ m = e.message; }} vc.log(m); vc.log(g.typename);"
|
||
),
|
||
);
|
||
assert_eq!(out, [refused.clone(), json!("GroupItem")], "{call}");
|
||
assert_eq!(vectorcraft_format::save(&s.active().unwrap().doc, false), before, "{call}");
|
||
assert_eq!(undo_steps(&s), steps, "{call}");
|
||
assert!(traces(&s).is_empty());
|
||
}
|
||
// With a rectangle left first, the type goes and the group stays an ordinary group.
|
||
let (mut s, _) = session(&base, false);
|
||
let out = log(
|
||
&mut s,
|
||
&base,
|
||
"var d = app.activeDocument; d.selection = [d.pathItems.rectangle(10, 10, 20, 20)]; vc.run('object.group');\
|
||
var g = d.pageItems[0]; g.name = 'Image Trace'; var t = d.textFrames.add(); t.contents = 'Over';\
|
||
t.move(g, ElementPlacement.PLACEATBEGINNING); d.rasterItems[0].move(g, ElementPlacement.PLACEATBEGINNING);\
|
||
g.textFrames.removeAll(); vc.log(g.textFrames.length); vc.log(g.pageItems.length); vc.log(g.typename);",
|
||
);
|
||
assert_eq!(out, [json!(0), json!(2), json!("GroupItem")]);
|
||
assert!(traces(&s).is_empty());
|
||
let _ = std::fs::remove_dir_all(base);
|
||
}
|
||
|
||
/// `releaseTracing()` keeps only the source image, so it refuses a tracing that holds an object
|
||
/// its trace did not make, before the document changes.
|
||
#[test]
|
||
fn release_refuses_added_artwork_before_changing_the_document() {
|
||
let base = folder("release-added-artwork");
|
||
let (mut s, _) = session(&base, false);
|
||
log(
|
||
&mut s,
|
||
&base,
|
||
"var d = app.activeDocument, p = d.rasterItems[0].trace(); d.pathItems.rectangle(20, 20, 10, 10).move(p, ElementPlacement.PLACEATEND);",
|
||
);
|
||
let before = vectorcraft_format::save(&s.active().unwrap().doc, false);
|
||
let steps = undo_steps(&s);
|
||
let out = log(
|
||
&mut s,
|
||
&base,
|
||
"var items = app.activeDocument.pageItems, p, m = '';\
|
||
for (var i = 0; i < items.length; i++) if (items[i].typename === 'PluginItem') p = items[i];\
|
||
try { p.tracing.releaseTracing(); } catch (e) { m = e.message; } vc.log(m);",
|
||
);
|
||
assert_eq!(out, [json!("Cannot release a tracing containing added artwork")]);
|
||
assert_eq!(vectorcraft_format::save(&s.active().unwrap().doc, false), before);
|
||
assert_eq!(undo_steps(&s), steps);
|
||
assert_eq!(traces(&s).len(), 1);
|
||
let _ = std::fs::remove_dir_all(base);
|
||
}
|
||
|
||
/// Retracing and releasing discard the objects the trace made, so both refuse a tracing that holds
|
||
/// a locked one, before the document changes.
|
||
#[test]
|
||
fn retrace_and_release_refuse_locked_traced_artwork() {
|
||
let base = folder("locked-traced-artwork");
|
||
for action in ["p.tracing.tracingOptions.threshold = 90;", "p.tracing.releaseTracing();"] {
|
||
let (mut s, image) = session(&base, false);
|
||
let r = s.execute("imageTrace.make", &json!({"id": image.0})).unwrap();
|
||
let group = NodeId(r["id"].as_u64().unwrap());
|
||
let made = s.active().unwrap().doc.node(group).unwrap().children().unwrap()[1].id;
|
||
s.edit("Lock traced artwork", |d, _| {
|
||
d.node_mut(made).unwrap().locked = true;
|
||
Ok(())
|
||
})
|
||
.unwrap();
|
||
let before = vectorcraft_format::save(&s.active().unwrap().doc, false);
|
||
let steps = undo_steps(&s);
|
||
let out = log(
|
||
&mut s,
|
||
&base,
|
||
&format!("var p = app.activeDocument.pageItems[0], m = ''; try {{ {action} }} catch (e) {{ m = e.message; }} vc.log(m);"),
|
||
);
|
||
assert_eq!(out, [json!(format!("Cannot edit page item {}", made.0))], "{action}");
|
||
assert_eq!(vectorcraft_format::save(&s.active().unwrap().doc, false), before, "{action}");
|
||
assert_eq!(undo_steps(&s), steps, "{action}");
|
||
}
|
||
let _ = std::fs::remove_dir_all(base);
|
||
}
|
||
|
||
/// The `TracingOptions` and `TracingObject` members that are not implemented are left out of
|
||
/// `hasOwnProperty` and `reflect`, and still throw when read.
|
||
#[test]
|
||
fn unimplemented_tracing_members_are_not_reported() {
|
||
let base = folder("unimplemented-members");
|
||
let (mut s, _) = session(&base, false);
|
||
let out = log(
|
||
&mut s,
|
||
&base,
|
||
"var p = app.activeDocument.rasterItems[0].trace(), t = p.tracing, o = t.tracingOptions, m = '';\
|
||
vc.log([o.hasOwnProperty('pathFitting'), t.hasOwnProperty('areaCount'), t.hasOwnProperty('pathCount')]);\
|
||
vc.log([o.reflect.find('pathFitting') === null, t.reflect.find('areaCount') === null, t.reflect.find('pathCount') === null]);\
|
||
try { t.areaCount; } catch (e) { m = e.message; } vc.log(m);",
|
||
);
|
||
assert_eq!(out, [json!([false, false, true]), json!([true, true, false]), json!("TracingObject.areaCount is not implemented")]);
|
||
let _ = std::fs::remove_dir_all(base);
|
||
}
|
||
|
||
#[test]
|
||
fn new_group_at_the_bottom_of_a_tracing_is_refused() {
|
||
let base = folder("new-group-bottom");
|
||
let (mut s, id) = session(&base, false);
|
||
let tid = NodeId(s.execute("imageTrace.make", &json!({"id": id.0})).unwrap()["id"].as_u64().unwrap());
|
||
let steps = undo_steps(&s);
|
||
let e = s.execute("object.newGroup", &json!({"parent": tid.0, "index": 0})).unwrap_err().to_string();
|
||
assert!(e.contains("source image"), "{e}");
|
||
assert_eq!(traces(&s), [tid]);
|
||
assert_eq!(undo_steps(&s), steps);
|
||
let g = NodeId(s.execute("object.newGroup", &json!({"parent": tid.0, "index": 1})).unwrap()["id"].as_u64().unwrap());
|
||
assert_eq!(traces(&s), [tid]);
|
||
assert_eq!(s.active().unwrap().doc.children(Some(tid)).unwrap()[1].id, g);
|
||
let _ = std::fs::remove_dir_all(base);
|
||
}
|
||
|
||
#[test]
|
||
fn retrace_keeps_the_tracing_opacity_and_blend_mode() {
|
||
let base = folder("retrace-appearance");
|
||
let (mut s, _) = session(&base, false);
|
||
let out = log(
|
||
&mut s,
|
||
&base,
|
||
"var p = app.activeDocument.rasterItems[0].trace(); p.opacity = 50; p.blendingMode = BlendModes.MULTIPLY;\
|
||
p.tracing.tracingOptions.threshold = 90; vc.log(p.opacity); vc.log(p.blendingMode === BlendModes.MULTIPLY);\
|
||
p.tracing.tracingOptions.threshold = 100; vc.log(p.opacity); vc.log(p.blendingMode === BlendModes.MULTIPLY);",
|
||
);
|
||
assert_eq!(out, [json!(50), json!(true), json!(50), json!(true)]);
|
||
let id = traces(&s)[0];
|
||
assert_eq!(s.active().unwrap().doc.node(id).unwrap().opacity, 0.5);
|
||
let _ = std::fs::remove_dir_all(base);
|
||
}
|
||
|
||
#[test]
|
||
fn retraced_plugin_is_the_same_object_as_its_collection_handle() {
|
||
let base = folder("retrace-identity");
|
||
let (mut s, _) = session(&base, false);
|
||
let out = log(
|
||
&mut s,
|
||
&base,
|
||
"var d = app.activeDocument, p = d.rasterItems[0].trace(); vc.log(d.pageItems[0] === p);\
|
||
p.tracing.tracingOptions.threshold = 90; vc.log(d.pageItems[0] === p); vc.log(app.selection[0] === p);\
|
||
p.tracing.tracingOptions.threshold = 100; vc.log(d.pageItems[0] === p); vc.log(p.tracing.parent === d.pageItems[0]);",
|
||
);
|
||
assert_eq!(out, vec![json!(true); 5]);
|
||
let _ = std::fs::remove_dir_all(base);
|
||
}
|