diff --git a/crates/engine/src/cmd/fileio/save.rs b/crates/engine/src/cmd/fileio/save.rs index 94187808c6..ba7e6682af 100644 --- a/crates/engine/src/cmd/fileio/save.rs +++ b/crates/engine/src/cmd/fileio/save.rs @@ -1071,13 +1071,13 @@ impl SaveJob { return Ok(stopped); } // Every path is checked against the file access in force before the first file is - // written. A refused file goes to `write` first, which refuses it with the error the - // caller gives (naming the path as the caller does), so none of the files is written. + // written. A refused file is refused here, so none of the files is written, also through + // a `write` that does not check the file access itself. #[cfg(not(target_arch = "wasm32"))] if files.len() > 1 - && let Some((p, bytes)) = files.iter().find(|(p, _)| super::may_write(p).is_err()) + && let Some(refused) = files.iter().find_map(|(p, _)| super::may_write(p).err()) { - write(p, bytes)?; + return Err(refused); } for (i, (p, bytes)) in files.iter().enumerate() { if i == 0 { diff --git a/crates/engine/src/cmd/fileio/tests.rs b/crates/engine/src/cmd/fileio/tests.rs index 56e2a12f30..36ace77603 100644 --- a/crates/engine/src/cmd/fileio/tests.rs +++ b/crates/engine/src/cmd/fileio/tests.rs @@ -1038,6 +1038,31 @@ fn a_save_canceled_after_its_first_file_writes_them_all() { let _ = std::fs::remove_dir_all(&d); } +/// A save that writes several files, through a writer that does not check the file access in +/// force, writes none of them when that access refuses one: the save refuses it itself. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_save_of_several_files_refused_by_the_file_access_writes_none_through_any_writer() { + let d = tmp_dir("refused-files"); + let mut s = session(100.0, 100.0, 2); + s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 30, "height": 30})).unwrap(); + let path = d.join("logo.eps").to_string_lossy().to_string(); + let plan = save_plan(&s, SaveMode::Copy, &json!({"path": path, "options": {"useArtboards": true}})).unwrap(); + let job = save_job(&mut s, plan).unwrap(); + let mut written = vec![]; + let r = crate::file_access::confine(Some(&crate::file_access::AutomationRoots::none()), || { + job.write(|p, b| { + std::fs::write(p, b).map_err(|e| EngineError::Other(e.to_string()))?; + written.push(p.to_string()); + Ok(()) + }) + }); + assert!(r.as_ref().is_err_and(|e| e.to_string().contains("write authority is absent")), "{r:?}"); + assert!(written.is_empty(), "{written:?}"); + assert_eq!(std::fs::read_dir(&d).unwrap().count(), 0, "nothing written"); + let _ = std::fs::remove_dir_all(&d); +} + /// A save that fails leaves File Info's dates and the saved state alone; one that works stamps them. #[test] fn a_failed_save_does_not_stamp_the_documents_dates() { diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 87f348a24c..20d6668374 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -1171,20 +1171,23 @@ fn selection_ids(h: &Host, doc: Doc, v: &Data) -> std::result::Result a.iter().collect(), d => vec![d], }; - let mut ids: Vec = Vec::with_capacity(list.len()); - for d in list { - let item = item_of(h, d)?; - let ok = item.doc.uid == doc.uid - && with_doc(h, doc, |_, st| crate::cmd::select::is_selectable(&st.doc, st.isolation, &st.doc.locked_artboards(), item.id)); - if !ok { - let name = with_doc(h, item.doc, |_, st| st.doc.node(item.id).and_then(typename).unwrap_or("page item")); - return Err(HostError::Error(format!("Cannot select {name} {}", item.id.0))); + // The locked artboards are worked out once for the whole list. + with_doc(h, doc, |_, st| { + let locked = st.doc.locked_artboards(); + let mut ids: Vec = Vec::with_capacity(list.len()); + let mut seen = std::collections::HashSet::with_capacity(list.len()); + for d in list { + let item = item_of(h, d)?; + if item.doc.uid != doc.uid || !crate::cmd::select::is_selectable(&st.doc, st.isolation, &locked, item.id) { + let name = with_doc(h, item.doc, |_, st| st.doc.node(item.id).and_then(typename).unwrap_or("page item")); + return Err(HostError::Error(format!("Cannot select {name} {}", item.id.0))); + } + if seen.insert(item.id) { + ids.push(item.id); + } } - if !ids.contains(&item.id) { - ids.push(item.id); - } - } - Ok(ids) + Ok(ids) + }) } fn doc_set_selection(h: &Host, a: &[Data]) -> Answer { @@ -1453,6 +1456,28 @@ fn item_visible(h: &Host, a: &[Data]) -> Answer { bounds(h, a, true) } +/// `controlBounds`: the visible bounds and the Bézier handles of the item's paths. +fn item_control(h: &Host, a: &[Data]) -> Answer { + let item = this_item(h, a)?; + let (r, f) = item_rect(h, item, true)?; + let handles = with_doc(h, item.doc, |_, st| st.doc.node(item.id).and_then(handle_bounds)); + Ok(f.bounds(h.dom.coords.get(), handles.map_or(r, |b| r.union(b)))) +} + +/// The bounds of the anchors and handles of `n`'s paths: a path's own, and those of the shown +/// paths in a group or compound path (a clip group's from its clipping path). `None` for other +/// objects. +fn handle_bounds(n: &crate::doc::Node) -> Option { + match &n.kind { + NodeKind::Path { path, .. } => path.control_bounds(), + NodeKind::Group { children, clip: true } => children.first().and_then(|c| handle_bounds(c)), + NodeKind::Group { children, .. } | NodeKind::Compound { children, .. } => { + children.iter().filter(|c| c.visible).filter_map(|c| handle_bounds(c)).reduce(|a, b| a.union(b)) + } + _ => None, + } +} + fn item_position(h: &Host, a: &[Data]) -> Answer { let item = this_item(h, a)?; let (r, f) = item_rect(h, item, false)?; @@ -1623,19 +1648,25 @@ struct Destination { fn destination(h: &Host, item: Item, target: &Data, how: &Data, copy: bool) -> std::result::Result { let how = placement_of(how)?; let beside = matches!(how, Placement::Above | Placement::Below); - let pending = images::pending_as_item(h, target)?.map(|p| p.to_vec()); - let handle = pending.or_else(|| handle_of(target, "PageItem")).or_else(|| handle_of(target, "Layer")); - let Some(&[run, uid, high, low]) = handle.as_deref() else { - if handle_of(target, "Document").is_some() { - return Err(HostError::Error("a document as the relative object is not available yet".into())); - } - return Err(HostError::Type("the relative object must be a page item or a layer".into())); + // A page item is looked up as its class names it (a wrapper whose object changed class is + // stale), a layer by its handle. + let (doc, target) = if handle_of(target, "PageItem").is_some() { + let t = item_of(h, target)?; + (t.doc, t.id) + } else { + let handle = handle_of(target, "Layer"); + let Some(&[run, uid, high, low]) = handle.as_deref() else { + if handle_of(target, "Document").is_some() { + return Err(HostError::Error("a document as the relative object is not available yet".into())); + } + return Err(HostError::Type("the relative object must be a page item or a layer".into())); + }; + let doc = find_doc(h, run, uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; + (doc, id_of(high, low).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?) }; - let doc = find_doc(h, run, uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; if doc.uid != item.doc.uid { return Err(HostError::Error(CROSS_DOCUMENT.into())); } - let target = id_of(high, low).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; with_doc(h, doc, |_, st| { let d = &st.doc; let t = d.node(target).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; @@ -1672,7 +1703,10 @@ fn place(h: &Host, doc: Doc, id: NodeId, to: &Destination) -> std::result::Resul let d = &st.doc; let from = d.position(id); let count = d.children(Some(to.parent)).map_or(0, Vec::len) - usize::from(from.is_some_and(|(p, ..)| p == Some(to.parent))); - let clips = d.node(to.parent).is_some_and(crate::doc::Node::clips) && count > 0; + // A clip group's first child is its clipping path, and an Image Trace object's its source + // image: both stay first (the source image itself may go to the end of its own tracing). + let source = crate::cmd::is_trace_source(d, id) && d.parent_of(id) == Some(to.parent); + let clips = d.node(to.parent).is_some_and(|n| n.clips() || (crate::cmd::is_trace_group(n) && !source)) && count > 0; let at = match (to.how, to.beside) { (Placement::Top, _) => count, (Placement::Bottom, _) => 0, @@ -1932,7 +1966,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), ("height", property(l, item_height, item_set_height)), ("geometricBounds", get(l, item_geometric)), ("visibleBounds", get(l, item_visible)), - ("controlBounds", get(l, item_visible)), + ("controlBounds", get(l, item_control)), ("editable", get(l, item_editable)), ("zOrderPosition", get(l, item_z_order_position)), ("duplicate", method(l, item_duplicate)), diff --git a/crates/engine/src/script/dom/images.rs b/crates/engine/src/script/dom/images.rs index b1a3665190..10291e2ef1 100644 --- a/crates/engine/src/script/dom/images.rs +++ b/crates/engine/src/script/dom/images.rs @@ -40,9 +40,9 @@ use vectorcraft_geom::{Affine, Point}; use vectorcraft_js::{Data, HostClass, HostError, HostMember, file_ref, file_ref_path, host_ref, host_ref_parts}; use super::{ - Answer, Coords, Doc, Host, Item, Link, NOT_FOUND, ON_LOCKED_ARTBOARD, STALE_ITEM, all_editable, arg, class, command, doc_of, doc_ref, edit_item, - editable, find_doc, float, frame, get, item_of, item_ref, later, method, named, num, on_doc, page_items, property, text, typename_of, whole, - with_doc, + Answer, Coords, Doc, Host, Item, Link, NOT_FOUND, ON_LOCKED_ARTBOARD, STALE_ITEM, all_editable, arg, class, command, command_value, doc_of, + doc_ref, edit_item, editable, find_doc, float, frame, get, item_of, item_ref, later, method, named, num, on_doc, page_items, property, text, + typename_of, whole, with_doc, }; use crate::{DocState, Document, NodeId, NodeKind}; @@ -127,14 +127,6 @@ fn pending_handle(d: &Data) -> Option<[f64; 3]> { } } -/// The page item handle (run, uid and the two halves of the id) of the image a -/// `PlacedItems.add()` result `d` placed, or `None` when `d` is not such a result. -pub(super) fn pending_as_item(h: &Host, d: &Data) -> Result, HostError> { - let Some([run, uid, slot]) = pending_handle(d) else { return Ok(None) }; - let [high, low] = super::id_parts(pending_id(h, run, uid, slot)?); - Ok(Some([run, uid, high, low])) -} - /// The ids of a document's linked (`placed`) or embedded images in paint order. fn images(h: &Host, st: &DocState, placed: bool) -> Result>, HostError> { let pick = |l: &Lists| if placed { l.2.clone() } else { l.3.clone() }; @@ -360,6 +352,8 @@ fn placed_file(h: &Host, a: &[Data]) -> Answer { if let Some([run, uid, slot]) = pending_handle(arg(a, 0)) { let k = slot_of(h, run, uid, slot)?; if h.dom.images.pending.borrow().get(k).is_some_and(|p| p.bound.is_none()) { + // Null while its document is open; stale once that document is closed. + find_doc(h, run, uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; return Ok(Data::Null); } } @@ -387,12 +381,12 @@ fn placed_set_file(h: &Host, a: &[Data]) -> Answer { } let doc = find_doc(h, run, uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?; let path = image_path(h, arg(a, 1), "PlacedItem.file")?; - let placed = on_doc(h, doc.uid, true, |h| command(h, "file.place", &json!({"path": path, "link": true})))?; - let ids: Vec = match field(&placed, "ids") { - Some(Data::Array(ids)) => ids.iter().filter_map(|d| id_value(Some(d))).map(|i| i.0).collect(), - _ => Vec::new(), - }; - let id = id_value(field(&placed, "image")).or_else(|| id_value(field(&placed, "ids"))); + // The ids are read from the command's own result, where every id is exact (a script number + // holds integers exactly only up to 2^53). + let (_, placed) = on_doc(h, doc.uid, true, |h| command_value(h, "file.place", &json!({"path": path, "link": true})))?; + let ids: Vec = placed["ids"].as_array().map(|ids| ids.iter().filter_map(serde_json::Value::as_u64).collect()).unwrap_or_default(); + let first = |v: &serde_json::Value| v.as_u64().or_else(|| v.as_array().and_then(|a| a.first()).and_then(serde_json::Value::as_u64)); + let id = first(&placed["image"]).or_else(|| first(&placed["ids"])).map(NodeId); let linked = |id: NodeId| with_doc(h, doc, |_, st| matches!(st.doc.node(id).map(|n| &n.kind), Some(NodeKind::Image(im)) if im.link.is_some())); match id.filter(|id| linked(*id)) { Some(id) => { diff --git a/crates/engine/src/script/dom/save_open.rs b/crates/engine/src/script/dom/save_open.rs index c76ae0f44e..04a06629d0 100644 --- a/crates/engine/src/script/dom/save_open.rs +++ b/crates/engine/src/script/dom/save_open.rs @@ -84,6 +84,77 @@ pub(super) const ENUMS: &[(&str, &[&str])] = &[ ("EPSPostScriptLevelEnum", &["LEVEL2", "LEVEL3"]), ("PDFOverprint", &["DISCARDPDFOVERPRINT", "PRESERVEPDFOVERPRINT"]), ("UserInteractionLevel", &["DISPLAYALERTS", "DONTDISPLAYALERTS"]), + // The enumerations of the option defaults ([`Default::Member`]), with the members + // https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/ lists. + ("OutputFlattening", &["PRESERVEAPPEARANCE", "PRESERVEPATHS"]), + ( + "CompressionQuality", + &[ + "AUTOMATICJPEG2000HIGH", + "AUTOMATICJPEG2000LOSSLESS", + "AUTOMATICJPEG2000LOW", + "AUTOMATICJPEG2000MAXIMUM", + "AUTOMATICJPEG2000MEDIUM", + "AUTOMATICJPEG2000MINIMUM", + "AUTOMATICJPEGHIGH", + "AUTOMATICJPEGLOW", + "AUTOMATICJPEGMAXIMUM", + "AUTOMATICJPEGMEDIUM", + "AUTOMATICJPEGMINIMUM", + "JPEG2000HIGH", + "JPEG2000LOSSLESS", + "JPEG2000LOW", + "JPEG2000MAXIMUM", + "JPEG2000MEDIUM", + "JPEG2000MINIMUM", + "JPEGHIGH", + "JPEGLOW", + "JPEGMAXIMUM", + "JPEGMEDIUM", + "JPEGMINIMUM", + "ZIP4BIT", + "ZIP8BIT", + "None", + ], + ), + ("ColorConversion", &["COLORCONVERSIONREPURPOSE", "COLORCONVERSIONTODEST", "None"]), + ( + "ColorDestination", + &[ + "COLORDESTINATIONDOCCMYK", + "COLORDESTINATIONDOCRGB", + "COLORDESTINATIONPROFILE", + "COLORDESTINATIONWORKINGCMYK", + "COLORDESTINATIONWORKINGRGB", + "None", + ], + ), + ("DownsampleMethod", &["AVERAGEDOWNSAMPLE", "BICUBICDOWNSAMPLE", "NODOWNSAMPLE", "SUBSAMPLE"]), + ("ColorProfile", &["INCLUDEALLPROFILE", "INCLUDEDESTPROFILE", "INCLUDERGBPROFILE", "LEAVEPROFILEUNCHANGED", "None"]), + ("MonochromeCompression", &["CCIT3", "CCIT4", "MONOZIP", "None", "RUNLENGTH"]), + ("PageMarksTypes", &["Japanese", "Roman"]), + ("PDFPrintAllowedEnum", &["PRINT128HIGHRESOLUTION", "PRINT128LOWRESOLUTION", "PRINT128NONE", "PRINT40HIGHRESOLUTION", "PRINT40NONE"]), + ( + "PDFChangesAllowedEnum", + &[ + "CHANGE128ANYCHANGES", + "CHANGE128COMMENTING", + "CHANGE128EDITPAGE", + "CHANGE128FILLFORM", + "CHANGE128NONE", + "CHANGE40ANYCHANGES", + "CHANGE40COMMENTING", + "CHANGE40NONE", + "CHANGE40PAGELAYOUT", + ], + ), + ("PDFXStandard", &["PDFX1A2001", "PDFX1A2003", "PDFX32002", "PDFX32003", "PDFX42007", "PDFXNONE"]), + ("PDFTrimMarkWeight", &["TRIMMARKWEIGHT0125", "TRIMMARKWEIGHT025", "TRIMMARKWEIGHT05"]), + ("SVGCSSPropertyLocation", &["ENTITIES", "STYLEATTRIBUTES", "PRESENTATIONATTRIBUTES", "STYLEELEMENTS"]), + ("SVGDocumentEncoding", &["ASCII", "UTF8", "UTF16"]), + ("SVGDTDVersion", &["SVG1_0", "SVG1_1", "SVGBASIC1_1", "SVGTINY1_1", "SVGTINY1_1PLUS", "SVGTINY1_2"]), + ("SVGFontSubsetting", &["ALLGLYPHS", "GLYPHSUSEDPLUSENGLISH", "COMMONENGLISH", "GLYPHSUSEDPLUSROMAN", "COMMONROMAN", "GLYPHSUSED", "None"]), + ("SVGFontType", &["CEFFONT", "SVGFONT", "OUTLINEFONT"]), ]; const DISPLAY: &str = "UserInteractionLevel.DISPLAYALERTS"; diff --git a/crates/engine/src/script/dom/tracing.rs b/crates/engine/src/script/dom/tracing.rs index f8642f3b7d..4e37fb9f31 100644 --- a/crates/engine/src/script/dom/tracing.rs +++ b/crates/engine/src/script/dom/tracing.rs @@ -118,26 +118,31 @@ pub(super) struct State { } /// `id` while the document `uid` holds it (a run never gives an id out twice, so an undo that put -/// it back put back the same object), else the Image Trace object that replaced it when this run -/// traced it again, else `id`. +/// it back put back the same object), else the first object the document holds among those that +/// replaced it, one after the other, when this run traced it again (an Undo can put back one of +/// them), else the last of them, else `id`. pub(super) fn follow(h: &Host, uid: u64, id: NodeId) -> NodeId { - let held = h.session.borrow().documents().iter().find(|d| d.uid == uid).is_some_and(|d| d.doc.node(id).is_some()); - if held { - return id; - } - h.dom.tracing.next.borrow().get(&(uid, id.0)).map_or(id, |n| NodeId(*n)) -} - -/// Records that `new` replaced `old` in the document `uid`: every object that led to `old` leads to -/// `new` now. -fn replaced(h: &Host, uid: u64, old: NodeId, new: NodeId) { - let mut next = h.dom.tracing.next.borrow_mut(); - for ((u, _), to) in next.iter_mut() { - if *u == uid && *to == old.0 { - *to = new.0; + let s = h.session.borrow(); + let doc = s.documents().iter().find(|d| d.uid == uid); + let held = |id: NodeId| doc.is_some_and(|d| d.doc.node(id).is_some()); + let next = h.dom.tracing.next.borrow(); + let mut id = id; + // Each object is replaced by one made later, so the steps end; the bound holds them anyway. + for _ in 0..=next.len() { + if held(id) { + return id; + } + match next.get(&(uid, id.0)) { + Some(n) => id = NodeId(*n), + None => return id, } } - next.insert((uid, old.0), new.0); + id +} + +/// Records that `new` replaced `old` in the document `uid`. +fn replaced(h: &Host, uid: u64, old: NodeId, new: NodeId) { + h.dom.tracing.next.borrow_mut().insert((uid, old.0), new.0); } /// The error of a member with no VectorCraft setting. diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 5bf276e3b9..18fdf0b133 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -118,6 +118,20 @@ fn page_item_geometry_uses_document_coordinates_with_y_up() { assert_eq!(out[4], json!([20, 250, 80, 210])); } +/// `controlBounds` takes in the Bézier handles of a path, which can reach past what it draws. +#[test] +fn page_item_control_bounds_take_in_the_handles() { + let (mut s, _, _) = doc(); + let anchors = json!([{"x": 0, "y": 100, "out": [0, 0]}, {"x": 100, "y": 100, "in": [100, 0]}]); + s.execute("path.create", &json!({"anchors": anchors})).unwrap(); + let out = log(&mut s, "var p = app.activeDocument.pageItems, i = p[p.length - 1]; vc.log(i.visibleBounds); vc.log(i.controlBounds);"); + let b = |v: &Value| -> Vec { v.as_array().unwrap().iter().map(|n| n.as_f64().unwrap()).collect() }; + let (visible, control) = (b(&out[0]), b(&out[1])); + assert!(visible[1] < 290.0, "the curve stays well under its handles: {visible:?}"); + assert!((control[1] - 300.0).abs() < 1e-9, "the handles reach the top of the page: {control:?}"); + assert!(control[0] <= visible[0] && control[2] >= visible[2] && control[3] <= visible[3], "{visible:?} {control:?}"); +} + #[test] fn page_item_size_setters_on_a_rotated_object_give_the_page_aligned_size() { let (mut s, a, b) = doc(); @@ -451,6 +465,14 @@ fn a_grid_by_column_takes_the_number_of_rows() { let tops = distinct(boards.iter().map(|b| b.rect.y0.round() as i64).collect()); let lefts = distinct(boards.iter().map(|b| b.rect.x0.round() as i64).collect()); assert_eq!((tops, lefts), (rows, cols), "{layout} {count}"); + if layout.ends_with("GridByCol") { + // A column fills from the top before the next one starts, to the right of it (to the + // left from right to left). + let (first, second, next) = (boards[0].rect, boards[1].rect, boards[rows].rect); + assert!((second.x0 - first.x0).abs() < 1e-9 && second.y0 > first.y0, "{layout} {count}: {first:?} {second:?}"); + let rightward = next.x0 > first.x0; + assert_eq!(rightward, layout == "GridByCol", "{layout} {count}: {first:?} {next:?}"); + } } } @@ -1003,8 +1025,10 @@ fn get_is_file_open_cannot_probe_outside_script_scope() { let (mut s, _, _) = doc(); let path = std::env::temp_dir().join(format!("vc-dom-open-{}.svg", std::process::id())); s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap(); - let p = path.to_string_lossy().replace('\\', "\\\\"); - let query = format!("vc.log(app.getIsFileOpen('{p}')); vc.log(app.getIsFileOpen('{p}.other'));"); + // String literals of the script, whatever characters the temporary folder's path holds. + let literal = |p: String| serde_json::to_string(&p).unwrap(); + let (p, other) = (literal(path.to_string_lossy().into_owned()), literal(format!("{}.other", path.to_string_lossy()))); + let query = format!("vc.log(app.getIsFileOpen({p})); vc.log(app.getIsFileOpen({other}));"); let out = log(&mut s, &query); assert_eq!(out, vec![json!(true), json!(false)]); // Read roots that leave out the document's file: the same path does not count. diff --git a/crates/engine/src/tests/script_dom_images.rs b/crates/engine/src/tests/script_dom_images.rs index 7a3b764276..8101e17ab0 100644 --- a/crates/engine/src/tests/script_dom_images.rs +++ b/crates/engine/src/tests/script_dom_images.rs @@ -522,3 +522,64 @@ fn members_not_available_yet_check_the_image_first() { assert_eq!(out, vec![json!(["PlacedItem.file is required", "Stale page item", "RasterItem.colorize is not available yet", "Stale page item"])]); let _ = std::fs::remove_dir_all(base); } + +/// The `file` of a `PlacedItems.add()` result with no file is null while its document is open, and +/// the item is stale once that document is closed. +#[test] +fn a_pending_placed_items_file_is_stale_once_its_document_closes() { + let base = folder("pending-closed"); + let mut s = session(); + let out = log( + &mut s, + &base, + "var p = app.activeDocument.placedItems.add(); vc.log(p.file); vc.run('file.close', {});\ + var m = ''; try { vc.log(p.file); } catch (e) { m = e.message; } vc.log(m);", + ); + assert_eq!(out, vec![json!(null), json!("Stale page item")]); + let _ = std::fs::remove_dir_all(base); +} + +/// Assigning `file` binds the placed item to the image `file.place` made, by its exact id, also +/// for an id above 2^53, which a script number does not hold exactly. +#[test] +fn a_placed_items_file_binds_the_exact_id_of_the_image_placed() { + let base = folder("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 out = log( + &mut s, + &base, + &format!("var p = app.activeDocument.placedItems.add(); p.file = new File('{}'); vc.log(p.file.name); vc.log(p.width);", js_path(&png)), + ); + assert_eq!(out, vec![json!("a.png"), json!(4)]); + let imgs = images(&s); + assert_eq!(imgs.len(), 1, "{imgs:?}"); + assert_eq!(imgs[0].0, NodeId(big)); + let _ = std::fs::remove_dir_all(base); +} + +/// A `PlacedItem` that was embedded is stale as the relative object of `move`: the raster item +/// it became is named by a fresh wrapper. +#[test] +fn a_stale_placed_item_is_refused_as_the_relative_object_of_move() { + let base = folder("stale-relative"); + let a = base.join("main/a.png"); + std::fs::write(&a, gray_png(4, 4)).unwrap(); + let mut s = session(); + place(&mut s, &a, true); + let rect = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap(); + let out = log( + &mut s, + &base, + "var d = app.activeDocument, p = d.placedItems[0], x = null, m = '';\ + for (var i = 0; i < d.pageItems.length; i++) { if (d.pageItems[i].typename == 'PathItem') x = d.pageItems[i]; }\ + p.embed(); try { x.move(p, ElementPlacement.PLACEAFTER); } catch (e) { m = e.message; } vc.log(m);\ + x.move(d.rasterItems[0], ElementPlacement.PLACEAFTER); vc.log(d.pageItems[0].typename);", + ); + assert_eq!(out, vec![json!("Stale page item"), json!("PathItem")]); + assert!(s.active().unwrap().doc.node(NodeId(rect)).is_some()); + let _ = std::fs::remove_dir_all(base); +} diff --git a/crates/engine/src/tests/script_dom_tracing.rs b/crates/engine/src/tests/script_dom_tracing.rs index 9479139027..dd48079cef 100644 --- a/crates/engine/src/tests/script_dom_tracing.rs +++ b/crates/engine/src/tests/script_dom_tracing.rs @@ -393,6 +393,26 @@ fn trace_external_retrace_undo_and_source_delete() { 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"); @@ -506,6 +526,32 @@ fn trace_of_another_image_inside_a_tracing() { 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> = 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); +} + #[test] fn trace_source_art_is_not_listed_with_the_images() { let base = folder("lists"); diff --git a/crates/engine/src/tests/script_save_open.rs b/crates/engine/src/tests/script_save_open.rs index 8518f14365..3812314b26 100644 --- a/crates/engine/src/tests/script_save_open.rs +++ b/crates/engine/src/tests/script_save_open.rs @@ -178,6 +178,36 @@ fn a_pdf_preset_keeps_its_settings_unless_an_option_changes() { let _ = std::fs::remove_dir_all(base); } +/// The defaults of the options a save or export does not map are named through their +/// enumerations, and an options object given them saves as one left as it was. +#[test] +fn option_defaults_are_named_through_their_enumerations() { + let base = folder("enum-defaults"); + let mut s = session(&base); + let dir = data_folder(&mut s, &base); + let d = quoted(&dir); + let out = logged( + &mut s, + &base, + &format!( + "Folder.userData; var dir = {d}, d = app.documents.add(DocumentColorSpace.RGB, 200, 100);\n\ + vc.run('shape.rectangle', {{x: 10, y: 10, width: 50, height: 20}});\n\ + var o = new PDFSaveOptions(); o.colorDownsamplingMethod = DownsampleMethod.NODOWNSAMPLE;\n\ + o.colorCompression = CompressionQuality.None; o.monochromeCompression = MonochromeCompression.None;\n\ + o.flattenOutput = OutputFlattening.PRESERVEAPPEARANCE; o.pDFXStandard = PDFXStandard.PDFXNONE;\n\ + d.saveAs(new File(dir + '/a.pdf'), o);\n\ + var v = new ExportOptionsSVG(); v.cssProperties = SVGCSSPropertyLocation.STYLEATTRIBUTES;\n\ + v.documentEncoding = SVGDocumentEncoding.ASCII; v.DTD = SVGDTDVersion.SVG1_1; v.fontType = SVGFontType.CEFFONT;\n\ + v.fontSubsetting = SVGFontSubsetting.ALLGLYPHS; d.exportFile(new File(dir + '/s'), ExportType.SVG, v);\n\ + vc.log([DownsampleMethod.BICUBICDOWNSAMPLE, CompressionQuality.ZIP8BIT, SVGCSSPropertyLocation.ENTITIES]);" + ), + ); + assert_eq!(out, json!([["DownsampleMethod.BICUBICDOWNSAMPLE", "CompressionQuality.ZIP8BIT", "SVGCSSPropertyLocation.ENTITIES"]])); + assert!(std::fs::read(dir.join("a.pdf")).unwrap().starts_with(b"%PDF-")); + assert!(dir.join("s.svg").is_file()); + let _ = std::fs::remove_dir_all(base); +} + /// A save that writes several files, such as an EPS with a file per artboard, writes none of them /// when one may not be written. #[test] diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index 8593d593aa..3beea4cfed 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -177,6 +177,44 @@ const INSIDE: &[(&str, &str)] = &[ ("PDFCompatibility.", "ACROBAT4 ACROBAT5 ACROBAT6 ACROBAT7 ACROBAT8"), ("PDFOverprint.", "DISCARDPDFOVERPRINT PRESERVEPDFOVERPRINT"), ("UserInteractionLevel.", "DISPLAYALERTS DONTDISPLAYALERTS"), + // The enumerations of the save and export options' defaults. + ( + "", + "ColorConversion ColorDestination ColorProfile CompressionQuality DownsampleMethod MonochromeCompression \ + OutputFlattening PDFChangesAllowedEnum PDFPrintAllowedEnum PDFTrimMarkWeight PDFXStandard PageMarksTypes \ + SVGCSSPropertyLocation SVGDTDVersion SVGDocumentEncoding SVGFontSubsetting SVGFontType", + ), + ("ColorConversion.", "COLORCONVERSIONREPURPOSE COLORCONVERSIONTODEST None"), + ( + "ColorDestination.", + "COLORDESTINATIONDOCCMYK COLORDESTINATIONDOCRGB COLORDESTINATIONPROFILE COLORDESTINATIONWORKINGCMYK \ + COLORDESTINATIONWORKINGRGB None", + ), + ("ColorProfile.", "INCLUDEALLPROFILE INCLUDEDESTPROFILE INCLUDERGBPROFILE LEAVEPROFILEUNCHANGED None"), + ( + "CompressionQuality.", + "AUTOMATICJPEG2000HIGH AUTOMATICJPEG2000LOSSLESS AUTOMATICJPEG2000LOW AUTOMATICJPEG2000MAXIMUM \ + AUTOMATICJPEG2000MEDIUM AUTOMATICJPEG2000MINIMUM AUTOMATICJPEGHIGH AUTOMATICJPEGLOW AUTOMATICJPEGMAXIMUM \ + AUTOMATICJPEGMEDIUM AUTOMATICJPEGMINIMUM JPEG2000HIGH JPEG2000LOSSLESS JPEG2000LOW JPEG2000MAXIMUM \ + JPEG2000MEDIUM JPEG2000MINIMUM JPEGHIGH JPEGLOW JPEGMAXIMUM JPEGMEDIUM JPEGMINIMUM None ZIP4BIT ZIP8BIT", + ), + ("DownsampleMethod.", "AVERAGEDOWNSAMPLE BICUBICDOWNSAMPLE NODOWNSAMPLE SUBSAMPLE"), + ("MonochromeCompression.", "CCIT3 CCIT4 MONOZIP None RUNLENGTH"), + ("OutputFlattening.", "PRESERVEAPPEARANCE PRESERVEPATHS"), + ( + "PDFChangesAllowedEnum.", + "CHANGE128ANYCHANGES CHANGE128COMMENTING CHANGE128EDITPAGE CHANGE128FILLFORM CHANGE128NONE \ + CHANGE40ANYCHANGES CHANGE40COMMENTING CHANGE40NONE CHANGE40PAGELAYOUT", + ), + ("PDFPrintAllowedEnum.", "PRINT128HIGHRESOLUTION PRINT128LOWRESOLUTION PRINT128NONE PRINT40HIGHRESOLUTION PRINT40NONE"), + ("PDFTrimMarkWeight.", "TRIMMARKWEIGHT0125 TRIMMARKWEIGHT025 TRIMMARKWEIGHT05"), + ("PDFXStandard.", "PDFX1A2001 PDFX1A2003 PDFX32002 PDFX32003 PDFX42007 PDFXNONE"), + ("PageMarksTypes.", "Japanese Roman"), + ("SVGCSSPropertyLocation.", "ENTITIES PRESENTATIONATTRIBUTES STYLEATTRIBUTES STYLEELEMENTS"), + ("SVGDTDVersion.", "SVG1_0 SVG1_1 SVGBASIC1_1 SVGTINY1_1 SVGTINY1_1PLUS SVGTINY1_2"), + ("SVGDocumentEncoding.", "ASCII UTF16 UTF8"), + ("SVGFontSubsetting.", "ALLGLYPHS COMMONENGLISH COMMONROMAN GLYPHSUSED GLYPHSUSEDPLUSENGLISH GLYPHSUSEDPLUSROMAN None"), + ("SVGFontType.", "CEFFONT OUTLINEFONT SVGFONT"), // The enumerations of placed and raster items. ("", "ImageColorSpace RasterLinkState"), ("ImageColorSpace.", "CMYK DeviceN Grayscale Indexed LAB RGB Separation"), diff --git a/crates/ui-egui/src/dialogs/new_document.rs b/crates/ui-egui/src/dialogs/new_document.rs index cf10f0035e..48f32b93d8 100644 --- a/crates/ui-egui/src/dialogs/new_document.rs +++ b/crates/ui-egui/src/dialogs/new_document.rs @@ -253,9 +253,13 @@ fn layout(d: &Dialog) -> (ArtboardLayout, u64, f64, bool) { } /// Sets one artboard layout field. A new layout or column count replaces the rows of a preset -/// made with `file.new`'s `rows`; a new layout keeps the column count those rows showed. +/// made with `file.new`'s `rows`; a new layout keeps the column count those rows showed. The +/// layout in force chosen again changes nothing. fn set_layout(d: &mut Dialog, key: &str, v: Value) { let (lay, shown, ..) = layout(d); + if key == "layout" && v.as_str().and_then(ArtboardLayout::parse) == Some(lay) { + return; + } let mut l = d.fields.get("artboardLayout").cloned().filter(Value::is_object).unwrap_or_else(|| json!({})); if let ("layout" | "columns", Some(o)) = (key, l.as_object_mut()) && o.remove("rows").and_then(|r| r.as_f64()).is_some_and(|r| r.is_finite() && r >= 1.0) @@ -935,7 +939,10 @@ mod tests { set(&mut app, "artboardLayout", json!({"layout": "gridByColumn", "columns": 2, "rows": rows})); assert_eq!(columns(&app), 3, "9 artboards in rows {rows}"); super::set_layout(app.ui.dialog.as_mut().unwrap(), "layout", json!(to)); - assert_eq!(field(&app, "artboardLayout"), json!({"layout": to, "columns": 3}), "{to}, rows {rows}"); + // The layout in force chosen again keeps the rows, and the columns follow them. + let kept = if to == "gridByColumn" { json!({"layout": to, "columns": 2, "rows": rows}) } else { json!({"layout": to, "columns": 3}) }; + assert_eq!(field(&app, "artboardLayout"), kept, "{to}, rows {rows}"); + assert_eq!(columns(&app), 3, "{to}, rows {rows}"); } } set(&mut app, "artboardLayout", json!({"layout": "gridByRow", "columns": 2, "rows": 4})); diff --git a/crates/ui-egui/src/panels/image_trace/tests.rs b/crates/ui-egui/src/panels/image_trace/tests.rs index c35a961aa3..ca44c496ac 100644 --- a/crates/ui-egui/src/panels/image_trace/tests.rs +++ b/crates/ui-egui/src/panels/image_trace/tests.rs @@ -1674,16 +1674,24 @@ fn a_trace_off_the_ui_thread_is_adopted_when_it_lands() { } /// The object Trace acts on as the panel found it before [`find_target`]: every selected object put -/// in paint order, the first image or Image Trace object among them taken, else the first selected -/// object. +/// in paint order, the first image or Image Trace object among them taken (an Image Trace object's +/// source image is traced through that object, so it is skipped), else the first selected object +/// when it is neither. fn target_node_sorting_everything(app: &VectorcraftApp) -> Option { let st = app.session.active()?; - let traceable = |n: &&Node| is_trace(n) || matches!(n.kind, NodeKind::Image(_)); + let traceable = |n: &Node| is_trace(n) || matches!(n.kind, NodeKind::Image(_)); + let source = |id: NodeId| { + st.doc + .parent_of(id) + .and_then(|g| st.doc.node(g)) + .is_some_and(|g| is_trace(g) && g.children().and_then(|c| c.first()).is_some_and(|f| f.id == id)) + }; st.selection .in_paint_order(&st.doc) .into_iter() - .find_map(|id| st.doc.node(id).filter(traceable).cloned()) - .or_else(|| first_selected(app).map(|n| (*n).clone())) + .filter(|id| !source(*id)) + .find_map(|id| st.doc.node(id).filter(|n| traceable(n)).cloned()) + .or_else(|| first_selected(app).filter(|n| !traceable(n)).map(|n| (*n).clone())) } /// [`Target`] from [`target_node_sorting_everything`] and a scan of the whole selection for Image @@ -1779,6 +1787,9 @@ fn the_target_lookup_matches_sorting_the_whole_selection() { &["trace", "trace image"], &["trace image", "trace"], &["rect", "trace image"], + &["trace image"], + &["trace image", "rect"], + &["trace image", "front"], &["clip"], &["rect", "clipped"], &["outer"], diff --git a/docs/gaps.md b/docs/gaps.md index fc32f5b719..602b94f48a 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -810,7 +810,9 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi - **Missing:** the rest of the document object model for scripts (layers, artboards, paths, type and the other classes) and the `#engine` script directive (#1183 is open). Scripts have `app`, the open documents, new documents, each document's selection and its page items, and its linked and embedded images (`placedItems` and - `rasterItems`, with `PlacedItem` and `RasterItem`); tracing, rasterizing and capturing images are still missing. File › Scripts › Other Script… and `script.run` run JavaScript files over the command registry, `#targetengine` + `rasterItems`, with `PlacedItem` and `RasterItem`), and trace them with `trace()`, which gives the Image Trace + object as a `PluginItem` with its `TracingObject` and `TracingOptions`; the tracing options VectorCraft has no + setting for, rasterizing and capturing images are still missing. File › Scripts › Other Script… and `script.run` run JavaScript files over the command registry, `#targetengine` runs a script in a named engine whose globals last between runs, File › Scripts lists the scripts of the Scripts folder, and Window › Script Console shows their output, errors and run reports. Actions, Batch, Variables (text, visibility, image and graph), data set CSV import and diff --git a/docs/mcp.md b/docs/mcp.md index 00ad4fe8af..6730483bc9 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2642,8 +2642,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot starts with the defaults that page gives. Its `documentBleedLink`, `documentBleedOffsetRect` and `transparencyGrid` can be assigned, but `addDocument` throws an error that says they are not available yet when the preset it is given holds one of them with a value other than `null`, and makes no document. A - `presetSettings` that is not a `DocumentPreset` (a plain object such as `{width: 500}` included) throws a - `TypeError`. A script's `file.new` reads the profile's file in the profiles folder as the person's does, under the + `presetSettings` of `null` or `undefined` counts as omitted. Any other `presetSettings` that is not a + `DocumentPreset` (a plain object such as `{width: 500}` included) throws a `TypeError`. A script's `file.new` reads the profile's file in the profiles folder as the person's does, under the automation roots in force; when `file.new` reports a `profileError`, `addDocument` throws an error that names the profile and the reason, and makes no document. `showOptionsDialog` true throws `Dialog unavailable` with no document made. A `Document` (https://ai-scripting.docsforadobe.dev/jsobjref/Document/) has `name`, @@ -2656,7 +2656,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot or removes only that object, as `select.add` and `select.toggle` do, and the other objects stay selected as they were), `opacity` (0 to 100), `position`, `left`, `top`, `width`, `height`, `geometricBounds`, `visibleBounds`, `controlBounds` (the - visible bounds), `editable`, `zOrderPosition`, `duplicate(relativeObject?, insertionLocation?)`, + visible bounds with the anchors and Bézier handles of the object's paths, and of the shown paths in its groups and + compound paths; a clip group's come from its clipping path), `editable`, `zOrderPosition`, `duplicate(relativeObject?, insertionLocation?)`, `move(relativeObject, insertionLocation?)`, `remove()` and `zOrder(method)` (https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/). `move` runs `node.move`, and `duplicate` runs `edit.duplicate` and then `node.move` on the copy. The relative object is a page item or a layer of the same @@ -2717,7 +2718,10 @@ app through the global object `vc`, and writes to the Script Console and runs ot `options` is a `PDFFileOptions` record (https://ai-scripting.docsforadobe.dev/jsobjref/PDFFileOptions/) with `pageToOpen` and `pDFCropToBox`. `app.userInteractionLevel` is `UserInteractionLevel.DISPLAYALERTS` at the start of each run. The enumerations `ExportType`, `Compatibility`, `PDFCompatibility`, `PDFBoxType`, `EPSPreview`, - `EPSPostScriptLevelEnum`, `PDFOverprint` and `UserInteractionLevel` hold strings such as `"ExportType.PNG24"`. + `EPSPostScriptLevelEnum`, `PDFOverprint` and `UserInteractionLevel` hold strings such as `"ExportType.PNG24"`, as + do the enumerations of the other options' defaults (`CompressionQuality`, `DownsampleMethod`, + `SVGCSSPropertyLocation` and the like), with the members + https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/ lists. VectorCraft's own rules: each path is checked as a `File` opened for reading or writing is checked, before the command runs. A path outside the script's folders throws `Script file access denied`, also when it is an open document's file, a link that leads outside them, or the settings folder; a read-only file throws `Script file is @@ -2777,7 +2781,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot count the seam fills of an Abutting trace, `usedColorCount` counts the different fill and stroke paints, and `imageResolution` is the image's pixels per inch as placed, an error for an image placed at different resolutions across and down. Assigning an option, or `loadFromPreset(name)`, traces again with `imageTrace.make`, keeps the - source image and the view, and a value the tracing already has runs no command. The `PluginItem`, `TracingObject` + source image and the view, and a value the tracing already has runs no command. Assigning `viewRaster` or + `viewVector` does not trace again: it runs `imageTrace.setView`. The `PluginItem`, `TracingObject` and `TracingOptions` follow the new object, and a run traces again at most 10,000 times. `threshold` takes a whole number from 0 to 255, `maxColors` from 2 to 256 and `minArea` (the Noise setting, in pixels) from 0 to the largest image the tracer reads; `fills` and `strokes` cannot both be `false`; `palette` is `""` (automatic), `"Limited"`,