mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-03 15:21:17 -05:00
Scripts: tracing keeps added images and direct selections; app.open logs warnings
- Expanding a tracing removes only its source image; other images a script moved or duplicated into the group stay. - A TracingObject goes stale when its original source image is gone, even when another image now sits first in the group. - Tracing, retracing, expanding and releasing restore the whole selection, anchors and segments included, with only the replaced object remapped. - app.open writes the open's warnings to the script console, as saveAs does. - embed() checks the image's link state after the command instead of a returned id rounded to a JavaScript number. - The placed-image tests pass ordinary drive paths to File on Windows.
This commit is contained in:
@@ -1400,7 +1400,8 @@ pub(super) fn trace_expand(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
n.name = None;
|
||||
n.extras_mut().trace = None;
|
||||
if let Some(ch) = n.children_mut() {
|
||||
ch.retain(|c| !matches!(c.kind, NodeKind::Image(_)));
|
||||
let source = ch.first().map(|c| c.id);
|
||||
ch.retain(|c| Some(c.id) != source);
|
||||
}
|
||||
if by_color {
|
||||
let items = d.node(*g).and_then(Node::children).cloned().unwrap_or_default();
|
||||
|
||||
@@ -159,14 +159,6 @@ fn field<'a>(d: &'a Data, k: &str) -> Option<&'a Data> {
|
||||
}
|
||||
}
|
||||
|
||||
fn id_value(d: Option<&Data>) -> Option<NodeId> {
|
||||
match d {
|
||||
Some(Data::Number(n)) => whole(*n).map(NodeId),
|
||||
Some(Data::Array(a)) => id_value(a.first()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
// ---- PlacedItems and RasterItems ----
|
||||
|
||||
fn collection(placed: bool) -> &'static str {
|
||||
@@ -422,11 +414,8 @@ fn placed_embed(h: &Host, a: &[Data]) -> Answer {
|
||||
if matches!(field(&info, "status"), Some(Data::String(s)) if s == "missing") {
|
||||
return Err(HostError::Error(MISSING_LINK.into()));
|
||||
}
|
||||
let r = edit_item(h, item, "links.embed", &json!({"ids": [item.id.0]}))?;
|
||||
let embedded = match field(&r, "embedded") {
|
||||
Some(Data::Array(ids)) => ids.iter().any(|d| id_value(Some(d)) == Some(item.id)),
|
||||
_ => false,
|
||||
};
|
||||
edit_item(h, item, "links.embed", &json!({"ids": [item.id.0]}))?;
|
||||
let embedded = with_doc(h, item.doc, |_, st| matches!(st.doc.node(item.id).map(|n| &n.kind), Some(NodeKind::Image(im)) if im.link.is_none()));
|
||||
if !embedded {
|
||||
return Err(HostError::Error(MISSING_LINK.into()));
|
||||
}
|
||||
|
||||
@@ -767,7 +767,10 @@ fn app_open(h: &Host, a: &[Data]) -> Answer {
|
||||
}
|
||||
let real = h.disk.borrow().open_target(path).map_err(|m| refused(m, path))?;
|
||||
p.insert("path".into(), json!(plain(real)));
|
||||
let r = exactly(h, || command(h, "document.open", &Value::Object(p)))?;
|
||||
let (r, value) = exactly(h, || command_value(h, "document.open", &Value::Object(p)))?;
|
||||
for w in value.get("warnings").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str) {
|
||||
super::super::each_line(&format!("open: {w}"), |line, cut| h.line(super::super::console::Entry::Log(line), cut));
|
||||
}
|
||||
let index = match &r {
|
||||
Data::Object(items) => items.iter().find_map(|(k, v)| match (k.as_str(), v) {
|
||||
("index", Data::Number(n)) => whole(*n).and_then(|i| usize::try_from(i).ok()),
|
||||
|
||||
@@ -115,6 +115,7 @@ const NOT_IMPLEMENTED: &[&str] = &[
|
||||
#[derive(Default)]
|
||||
pub(super) struct State {
|
||||
next: RefCell<HashMap<(u64, u64), u64>>,
|
||||
sources: RefCell<HashMap<(u64, u64), NodeId>>,
|
||||
}
|
||||
|
||||
/// `id` while the document `uid` holds it (a run never gives an id out twice, so an undo that put
|
||||
@@ -185,8 +186,11 @@ fn tracing_of(h: &Host, d: &Data, cls: &str) -> Result<(Item, [f64; 5]), HostErr
|
||||
};
|
||||
let &[run, uid, high, low, reverts] = handle.as_slice() else { return Err(HostError::Type(format!("this is not a {c}"))) };
|
||||
let (doc, id) = node_of(h, &handle).ok_or_else(stale)?;
|
||||
let source = h.dom.tracing.sources.borrow().get(&(doc.uid, id.0)).copied().ok_or_else(stale)?;
|
||||
let id = follow(h, doc.uid, id);
|
||||
let live = with_doc(h, doc, |_, st| st.doc.node(id).is_some_and(crate::cmd::is_trace_group));
|
||||
let live = with_doc(h, doc, |_, st| {
|
||||
st.doc.node(id).is_some_and(|g| crate::cmd::is_trace_group(g) && g.children().and_then(|c| c.first()).is_some_and(|n| n.id == source))
|
||||
});
|
||||
if !live {
|
||||
return Err(stale());
|
||||
}
|
||||
@@ -218,27 +222,24 @@ fn read_group<T>(h: &Host, item: Item, f: impl FnOnce(&crate::DocState, &Node) -
|
||||
/// Runs command `id` with `params` on `item`'s document → the object its result names under `key`.
|
||||
/// The selection stays as it was, with that object in place of `item`.
|
||||
fn replace(h: &Host, item: Item, id: &str, params: &Value, key: &str) -> Result<NodeId, HostError> {
|
||||
let before = with_doc(h, item.doc, |_, st| st.selection.objects.clone());
|
||||
let mut before = with_doc(h, item.doc, |_, st| st.selection.clone());
|
||||
on_doc(h, item.doc.uid, false, |h| {
|
||||
let (_, r) = command_value(h, id, params)?;
|
||||
let new = result_id(&r, key).ok_or_else(|| HostError::Error(format!("{id} gave no object")))?;
|
||||
let (want, now) = {
|
||||
let remap = |i: NodeId| if i == item.id { new } else { i };
|
||||
before.objects = before.objects.into_iter().map(remap).collect();
|
||||
let mut seen = HashSet::new();
|
||||
before.objects.retain(|i| seen.insert(*i));
|
||||
before.key = before.key.map(remap);
|
||||
before.target = before.target.map(remap);
|
||||
before.on_path_member = before.on_path_member.map(remap);
|
||||
let restore = {
|
||||
let s = h.session.borrow();
|
||||
let st = s.documents().iter().find(|d| d.uid == item.doc.uid).ok_or_else(|| HostError::Error(super::STALE_DOCUMENT.into()))?;
|
||||
let mut want: Vec<NodeId> = Vec::new();
|
||||
for i in before.iter().map(|i| if *i == item.id { new } else { *i }) {
|
||||
if st.doc.node(i).is_some() && !want.contains(&i) {
|
||||
want.push(i);
|
||||
}
|
||||
}
|
||||
(want, st.selection.objects.clone())
|
||||
(st.selection != before).then(|| st.doc.clone())
|
||||
};
|
||||
if now != want {
|
||||
if want.is_empty() {
|
||||
command(h, "select.none", &json!({}))?;
|
||||
} else {
|
||||
command(h, "select.set", &json!({"ids": want.iter().map(|i| i.0).collect::<Vec<_>>()}))?;
|
||||
}
|
||||
if let Some(doc) = restore {
|
||||
super::restore_selection(h, &doc, &before)?;
|
||||
}
|
||||
Ok(new)
|
||||
})
|
||||
@@ -299,7 +300,10 @@ fn plugin_is_tracing(h: &Host, a: &[Data]) -> Answer {
|
||||
}
|
||||
|
||||
fn plugin_tracing(h: &Host, a: &[Data]) -> Answer {
|
||||
let (_, handle) = plugin_of(h, a)?;
|
||||
let (item, handle) = plugin_of(h, a)?;
|
||||
let source = read_group(h, item, |_, g| g.children().and_then(|c| c.first()).map(|n| n.id).ok_or_else(stale))?;
|
||||
let (_, original) = node_of(h, &handle).ok_or_else(stale)?;
|
||||
h.dom.tracing.sources.borrow_mut().entry((item.doc.uid, original.0)).or_insert(source);
|
||||
Ok(host_ref("TracingObject", &handle))
|
||||
}
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@ fn folder(name: &str) -> PathBuf {
|
||||
let _ = std::fs::remove_dir_all(&base);
|
||||
std::fs::create_dir_all(base.join("main")).unwrap();
|
||||
std::fs::create_dir_all(base.join("outside")).unwrap();
|
||||
std::fs::canonicalize(&base).unwrap()
|
||||
PathBuf::from(plain_path(&std::fs::canonicalize(&base).unwrap().to_string_lossy()))
|
||||
}
|
||||
|
||||
/// A `w`×`h` 8-bit gray PNG.
|
||||
@@ -25,7 +25,21 @@ fn gray_png(w: u32, h: u32) -> Vec<u8> {
|
||||
}
|
||||
|
||||
fn js_path(p: &Path) -> String {
|
||||
p.to_string_lossy().replace('\\', "\\\\").replace('\'', "\\'")
|
||||
plain_path(&p.to_string_lossy()).replace('\\', "\\\\").replace('\'', "\\'")
|
||||
}
|
||||
|
||||
fn plain_path(path: &str) -> String {
|
||||
if let Some(tail) = path.strip_prefix(r"\\?\UNC\") { format!(r"\\{tail}") } else { path.strip_prefix(r"\\?\").unwrap_or(path).to_string() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fixture_paths_strip_verbatim_prefixes_on_every_platform() {
|
||||
let drive = format!("{}{}", r"\\?\", r"C:\x\a.png");
|
||||
let unc = format!("{}{}", r"\\?\UNC\", r"server\share\a.png");
|
||||
assert_eq!(plain_path(&drive), r"C:\x\a.png");
|
||||
assert_eq!(plain_path(&unc), r"\\server\share\a.png");
|
||||
assert_eq!(js_path(Path::new(&drive)), r"C:\\x\\a.png");
|
||||
assert_eq!(plain_path("/tmp/a.png"), "/tmp/a.png");
|
||||
}
|
||||
|
||||
/// A session with one 400 × 300 pt document.
|
||||
@@ -334,6 +348,23 @@ fn missing_link_embed_reports_error() {
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn embed_keeps_an_exact_image_id_above_javascript_integer_precision() {
|
||||
let base = folder("embed-big-id");
|
||||
let png = base.join("main/a.png");
|
||||
std::fs::write(&png, gray_png(4, 4)).unwrap();
|
||||
let mut s = session();
|
||||
let big = (1u64 << 53) + 1;
|
||||
s.active_mut().unwrap().change_unsaved(|d| std::sync::Arc::make_mut(d).raise_next_id(big));
|
||||
let id = place(&mut s, &png, true);
|
||||
assert_eq!(id, NodeId(big));
|
||||
let out =
|
||||
log(&mut s, &base, "var d = app.activeDocument; d.placedItems[0].embed(); vc.log(d.placedItems.length); vc.log(d.rasterItems[0].embedded);");
|
||||
assert_eq!(out, [json!(0), json!(true)]);
|
||||
assert_eq!(images(&s), vec![(id, None)]);
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn raster_metadata_uses_encoded_header_not_rgb_fallback() {
|
||||
let base = folder("meta");
|
||||
|
||||
@@ -222,6 +222,87 @@ fn trace_expand_returns_group_and_stales_plugin() {
|
||||
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_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); }} vc.log(m);",
|
||||
source.0
|
||||
),
|
||||
);
|
||||
assert_eq!(out, [json!(vec!["Stale page item"; 3])]);
|
||||
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");
|
||||
|
||||
@@ -112,6 +112,26 @@ fn save_as_logs_the_saves_warnings() {
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn open_logs_warnings_for_an_unreadable_linked_image() {
|
||||
let base = folder("open-warnings");
|
||||
let mut s = session(&base);
|
||||
let dir = data_folder(&mut s, &base);
|
||||
let svg = dir.join("missing-image.svg");
|
||||
std::fs::write(
|
||||
&svg,
|
||||
"<svg xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' width='50' height='50'>\
|
||||
<image width='10' height='10' xlink:href='missing.png'/></svg>",
|
||||
)
|
||||
.unwrap();
|
||||
let text = format!("Folder.userData; var d = app.open(new File({})); vc.log(d.typename);", quoted(&svg));
|
||||
let r = run(&mut s, &base, &text).unwrap();
|
||||
assert_eq!(r["log"], json!(["Document"]));
|
||||
let lines = r["console"]["lines"].as_array().unwrap();
|
||||
assert!(lines.iter().filter_map(Value::as_str).any(|l| l.starts_with("open: ") && l.contains("missing.png")), "{lines:?}");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// Without options, a save or export writes what an untouched new options object of its class gives.
|
||||
#[test]
|
||||
fn omitted_options_are_a_new_options_objects_defaults() {
|
||||
|
||||
Reference in New Issue
Block a user