diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 7964fee085..6ba1934af1 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -581,10 +581,11 @@ fn item_of(h: &Host, d: &Data) -> std::result::Result { } _ => return Err(HostError::Type("this is not a page item".into())), }; + let original = id; let id = if class == "PluginItem" { tracing::follow(h, doc.uid, id) } else { id }; let s = h.session.borrow(); let st = &s.documents()[doc.index]; - if st.doc.node(id).is_none_or(|n| typename(n) != Some(class)) { + if st.doc.node(id).is_none_or(|n| typename(n) != Some(class) || (class == "PluginItem" && !tracing::same_source(h, doc.uid, original, n))) { return Err(HostError::Error(STALE_ITEM.into())); } Ok(Item { doc, id }) @@ -619,6 +620,11 @@ fn doc_ref(h: &Host, uid: u64) -> Data { fn item_ref(h: &Host, st: &DocState, id: NodeId) -> Data { match st.doc.node(id) { Some(n) => match typename(n) { + Some("PlacedItem") => images::bound_ref(h, st, id).unwrap_or_else(|| host_ref("PlacedItem", &node_handle(h, st, id))), + Some("PluginItem") => { + tracing::remember_source(h, st.uid, n); + host_ref("PluginItem", &node_handle(h, st, id)) + } Some(t) => host_ref(t, &node_handle(h, st, id)), None => host_ref("Layer", &node_handle(h, st, id)), }, diff --git a/crates/engine/src/script/dom/images.rs b/crates/engine/src/script/dom/images.rs index d32a183ebc..d3d8c997b4 100644 --- a/crates/engine/src/script/dom/images.rs +++ b/crates/engine/src/script/dom/images.rs @@ -94,6 +94,12 @@ struct Pending { bound: Option, } +pub(super) fn bound_ref(h: &Host, st: &DocState, id: NodeId) -> Option { + let pending = h.dom.images.pending.borrow(); + let slot = pending.iter().position(|p| p.uid == st.uid && p.reverts == st.reverts && p.bound == Some(id))?; + Some(host_ref("PlacedItem", &[float(h.run), float(st.uid), 0.0, 0.0, float(st.reverts), float(slot as u64)])) +} + /// The slot of a `PlacedItems.add()` result in this run, from its handle. A result whose document /// was closed or reverted since is stale. fn slot_of(h: &Host, run: f64, uid: f64, slot: f64) -> Result { diff --git a/crates/engine/src/script/dom/save_open.rs b/crates/engine/src/script/dom/save_open.rs index 65691227c9..f8c0cb5d16 100644 --- a/crates/engine/src/script/dom/save_open.rs +++ b/crates/engine/src/script/dom/save_open.rs @@ -42,8 +42,8 @@ use serde_json::{Map, Value, json}; use vectorcraft_js::{Data, HostClass, HostError, HostFunction}; use super::{ - Answer, Described, Host, Link, MAX_TEXT_BYTES, NO_ACTIVE_DOCUMENT, arg, boolean, command, command_value, current, doc_ref, given, method, named, - num, on_doc, property, returns, text, this_doc, typed, whole, + Answer, Described, Host, Link, MAX_TEXT_BYTES, NO_ACTIVE_DOCUMENT, arg, boolean, command_value, current, doc_ref, given, method, named, num, + on_doc, property, returns, text, this_doc, typed, whole, }; /// The most a scale factor of an export takes, in percent. @@ -667,6 +667,9 @@ fn doc_save_as(h: &Host, a: &[Data]) -> Answer { } } let real = h.disk.borrow().save_target(path).map_err(|m| refused(m, path))?; + if given_options.is_none() && extension.as_deref().is_some_and(|e| !e.is_empty()) && crate::cmd::fileio::format_for_name(path).is_none() { + return Err(HostError::Error("saveAs needs a recognized file extension or format options".into())); + } p.insert("path".into(), json!(plain(real))); let (_, value) = exactly(h, || on_doc(h, doc.uid, false, |h| command_value(h, "file.saveAs", &Value::Object(p))))?; // Each warning of the save (what the format leaves out) goes to the console. @@ -726,7 +729,10 @@ fn doc_export_file(h: &Host, a: &[Data]) -> Answer { let named = with_extension(path, &kind, svgz); let real = h.disk.borrow().save_target(&named).map_err(|m| refused(m, &named))?; p.insert("path".into(), json!(plain(real))); - exactly(h, || on_doc(h, doc.uid, false, |h| command(h, "document.export", &Value::Object(p))))?; + let (_, value) = exactly(h, || on_doc(h, doc.uid, false, |h| command_value(h, "document.export", &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!("exportFile: {w}"), |line, cut| h.line(super::super::console::Entry::Log(line), cut)); + } Ok(Data::Undefined) } diff --git a/crates/engine/src/script/dom/tracing.rs b/crates/engine/src/script/dom/tracing.rs index c26cf2839e..e2c3708000 100644 --- a/crates/engine/src/script/dom/tracing.rs +++ b/crates/engine/src/script/dom/tracing.rs @@ -146,6 +146,17 @@ fn replaced(h: &Host, uid: u64, old: NodeId, new: NodeId) { h.dom.tracing.next.borrow_mut().insert((uid, old.0), new.0); } +pub(super) fn remember_source(h: &Host, uid: u64, group: &Node) { + if let Some(source) = group.children().and_then(|c| c.first()) { + h.dom.tracing.sources.borrow_mut().entry((uid, group.id.0)).or_insert(source.id); + } +} + +pub(super) fn same_source(h: &Host, uid: u64, original: NodeId, group: &Node) -> bool { + let source = h.dom.tracing.sources.borrow().get(&(uid, original.0)).copied(); + source.is_some_and(|source| group.children().and_then(|c| c.first()).is_some_and(|n| n.id == source)) +} + /// The error of a member with no VectorCraft setting. pub fn not_implemented(class: &str, name: &str) -> String { format!("{class}.{name} is not implemented") @@ -185,12 +196,9 @@ fn tracing_of(h: &Host, d: &Data, cls: &str) -> Result<(Item, [f64; 5]), HostErr return Err(HostError::Type(format!("this is not a {cls}"))); }; 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(|g| crate::cmd::is_trace_group(g) && g.children().and_then(|c| c.first()).is_some_and(|n| n.id == source)) - }); + let (doc, original) = node_of(h, &handle).ok_or_else(stale)?; + let id = follow(h, doc.uid, original); + let live = with_doc(h, doc, |_, st| st.doc.node(id).is_some_and(|g| crate::cmd::is_trace_group(g) && same_source(h, doc.uid, original, g))); if !live { return Err(stale()); } @@ -219,9 +227,18 @@ fn read_group(h: &Host, item: Item, f: impl FnOnce(&crate::DocState, &Node) - }) } +fn refuse_uneditable(h: &Host, item: Item) -> Result<(), HostError> { + let editable = with_doc(h, item.doc, |_, st| super::editable(&st.doc, item.id) && !super::on_locked_artboard(h, st, item.id)); + if !editable { + return Err(HostError::Error(format!("Cannot edit page item {}", item.id.0))); + } + Ok(()) +} + /// 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 { + refuse_uneditable(h, item)?; 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)?; @@ -402,8 +419,8 @@ fn tracing_resolution(h: &Host, a: &[Data]) -> Answer { } fn tracing_parent(h: &Host, a: &[Data]) -> Answer { - let (item, _) = tracing_of(h, arg(a, 0), "TracingObject")?; - Ok(with_doc(h, item.doc, |_, st| item_ref(h, st, item.id))) + let (_, handle) = tracing_of(h, arg(a, 0), "TracingObject")?; + Ok(host_ref("PluginItem", &handle)) } fn tracing_source(h: &Host, a: &[Data]) -> Answer { @@ -608,6 +625,7 @@ fn options_set_view(h: &Host, a: &[Data], raster: bool) -> Answer { let pair = |r: &str, v: &str| if raster { given == r && other == v } else { other == r && given == v }; let (to, ..) = VIEWS.iter().find(|(_, r, v)| pair(r, v)).ok_or_else(|| invalid(name))?; if *to != view { + refuse_uneditable(h, item)?; edit_item(h, item, "imageTrace.setView", &json!({"ids": [item.id.0], "view": to.id()}))?; } Ok(Data::Undefined) diff --git a/crates/engine/src/tests/script_dom_images.rs b/crates/engine/src/tests/script_dom_images.rs index 0caa9403e1..6628e48bdc 100644 --- a/crates/engine/src/tests/script_dom_images.rs +++ b/crates/engine/src/tests/script_dom_images.rs @@ -86,6 +86,26 @@ fn place(s: &mut Session, path: &Path, link: bool) -> NodeId { NodeId(r["ids"][0].as_u64().unwrap()) } +#[test] +fn placed_add_file_keeps_wrapper_identity_in_collections() { + let base = folder("bound-identity"); + let png = base.join("main/a.png"); + std::fs::write(&png, gray_png(4, 4)).unwrap(); + let mut s = session(); + let out = log( + &mut s, + &base, + &format!( + "var d = app.activeDocument, p = d.placedItems.add(); p.file = new File('{}'); p.name = 'placed'; d.selection = [p];\ + vc.log(p === d.placedItems[0]); vc.log(p === d.placedItems.getByName('placed'));\ + vc.log(p === d.pageItems[0]); vc.log(p === d.selection[0]);", + js_path(&png) + ), + ); + assert_eq!(out, vec![json!(true); 4]); + let _ = std::fs::remove_dir_all(base); +} + #[test] fn placed_add_file_links_one_image() { let base = folder("add"); diff --git a/crates/engine/src/tests/script_dom_tracing.rs b/crates/engine/src/tests/script_dom_tracing.rs index ed9b1e5431..523c70e5b2 100644 --- a/crates/engine/src/tests/script_dom_tracing.rs +++ b/crates/engine/src/tests/script_dom_tracing.rs @@ -245,6 +245,88 @@ fn expand_keeps_images_moved_and_duplicated_into_the_tracing() { 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 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"); @@ -259,11 +341,12 @@ fn tracing_handle_is_stale_when_another_image_replaces_its_source() { 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);", + 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"; 3])]); + 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); } diff --git a/crates/engine/src/tests/script_save_open.rs b/crates/engine/src/tests/script_save_open.rs index 8c62fb87d9..bee1b78188 100644 --- a/crates/engine/src/tests/script_save_open.rs +++ b/crates/engine/src/tests/script_save_open.rs @@ -93,6 +93,51 @@ fn save_as_export_file_and_open_write_and_read_where_the_script_may() { let _ = std::fs::remove_dir_all(base); } +#[test] +fn export_file_logs_encoder_warnings() { + let base = folder("export-warnings"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let text = format!( + "Folder.userData; var d = app.documents.add(DocumentColorSpace.RGB, 200, 100);\ + vc.run('shape.rectangle', {{x: 10, y: 10, width: 50, height: 20}});\ + d.pathItems[0].name = 'invalid\\u0001name';\ + vc.log(String(d.exportFile(new File({}), ExportType.SVG)));", + quoted(&dir.join("warnings.svg")) + ); + let r = run(&mut s, &base, &text).unwrap(); + assert_eq!(r["log"], json!(["undefined"])); + assert!(dir.join("warnings.svg").is_file()); + let lines = r["console"]["lines"].as_array().unwrap(); + let warning = "exportFile: Object names containing invalid XML characters were left out of SVG name attributes"; + assert!(lines.iter().any(|line| line.as_str() == Some(warning)), "{lines:?}"); + let _ = std::fs::remove_dir_all(base); +} + +#[test] +fn save_as_rejects_unknown_extensions_without_format_options() { + let base = folder("unknown-extension"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + s.execute("file.new", &json!({"width": 200, "height": 100})).unwrap(); + let before = vectorcraft_format::save(&s.active().unwrap().doc, false); + for options in ["", ", null", ", undefined"] { + let text = format!("Folder.userData; app.activeDocument.saveAs(new File({}){options});", quoted(&dir.join("typo.pfd"))); + let e = failure(&mut s, &base, &text); + assert!(e.contains("saveAs needs a recognized file extension or format options"), "{e}"); + assert!(!dir.join("typo.pfd").exists()); + assert_eq!(vectorcraft_format::save(&s.active().unwrap().doc, false), before); + assert!(s.active().unwrap().path.is_none()); + } + logged( + &mut s, + &base, + &format!("Folder.userData; app.activeDocument.saveAs(new File({}), new PDFSaveOptions());", quoted(&dir.join("explicit.pfd"))), + ); + assert!(std::fs::read(dir.join("explicit.pfd")).unwrap().starts_with(b"%PDF-")); + let _ = std::fs::remove_dir_all(base); +} + /// The warnings of the save go to the console, and `saveAs` still returns nothing. #[test] fn save_as_logs_the_saves_warnings() {