diff --git a/crates/engine/src/doc_state.rs b/crates/engine/src/doc_state.rs index f87cc07654..07f423b4be 100644 --- a/crates/engine/src/doc_state.rs +++ b/crates/engine/src/doc_state.rs @@ -3,6 +3,44 @@ use super::history::{History, HistoryEntry}; use super::interaction::{Interaction, LastTransform, UndoGroup}; use super::{Arc, Document, NodeId, NodeKind, Selection, Value, cmd, file_access}; +/// A document's window as the desktop app shows it ([`crate::Session::window_views`]). +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct WindowView { + /// The document point at the centre of the canvas. + pub center: vectorcraft_geom::Point, + /// The zoom is 1 at the window's displayed 100%. + pub zoom: f64, + /// The camera uses this scale at the window's displayed 100%. + pub zoom_baseline: f64, + /// The view's rotation in degrees, clockwise on screen. + pub rotation: f64, + /// The canvas's width and height in document points at a zoom of 1. + pub size: [f64; 2], + /// View › Screen Mode: 0 Normal, 1 Full Screen Mode with Menu Bar, 2 Full Screen Mode, 3 + /// Presentation Mode (`view.screenMode`). + pub screen_mode: u8, +} + +impl WindowView { + /// The physical camera scale stays within these limits. + pub const ZOOM_RANGE: (f64, f64) = (0.0313, 640.0); + + /// `zoom_range` returns this window's allowed displayed zoom ratios. + pub fn zoom_range(&self) -> (f64, f64) { + let (min, max) = Self::ZOOM_RANGE; + (min / self.zoom_baseline, max / self.zoom_baseline) + } + + /// The part of the document the canvas shows: the box around its four corners, which a + /// rotated view turns. + pub fn visible(&self) -> vectorcraft_geom::Rect { + let (sin, cos) = self.rotation.to_radians().sin_cos(); + let (w, h) = (self.size[0] / self.zoom / 2.0, self.size[1] / self.zoom / 2.0); + let (x, y) = (w * cos.abs() + h * sin.abs(), w * sin.abs() + h * cos.abs()); + vectorcraft_geom::Rect::new(self.center.x - x, self.center.y - y, self.center.x + x, self.center.y + y) + } +} + /// Per-document editing state. #[derive(Clone, Debug)] pub struct DocState { diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index a0d8b3510d..46e6c04343 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -375,6 +375,11 @@ pub struct Session { pub(crate) script_high_water: std::collections::HashMap, /// While a slice of a script runs in this session. pub(crate) script_in_run: bool, + /// The desktop app supplies each window by (document uid, runtime window identity) while a + /// script runs. Scripts read them as `Document.views`, and the app applies their zoom, center, + /// and screen mode. This list is empty without windows (headless). + /// View state: not saved, not undoable, and a run that fails keeps what it changed. + pub window_views: Vec<((u64, u64), WindowView)>, /// Write recovery copies of the unsaved documents before a run, and don't start without them. pub script_copy_first: bool, /// While the active tool's actions run: their commands aren't "a command from outside the @@ -499,7 +504,7 @@ pub(crate) use command_sets::SELECTS_GIVEN_IDS; #[cfg(test)] use command_sets::given_ids; pub use command_sets::{DRAWS_SHAPE, FIT_ACTIVE_ARTBOARD, ON_ACTIVE_ARTBOARD, waits_for_plugin_loads, waits_for_tool_edit}; -pub use doc_state::{DocState, LayersReveal, OpenRows, RecalledSelection}; +pub use doc_state::{DocState, LayersReveal, OpenRows, RecalledSelection, WindowView}; pub use error::{EngineError, READ_ONLY_LOCATION, Result, SCRIPT_BUSY}; #[cfg(test)] use history::history_budget_for; diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 7554440ab6..f57b6129cf 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -2,8 +2,10 @@ //! them, as the help pages , //! , //! , -//! and -//! describe them. +//! , +//! , +//! and +//! describe them. //! //! The objects are host classes ([`vectorcraft_js::HostClass`]): each holds the run's number, the //! document's [`crate::DocState::uid`] and, for art and layers, the object's id and the document's @@ -46,6 +48,15 @@ //! must be one of that document's that can be selected, or nothing changes. `undefined` throws. //! - `controlBounds` is the visible bounds, widened to take in the direction points of every path //! in the object. +//! - `Document.views` holds the document's drawn windows ([`crate::Session::window_views`]), +//! in view-number order, and none without one. View objects keep their window's identity when +//! windows are renumbered. The screen mode is the app's: +//! setting it on one view sets it on every view. Its `zoom` is 1 at the window's displayed 100%; +//! the physical camera scale ranges from 0.0313 to 640, and the allowed zoom ratios account for +//! the window's display density with Display Print Size at 100% Zoom enabled. `screenMode` reads +//! Presentation Mode as `ScreenMode.FULLSCREEN`. Changing a view runs no command, is not +//! undoable and stays when the run fails. +//! A center outside the canvas after coordinate conversion throws a `RangeError`. //! - Members the help pages list that are not here yet throw an error that says so, and `reflect` //! leaves them out. //! - Assigning `hidden`, `locked`, `opacity`, `position`, `left`, `top`, `width` or `height` to an @@ -76,7 +87,7 @@ use vectorcraft_js::{ }; use super::{HISTORY_LOST, Host, Link, Savepoint, command, command_value, current, data_size}; -use crate::{DocState, Document, NodeId, NodeKind, Session}; +use crate::{DocState, Document, NodeId, NodeKind, Session, WindowView}; mod tags; mod variables; @@ -102,6 +113,8 @@ pub const STALE_ITEM: &str = "Stale page item"; pub const STALE_DOCUMENT: &str = "Stale document"; /// The error of `index` and `getByName` when nothing matches. pub const NOT_FOUND: &str = "Not found"; +/// The error for a view whose document no longer has a window, or that came from an earlier run. +pub const STALE_VIEW: &str = "Stale view"; /// The most objects one read of a selection gives, and the most a selection assignment takes. pub const MAX_LISTED: usize = 10_000; /// The longest name an object or a path query may have, in bytes. @@ -1481,6 +1494,179 @@ fn doc_selection(h: &Host, a: &[Data]) -> Answer { selection_of(h, doc.uid) } +fn doc_views(h: &Host, a: &[Data]) -> Answer { + let doc = this_doc(h, a)?; + Ok(host_ref("Views", &[float(h.run), float(doc.uid)])) +} + +// ---- Views and View ---- + +fn views_doc(h: &Host, a: &[Data]) -> std::result::Result { + doc_of(h, arg(a, 0), "Views") +} + +fn window_of(h: &Host, doc: Doc, id: u64) -> Option { + h.session.borrow().window_views.iter().find(|((uid, window), _)| *uid == doc.uid && *window == id).map(|(_, v)| *v) +} + +fn views_length(h: &Host, a: &[Data]) -> Answer { + let doc = views_doc(h, a)?; + Ok(num(h.session.borrow().window_views.iter().filter(|((uid, _), _)| *uid == doc.uid).count() as f64)) +} + +fn views_typename(h: &Host, a: &[Data]) -> Answer { + views_doc(h, a)?; + Ok(text("Views")) +} + +fn views_parent(h: &Host, a: &[Data]) -> Answer { + let doc = views_doc(h, a)?; + Ok(doc_ref(h, doc.uid)) +} + +fn views_to_string(h: &Host, a: &[Data]) -> Answer { + views_doc(h, a)?; + Ok(text("[Views]")) +} + +fn views_at(h: &Host, a: &[Data]) -> Answer { + let doc = views_doc(h, a)?; + let index = match arg(a, 1) { + Data::Number(n) => whole(*n).and_then(|n| usize::try_from(n).ok()), + _ => None, + }; + let Some(index) = index else { return Ok(Data::Undefined) }; + let key = h.session.borrow().window_views.iter().filter(|((uid, _), _)| *uid == doc.uid).nth(index).map(|(key, _)| *key); + Ok(key.map_or(Data::Undefined, |(uid, id)| host_ref("View", &[float(h.run), float(uid), float(id)]))) +} + +/// `views.index(key)`: the view at index `key`. A view has no name, so a name finds nothing. +fn views_index(h: &Host, a: &[Data]) -> Answer { + match arg(a, 1) { + Data::String(_) => { + views_doc(h, a)?; + Err(HostError::Error(NOT_FOUND.into())) + } + Data::Number(_) => match views_at(h, a)? { + Data::Undefined => Err(HostError::Error(NOT_FOUND.into())), + d => Ok(d), + }, + _ => Err(HostError::Type("give a name or an index".into())), + } +} + +/// The document of a `View` and its window, which must still be shown. +fn this_view(h: &Host, a: &[Data]) -> std::result::Result<(Doc, u64, WindowView), HostError> { + let Some(handle) = handle_of(arg(a, 0), "View") else { return Err(HostError::Type("this is not a View".into())) }; + let &[run, uid, id] = handle.as_slice() else { return Err(HostError::Type("this is not a View".into())) }; + let doc = find_doc(h, run, uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?; + let id = whole(id).ok_or_else(|| HostError::Error(STALE_VIEW.into()))?; + let v = window_of(h, doc, id).ok_or_else(|| HostError::Error(STALE_VIEW.into()))?; + Ok((doc, id, v)) +} + +/// Reads the view with `f`, given the document's script coordinates. +fn read_view(h: &Host, a: &[Data], f: impl FnOnce(&Frame, Coords, &WindowView) -> Data) -> Answer { + let (doc, _, v) = this_view(h, a)?; + with_doc(h, doc, |_, st| Ok(f(&frame(st)?, h.dom.coords.get(), &v))) +} + +/// Changes the window of `doc` with `f`. No command runs: the change is not undoable, does not +/// join the run's undo step and stays when the run fails. +fn set_window(h: &Host, doc: Doc, id: u64, f: impl FnOnce(&mut WindowView)) -> Answer { + let mut s = h.session.borrow_mut(); + let v = s + .window_views + .iter_mut() + .find(|((uid, window), _)| *uid == doc.uid && *window == id) + .map(|(_, v)| v) + .ok_or_else(|| HostError::Error(STALE_VIEW.into()))?; + f(v); + Ok(Data::Undefined) +} + +fn view_typename(h: &Host, a: &[Data]) -> Answer { + this_view(h, a)?; + Ok(text("View")) +} + +fn view_parent(h: &Host, a: &[Data]) -> Answer { + let (doc, _, _) = this_view(h, a)?; + Ok(doc_ref(h, doc.uid)) +} + +fn view_to_string(h: &Host, a: &[Data]) -> Answer { + this_view(h, a)?; + Ok(text("[View]")) +} + +/// `bounds`: `[left, top, right, bottom]` of the part of the document the canvas shows. +fn view_bounds(h: &Host, a: &[Data]) -> Answer { + read_view(h, a, |f, c, v| f.bounds(c, v.visible())) +} + +fn view_center(h: &Host, a: &[Data]) -> Answer { + read_view(h, a, |f, c, v| pair(f.to_script(c, v.center))) +} + +fn view_set_center(h: &Host, a: &[Data]) -> Answer { + let (doc, id, _) = this_view(h, a)?; + let p = point(arg(a, 1), "centerPoint")?; + let to = with_doc(h, doc, |_, st| frame(st).map(|f| f.to_document(h.dom.coords.get(), p)))?; + if to.x.abs() > crate::MAX_COORD || to.y.abs() > crate::MAX_COORD { + return Err(HostError::Range("centerPoint is outside the canvas".into())); + } + set_window(h, doc, id, |v| v.center = to) +} + +fn view_zoom(h: &Host, a: &[Data]) -> Answer { + let (_, _, v) = this_view(h, a)?; + Ok(num(v.zoom)) +} + +fn view_set_zoom(h: &Host, a: &[Data]) -> Answer { + let (doc, id, v) = this_view(h, a)?; + let z = number(arg(a, 1), "zoom")?; + let (min, max) = v.zoom_range(); + if !(min..=max).contains(&z) { + return Err(HostError::Range(format!("zoom must be from {min} to {max}"))); + } + set_window(h, doc, id, |v| v.zoom = z) +} + +/// The `ScreenMode` value of each of the app's screen modes: Presentation Mode reads as +/// `FULLSCREEN`. +fn screen_mode_name(mode: u8) -> &'static str { + match mode { + 0 => "ScreenMode.MULTIWINDOW", + 1 => "ScreenMode.DESKTOP", + _ => "ScreenMode.FULLSCREEN", + } +} + +fn view_screen_mode(h: &Host, a: &[Data]) -> Answer { + let (_, _, v) = this_view(h, a)?; + Ok(text(screen_mode_name(v.screen_mode))) +} + +fn view_set_screen_mode(h: &Host, a: &[Data]) -> Answer { + let (_, _, v) = this_view(h, a)?; + let mode = match arg(a, 1) { + Data::String(s) if s == "ScreenMode.MULTIWINDOW" => 0, + Data::String(s) if s == "ScreenMode.DESKTOP" => 1, + Data::String(s) if s == "ScreenMode.FULLSCREEN" => 2, + _ => return Err(HostError::Type("give a ScreenMode value".into())), + }; + if screen_mode_name(v.screen_mode) == screen_mode_name(mode) { + return Ok(Data::Undefined); + } + // The screen mode is the app's, so every view shows the new one. + for (_, v) in &mut h.session.borrow_mut().window_views { + v.screen_mode = mode; + } + Ok(Data::Undefined) +} + /// The selection of the document `uid`: a new list of the selected objects, topmost first as /// `pageItems` lists them, empty when nothing is selected. fn selection_of(h: &Host, uid: u64) -> Answer { @@ -2329,6 +2515,7 @@ const ENUMS: &[(&str, &[&str])] = &[ ("RulerUnits", &["Centimeters", "Qs", "Inches", "Pixels", "Millimeters", "Unknown", "Picas", "Points"]), ("DocumentColorSpace", &["CMYK", "RGB"]), ("CoordinateSystem", &["ARTBOARDCOORDINATESYSTEM", "DOCUMENTCOORDINATESYSTEM"]), + ("ScreenMode", &["DESKTOP", "FULLSCREEN", "MULTIWINDOW"]), ("DocumentArtboardLayout", &["Column", "GridByCol", "GridByRow", "RLGridByCol", "RLGridByRow", "RLRow", "Row"]), ("DocumentPresetType", &["BasicCMYK", "BasicRGB", "Mobile", "Print", "Video", "Web"]), ("DocumentPreviewMode", &["DefaultPreview", "OverprintPreview", "PixelPreview"]), @@ -2450,16 +2637,43 @@ fn classes(link: &Link) -> Vec { ), ("pageItems", get(l, doc_page_items), MemberInfo { collection: true, ..typed("PageItems") }), ("selection", property(l, doc_selection, doc_set_selection), typed("*")), + ("views", get(l, doc_views), MemberInfo { collection: true, ..typed("Views") }), ("toString", method(l, doc_to_string), returns("string", &[])), ]); document.extend( - ["layers", "artboards", "pathItems", "groupItems", "textFrames", "swatches", "symbols", "views", "activeLayer", "saveAs", "close"] + ["layers", "artboards", "pathItems", "groupItems", "textFrames", "swatches", "symbols", "activeLayer", "saveAs", "close"] .into_iter() .map(|m| later(l, "Document", m)), ); document.extend(variables::document_members(l)); document.push(("tags".into(), get(l, tags::doc_tags), MemberInfo { collection: true, ..typed("Tags") })); classes.push(class("Document", None, document, None)); + classes.push(class( + "Views", + None, + named(vec![ + ("typename", get(l, views_typename), typed("string")), + ("length", get(l, views_length), typed("number")), + ("parent", get(l, views_parent), typed("Document")), + ("index", method(l, views_index), returns("View", &[("itemKey", "*")])), + ("toString", method(l, views_to_string), returns("string", &[])), + ]), + Some(function(l, views_at)), + )); + classes.push(class( + "View", + None, + named(vec![ + ("typename", get(l, view_typename), typed("string")), + ("parent", get(l, view_parent), typed("Views")), + ("bounds", get(l, view_bounds), typed("Array")), + ("centerPoint", property(l, view_center, view_set_center), typed("Array")), + ("zoom", property(l, view_zoom, view_set_zoom), typed("number")), + ("screenMode", property(l, view_screen_mode, view_set_screen_mode), typed("ScreenMode")), + ("toString", method(l, view_to_string), returns("string", &[])), + ]), + None, + )); classes.push(class( "PageItems", None, diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 7fc5f36967..258468641d 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -190,6 +190,7 @@ impl Session { startup_failures: vec![], script_high_water: Default::default(), script_in_run: false, + window_views: vec![], script_copy_first: cfg!(target_arch = "wasm32"), } } diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 295ed12f90..43de4420a4 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -193,6 +193,140 @@ fn ruler_origin_round_trips_without_moving_art() { assert!(failure(&mut s, "app.activeDocument.rulerOrigin = [1e12, 0];").contains("outside the canvas")); } +/// A window on the document of [`doc`] that shows 300 × 200 pt around (200, 150) at 200%. +fn window() -> WindowView { + WindowView { + center: vectorcraft_geom::Point::new(200.0, 150.0), + zoom: 2.0, + zoom_baseline: 1.0, + rotation: 0.0, + size: [600.0, 400.0], + screen_mode: 0, + } +} + +/// Shows the active document in the window `v`. +fn show(s: &mut Session, v: WindowView) { + let uid = s.active().unwrap().uid; + s.window_views = vec![((uid, 1), v)]; +} + +/// The window of the active document. +fn shown(s: &Session) -> Option { + let uid = s.active().unwrap().uid; + s.window_views.iter().find(|((u, _), _)| *u == uid).map(|(_, v)| *v) +} + +#[test] +fn the_view_shows_the_part_of_the_document_its_window_shows() { + let (mut s, ..) = doc(); + let none = "var v = app.activeDocument.views; vc.log(v.length); vc.log(v[0] === undefined); vc.log(0 in v); vc.log('a' in v);"; + assert_eq!(log(&mut s, none), vec![json!(0), json!(true), json!(false), json!(false)], "a document without a window has no view"); + show(&mut s, window()); + // A rectangle drawn over the visible part of the document has the view's bounds. + let r = window().visible(); + rect(&mut s, r.x0, r.y0, r.width(), r.height()); + let out = log( + &mut s, + "var d = app.activeDocument; var v = d.views[0]; vc.log(d.views.length); vc.log(v.typename);\ + vc.log(v.parent === d); vc.log(v.bounds); var r = d.pageItems[0];\ + vc.log(r.geometricBounds); vc.log(v.centerPoint); vc.log(r.position[0] + r.width / 2);\ + vc.log(r.position[1] - r.height / 2);", + ); + assert_eq!(out[..3], [json!(1), json!("View"), json!(true)]); + assert_eq!(out[3], out[4], "the view's bounds are the visible area"); + assert_eq!(out[5], json!([out[6], out[7]]), "the centre is the middle of the visible area"); + // Turning the view shows more of the document around the same centre. + show(&mut s, WindowView { rotation: 30.0, ..window() }); + let turned = log(&mut s, "vc.log(app.activeDocument.views[0].bounds);"); + let width = |b: &Value| b[2].as_f64().unwrap() - b[0].as_f64().unwrap(); + assert!(width(&turned[0]) > width(&out[3])); + let names = log(&mut s, "var d = app.activeDocument; vc.log(String(d.views) + String(d.views[0]));"); + assert_eq!(names, vec![json!("[Views][View]")]); + assert_eq!(log(&mut s, "var v = app.activeDocument.views; vc.log(0 in v); vc.log(1 in v);"), vec![json!(true), json!(false)]); + // A named engine keeps the views from an earlier run, but they are stale. + run(&mut s, "#targetengine keep\nvar vs = app.activeDocument.views, v = vs[0];").unwrap(); + for member in ["String(vs)", "String(v)"] { + let e = failure(&mut s, &format!("#targetengine keep\n{member};")); + assert!(e.contains("Stale document"), "{member}: {e}"); + } +} + +#[test] +fn setting_the_zoom_changes_the_view_without_an_undo_step() { + let (mut s, ..) = doc(); + show(&mut s, window()); + // Another document's window. + s.window_views.push(((u64::MAX, 1), window())); + let steps = undo_steps(&s); + let out = log( + &mut s, + "var v = app.activeDocument.views[0]; var b = v.bounds; v.zoom = 4; vc.log(v.zoom);\ + vc.log(v.bounds[2] - v.bounds[0] < b[2] - b[0]); v.centerPoint = [100, 100]; vc.log(v.centerPoint);\ + v.screenMode = ScreenMode.FULLSCREEN; vc.log(v.screenMode);", + ); + assert_eq!(out, vec![json!(4), json!(true), json!([100, 100]), json!("ScreenMode.FULLSCREEN")]); + let now = shown(&s).unwrap(); + assert!(now.zoom > window().zoom); + assert!(now.center != window().center && now.screen_mode != window().screen_mode); + assert_eq!(s.window_views[1].1.screen_mode, now.screen_mode, "the screen mode is the same in every window"); + assert_eq!(s.window_views[1].1.zoom, window().zoom, "the zoom is each window's own"); + assert_eq!(undo_steps(&s), steps, "a view change is not undoable"); + // A bad value throws and leaves the view as it is. + let bad = [ + ("v.zoom = 0;", "RangeError"), + ("v.zoom = 1000;", "RangeError"), + ("v.zoom = '2';", "TypeError"), + ("v.centerPoint = [1];", "TypeError"), + ("v.centerPoint = [1e12, 0];", "RangeError"), + ("v.screenMode = 'FULLSCREEN';", "TypeError"), + ]; + for (bad, name) in bad { + let out = log(&mut s, &format!("var v = app.activeDocument.views[0]; try {{ {bad} vc.log('set'); }} catch (e) {{ vc.log(e.name); }}")); + assert_eq!(out, vec![json!(name)], "{bad}"); + assert_eq!(shown(&s), Some(now), "{bad}"); + } + // A run that fails after changing the view keeps the change. + failure(&mut s, "app.activeDocument.views[0].zoom = 1; throw new Error('stop');"); + assert_eq!(shown(&s).map(|v| v.zoom), Some(1.0)); +} + +#[test] +fn view_centers_stay_inside_the_canvas_after_coordinate_conversion() { + let (mut s, ..) = doc(); + let origin = vectorcraft_geom::Point::new(3.0e6, 3.0e6); + s.edit("Move Artboard", |d, _| { + d.artboards[0].rect = vectorcraft_geom::Rect::from_origin_size(origin, (400.0, 300.0)); + Ok(()) + }) + .unwrap(); + show(&mut s, window()); + let steps = undo_steps(&s); + for coordinates in ["ARTBOARDCOORDINATESYSTEM", "DOCUMENTCOORDINATESYSTEM"] { + let script_point = |p: vectorcraft_geom::Point| { + let y = if coordinates == "ARTBOARDCOORDINATESYSTEM" { p.y - origin.y } else { origin.y + 300.0 - p.y }; + [p.x - origin.x, y] + }; + for bound in [-MAX_COORD, MAX_COORD] { + for horizontal in [false, true] { + let point = |n| if horizontal { vectorcraft_geom::Point::new(n, 0.0) } else { vectorcraft_geom::Point::new(0.0, n) }; + let before = shown(&s); + let [x, y] = script_point(point(bound + bound.signum())); + let source = format!( + "app.coordinateSystem = CoordinateSystem.{coordinates}; var v = app.activeDocument.views[0]; \ + try {{ v.centerPoint = [{x}, {y}]; vc.log('set'); }} catch (e) {{ vc.log(e.name); }}" + ); + assert_eq!(log(&mut s, &source), vec![json!("RangeError")], "{source}"); + assert_eq!(shown(&s), before, "a rejected center leaves the view unchanged"); + let [x, y] = script_point(point(bound)); + log(&mut s, &format!("app.coordinateSystem = CoordinateSystem.{coordinates}; app.activeDocument.views[0].centerPoint = [{x}, {y}];")); + assert_eq!(shown(&s).unwrap().center, point(bound), "the canvas boundary is allowed"); + } + } + } + assert_eq!(undo_steps(&s), steps); +} + #[test] fn page_item_properties_join_one_undo_step() { let (mut s, a, _) = doc(); diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index c54d8676c0..b7257d62b1 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -81,7 +81,8 @@ const INSIDE: &[(&str, &str)] = &[ "", "activeDocument activeDocument= app Application CoordinateSystem Document DocumentArtboardLayout DocumentColorSpace \ DocumentPreset DocumentPresetType DocumentPreviewMode DocumentRasterResolution DocumentTransparencyGrid documents \ - Documents ElementPlacement Layer PageItem PageItems RulerUnits selection selection= Tag Tags ZOrderMethod", + Documents ElementPlacement Layer PageItem PageItems RulerUnits ScreenMode selection selection= Tag Tags View Views \ + ZOrderMethod", ), ("Application.", "prototype"), ( @@ -105,8 +106,12 @@ const INSIDE: &[(&str, &str)] = &[ "activeLayer activeLayer= artboards artboards= close close= constructor convertCoordinate documentColorSpace \ groupItems groupItems= height layers layers= name pageItems parent pathItems pathItems= rulerOrigin rulerOrigin= \ rulerUnits saveAs saveAs= selection selection= swatches swatches= symbols symbols= tags textFrames textFrames= toString \ - typename views views= width", + typename views width", ), + ("Views.", "prototype"), + ("Views.prototype.", "constructor index length parent toString typename"), + ("View.", "prototype"), + ("View.prototype.", "bounds centerPoint centerPoint= constructor parent screenMode screenMode= toString typename zoom zoom="), ("Layer.", "prototype"), ("Layer.prototype.", "constructor name toString typename"), ("PageItems.", "prototype"), @@ -138,6 +143,7 @@ const INSIDE: &[(&str, &str)] = &[ ), ("ElementPlacement.", "INSIDE PLACEAFTER PLACEATBEGINNING PLACEATEND PLACEBEFORE"), ("RulerUnits.", "Centimeters Inches Millimeters Picas Pixels Points Qs Unknown"), + ("ScreenMode.", "DESKTOP FULLSCREEN MULTIWINDOW"), ("ZOrderMethod.", "BRINGFORWARD BRINGTOFRONT SENDBACKWARD SENDTOBACK"), // Variables and data sets. `importVariables` reads the library file it is given. `PageItem`'s // `visibilityVariable` is in its row above. diff --git a/crates/ui-egui/src/doc_windows.rs b/crates/ui-egui/src/doc_windows.rs index ca91583b93..b0b1a7c7d9 100644 --- a/crates/ui-egui/src/doc_windows.rs +++ b/crates/ui-egui/src/doc_windows.rs @@ -26,7 +26,8 @@ use crate::canvas::{BodyKind, show_document}; mod views; pub(crate) use views::{ - Views, Win, close_current, close_window, current, label, new_window, retain as retain_views, show_window, unfit_all, view, view_mut, windows, + Views, Win, close_current, close_window, current, label, new_window, retain as retain_views, show_window, unfit_all, view, view_by_id_mut, + view_mut, windows, }; use views::{find, key, window_param}; diff --git a/crates/ui-egui/src/doc_windows/tests.rs b/crates/ui-egui/src/doc_windows/tests.rs index 99a979b982..5033868701 100644 --- a/crates/ui-egui/src/doc_windows/tests.rs +++ b/crates/ui-egui/src/doc_windows/tests.rs @@ -190,6 +190,164 @@ fn float_in_window_moves_the_current_document_out_of_the_tabs() { assert_eq!(app.ui.floating.len(), 1); } +#[test] +fn a_script_sees_each_window_at_its_own_size() { + let mut app = app_with(3); + let ctx = crate::testing::ui_context(); + frame(&mut app, &ctx, vec![]); + app.run("window.arrange.floatInWindow", json!({})).unwrap(); + frame(&mut app, &ctx, vec![]); + frame(&mut app, &ctx, vec![]); + let uids: Vec = app.session.documents().iter().map(|d| d.uid).collect(); + let shared = crate::script_runs::share_views(&mut app); + let width = |uid: u64| shared.iter().find(|((u, _), _)| *u == uid).map(|(_, v)| v.size[0]); + let (floating, tabbed) = (width(uids[2]).unwrap(), width(uids[0]).unwrap()); + assert!(floating < tabbed, "the floating window is narrower than the main window: {floating} and {tabbed}"); + assert_eq!(width(uids[1]), None, "a document never drawn has no view"); +} + +#[test] +fn script_view_zoom_uses_each_windows_display_percentage_and_keeps_physical_bounds() { + for print_size in [true, false] { + let mut app = app_with(1); + let ctx = crate::testing::ui_context(); + frame(&mut app, &ctx, vec![]); + app.run("window.newWindow", json!({})).unwrap(); + frame(&mut app, &ctx, vec![]); + app.session.execute("prefs.set", &json!({"key": "displayPrintSize", "value": print_size})).unwrap(); + for (number, ppi, percent) in [(1, 96.0, 100.0), (2, 144.0, 200.0)] { + let v = view_mut(&mut app, (0, number)).unwrap(); + v.shown_ppi = Some(crate::ScreenPpi::Read(Some(ppi))); + v.rotation = 0.0; + v.zoom = crate::state::zoom_from_display_percent(percent, crate::state::print_ppi(print_size, Some(ppi))); + } + let shared = crate::script_runs::share_views(&mut app); + for (number, (_, script_view)) in (1..).zip(&shared) { + let camera = view(&app, (0, number)).unwrap(); + let width = f64::from(camera.rect.width()) * f64::from(app.ui_scaling()) / camera.zoom; + assert!((script_view.visible().width() - width).abs() < 1e-9); + } + app.session.script_frames = false; + let report = app + .session + .execute( + "script.run", + &json!({"source": + "var vs = app.activeDocument.views; vc.log(vs[0].zoom); vc.log(vs[1].zoom); vs[0].zoom = 3; vs[1].zoom = 4;" + }), + ) + .unwrap(); + assert_eq!(report["log"], json!([1, 2]), "print size: {print_size}"); + crate::script_runs::take_views(&mut app, &shared); + for (number, percent) in [(1, 300.0), (2, 400.0)] { + let shown = crate::state::zoom_display_percent(view(&app, (0, number)).unwrap().zoom, app.print_ppi_of(Some((0, number)))); + assert!((shown - percent).abs() < 1e-9, "window {number}, print size {print_size}: {shown}"); + } + } +} + +#[test] +fn script_view_center_changes_preserve_zoom_at_camera_limits() { + for zoom in [0.0313, 640.0] { + let mut app = app_with(1); + let ctx = crate::testing::ui_context(); + frame(&mut app, &ctx, vec![]); + app.session.execute("prefs.set", &json!({"key": "displayPrintSize", "value": true})).unwrap(); + let v = view_mut(&mut app, (0, 1)).unwrap(); + v.shown_ppi = Some(crate::ScreenPpi::Read(Some(96.0))); + v.zoom = zoom; + let shared = crate::script_runs::share_views(&mut app); + app.session.script_frames = false; + app.session.execute("script.run", &json!({"source": "app.activeDocument.views[0].centerPoint = [10, 20];"})).unwrap(); + crate::script_runs::take_views(&mut app, &shared); + assert_eq!(view(&app, (0, 1)).unwrap().zoom, zoom); + } +} + +#[test] +fn script_view_zoom_refuses_values_outside_each_windows_camera_range() { + for ppi in [96.0, 144.0] { + let mut app = app_with(1); + let ctx = crate::testing::ui_context(); + frame(&mut app, &ctx, vec![]); + app.session.execute("prefs.set", &json!({"key": "displayPrintSize", "value": true})).unwrap(); + view_mut(&mut app, (0, 1)).unwrap().shown_ppi = Some(crate::ScreenPpi::Read(Some(ppi))); + let shared = crate::script_runs::share_views(&mut app); + app.session.script_frames = false; + let requested = 640.0 / crate::state::zoom_baseline(Some(ppi)) * 1.1; + let source = format!("try {{ app.activeDocument.views[0].zoom = {requested}; vc.log('accepted'); }} catch (e) {{ vc.log(e.name); }}"); + let report = app.session.execute("script.run", &json!({"source": source})).unwrap(); + assert_eq!(report["log"], json!(["RangeError"])); + crate::script_runs::take_views(&mut app, &shared); + } +} + +#[test] +fn a_script_lists_and_changes_each_view_of_one_document() { + let mut app = app_with(1); + app.session.execute("prefs.set", &json!({"key": "displayPrintSize", "value": false})).unwrap(); + let ctx = crate::testing::ui_context(); + frame(&mut app, &ctx, vec![]); + app.run("window.newWindow", json!({})).unwrap(); + frame(&mut app, &ctx, vec![]); + let camera = serde_json::to_value(view(&app, (0, 1)).unwrap()).unwrap(); + for number in [1, 2] { + let v = view_mut(&mut app, (0, number)).unwrap(); + let rect = v.rect; + *v = serde_json::from_value(camera.clone()).unwrap(); + v.rect = rect; + } + view_mut(&mut app, (0, 1)).unwrap().zoom = 1.0; + view_mut(&mut app, (0, 2)).unwrap().zoom = 2.0; + let shared = crate::script_runs::share_views(&mut app); + app.session.script_frames = false; + let count = app.session.execute("script.run", &json!({"source": "vc.log(app.activeDocument.views.length);"})).unwrap(); + assert_eq!(count["log"], json!([2])); + let source = "var vs = app.activeDocument.views; vc.log(vs.length); vc.log(vs[0] !== vs[1]); \ + vc.log(vs[0].bounds[2] - vs[0].bounds[0] > vs[1].bounds[2] - vs[1].bounds[0]); \ + vs[0].zoom = 3; vs[1].zoom = 4; vs[0].centerPoint = [10, 20]; vs[1].centerPoint = [30, 40]; \ + vs[1].screenMode = ScreenMode.FULLSCREEN;"; + let report = app.session.execute("script.run", &json!({"source": source})).unwrap(); + assert_eq!(report["log"], json!([2, true, true])); + show_window(&mut app, (0, 1)); + crate::script_runs::take_views(&mut app, &shared); + assert_eq!(view(&app, (0, 1)).unwrap().zoom, 3.0); + assert_eq!(view(&app, (0, 2)).unwrap().zoom, 4.0); + assert_ne!(view(&app, (0, 1)).unwrap().center, view(&app, (0, 2)).unwrap().center); + assert_eq!(app.ui.screen_mode, 2); +} + +#[test] +fn a_script_retains_view_identity_after_renumbering_and_reusing_a_window_number() { + let mut app = app_with(1); + app.session.execute("prefs.set", &json!({"key": "displayPrintSize", "value": false})).unwrap(); + let ctx = crate::testing::ui_context(); + frame(&mut app, &ctx, vec![]); + app.run("window.newWindow", json!({})).unwrap(); + frame(&mut app, &ctx, vec![]); + view_mut(&mut app, (0, 1)).unwrap().zoom = 1.0; + view_mut(&mut app, (0, 2)).unwrap().zoom = 2.0; + crate::script_runs::share_views(&mut app); + app.session.script_frames = true; + let source = "var vs = app.activeDocument.views, closed = vs[0], kept = vs[1]; alert('ready'); \ + vc.log(kept.zoom); kept.zoom = 5; \ + try { closed.zoom = 9; vc.log('retargeted'); } catch (e) { vc.log(e.message); } vc.log(vs.length);"; + app.session.execute("script.run", &json!({"source": source})).unwrap(); + assert!(app.session.script_pump().is_none()); + assert!(app.session.script_dialog().is_some(), "the script waits after retaining both views"); + close_window(&mut app, (0, 1)).unwrap(); + assert_eq!(windows(&app), [(0, 1)], "the remaining view is renumbered"); + new_window(&mut app).unwrap(); + view_mut(&mut app, (0, 2)).unwrap().zoom = 7.0; + let shared = crate::script_runs::share_views(&mut app); + assert!(app.session.script_answer(vectorcraft_engine::script::DialogAnswer::Ok)); + let report = app.session.script_pump().expect("the resumed script ends").unwrap(); + crate::script_runs::take_views(&mut app, &shared); + assert_eq!(report["log"], json!([2, "Stale view", 2])); + assert_eq!(view(&app, (0, 1)).unwrap().zoom, 5.0, "the retained view is the one that remained"); + assert_eq!(view(&app, (0, 2)).unwrap().zoom, 7.0, "the new view is not an earlier handle's target"); +} + #[test] fn a_press_in_another_documents_window_or_the_main_window_makes_its_document_current() { let mut app = app_with(3); diff --git a/crates/ui-egui/src/doc_windows/views.rs b/crates/ui-egui/src/doc_windows/views.rs index dda76952ee..4685d63d4f 100644 --- a/crates/ui-egui/src/doc_windows/views.rs +++ b/crates/ui-egui/src/doc_windows/views.rs @@ -94,6 +94,16 @@ pub(crate) fn view_mut(app: &mut VectorcraftApp, (i, n): Win) -> Option<&mut Vie app.canvas.windows.views.others.iter_mut().find(|o| o.uid == u && o.number == n).map(|o| &mut o.view) } +pub(crate) fn view_by_id_mut(app: &mut VectorcraftApp, (uid, id): (u64, u64)) -> Option<&mut View> { + if !app.session.documents().iter().any(|d| d.uid == uid) { + return None; + } + if let Some(i) = app.view_uids.iter().zip(&app.views).position(|(u, v)| *u == uid && v.runtime_id == id) { + return app.views.get_mut(i); + } + app.canvas.windows.views.others.iter_mut().find(|o| o.uid == uid && o.view.runtime_id == id).map(|o| &mut o.view) +} + /// Unfit every window's view: each fits where it shows next. pub(crate) fn unfit_all(app: &mut VectorcraftApp) { for v in &mut app.views { @@ -175,7 +185,7 @@ pub(crate) fn new_window(app: &mut VectorcraftApp) -> Result { let (Some(u), Some(view)) = (uid(app, i), app.views.get(i).copied()) else { return Err("no document open".into()) }; let number = numbers(app, i).last().copied().unwrap_or(n) + 1; let floats = super::floats(app, (i, n)); - app.canvas.windows.views.others.push(OtherView { uid: u, number, view }); + app.canvas.windows.views.others.push(OtherView { uid: u, number, view: view.copy_for_window() }); show_window(app, (i, number)); if floats { super::place(app, &[(i, number)]); diff --git a/crates/ui-egui/src/script_runs.rs b/crates/ui-egui/src/script_runs.rs index 11d6c7e599..32d5adf9a8 100644 --- a/crates/ui-egui/src/script_runs.rs +++ b/crates/ui-egui/src/script_runs.rs @@ -4,6 +4,7 @@ //! `alert`, `confirm`, `prompt` or a `File` or `Folder` file dialog, waits for the person's answer. use serde_json::{Value, json}; +use vectorcraft_engine::WindowView; use crate::VectorcraftApp; use crate::dialogs::script_run::{self, GrowthQuestion, ScriptFiles, ScriptNotice}; @@ -24,7 +25,10 @@ pub fn poll(app: &mut VectorcraftApp) { } let name = app.session.script_name().unwrap_or_default(); let startup = app.session.startup_script_running(); - let Some(result) = app.session.script_pump() else { + let shared = share_views(app); + let pumped = app.session.script_pump(); + take_views(app, &shared); + let Some(result) = pumped else { // A pump that started the next queued run shows the runs before it that could not start // in this frame: with none left running, the app may draw no next one. startup_failures(app); @@ -47,6 +51,54 @@ pub fn poll(app: &mut VectorcraftApp) { app.sync_views(); } +/// The running script reads each drawn window in `Document.views`, with its last drawn area. +/// The returned list contains those windows for [`take_views`]. +pub(crate) fn share_views(app: &mut VectorcraftApp) -> Vec<((u64, u64), WindowView)> { + // The view's zoom counts screen points before UI scaling; its area is in the interface's points. + let scaling = f64::from(app.ui_scaling()); + let mode = app.ui.screen_mode; + let shared: Vec<((u64, u64), WindowView)> = crate::doc_windows::windows(app) + .into_iter() + .filter_map(|window| { + let uid = app.session.documents().get(window.0)?.uid; + let v = crate::doc_windows::view(app, window)?; + if !v.fitted || v.rect.width() <= 0.0 || v.rect.height() <= 0.0 { + return None; + } + let print = app.print_ppi_of(Some(window)); + let baseline = crate::state::zoom_baseline(print); + let size = [f64::from(v.rect.width()) * scaling / baseline, f64::from(v.rect.height()) * scaling / baseline]; + let zoom = crate::state::zoom_display_percent(v.zoom, print) / 100.0; + Some(((uid, v.runtime_id), WindowView { center: v.center, zoom, zoom_baseline: baseline, rotation: v.rotation, size, screen_mode: mode })) + }) + .collect(); + app.session.window_views.clone_from(&shared); + shared +} + +/// Applies the zoom, center and screen mode a script assigned to the views from [`share_views`]. +pub(crate) fn take_views(app: &mut VectorcraftApp, shared: &[((u64, u64), WindowView)]) { + let (min, max) = WindowView::ZOOM_RANGE; + for (key, before) in shared { + let Some(now) = app.session.window_views.iter().find(|(k, _)| k == key).map(|(_, v)| *v) else { continue }; + if now == *before { + continue; + } + if let Some(v) = crate::doc_windows::view_by_id_mut(app, *key) { + if now.zoom != before.zoom { + v.zoom = (now.zoom * now.zoom_baseline).clamp(min, max); + } + v.center = now.center; + } + } + // The screen mode is the app's: a script that sets it on any view sets it on every view. + if let (Some((_, before)), Some((_, now))) = (shared.first(), app.session.window_views.first()) + && now.screen_mode != before.screen_mode + { + app.ui.screen_mode = now.screen_mode.min(3); + } +} + /// Shows each run `script.startup.run` queued that could not start ([`add_notes`]), and once the /// round has no run left, the round's notes again ([`end_round`]). fn startup_failures(app: &mut VectorcraftApp) { diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 39a62b1161..070a96b94c 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -59,6 +59,8 @@ pub struct RearrangePlacement { /// Per-document view (camera). #[derive(Clone, Copy, Debug, Serialize, Deserialize)] pub struct View { + #[serde(skip, default = "next_view_id")] + pub(crate) runtime_id: u64, /// The zoom (1.0 = 100%): points of the screen per document point, counted before /// Preferences › User Interface › UI Scaling, which scales the interface and not the art. /// [`Self::canvas`] gives the zoom in the interface's points. @@ -107,6 +109,7 @@ pub struct View { impl Default for View { fn default() -> Self { Self { + runtime_id: next_view_id(), zoom: 1.0, center: Point::new(306.0, 396.0), fitted: false, @@ -123,7 +126,16 @@ impl Default for View { } } +fn next_view_id() -> u64 { + static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); + NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed) +} + impl View { + pub(crate) fn copy_for_window(&self) -> Self { + Self { runtime_id: next_view_id(), ..*self } + } + /// The view a document opens at: the one it was saved with, else fitted on first display, on /// the artboard the opened file names as its active one ([`vectorcraft_doc::Document::opened_artboard`]), /// else the first. diff --git a/crates/ui-egui/src/tests/script_run.rs b/crates/ui-egui/src/tests/script_run.rs index 6b94d92d59..5ed11652a6 100644 --- a/crates/ui-egui/src/tests/script_run.rs +++ b/crates/ui-egui/src/tests/script_run.rs @@ -612,6 +612,28 @@ fn a_scripts_file_dialog_keeps_at_most_2048_picked_files() { finish(&mut app); } +#[test] +fn a_script_sees_the_window_and_sets_its_zoom_centre_and_screen_mode() { + let mut app = app(); + let before = { + let v = app.view_mut().unwrap(); + v.rect = egui::Rect::from_min_size(egui::pos2(0.0, 0.0), egui::vec2(600.0, 400.0)); + v.fitted = true; + v.zoom = 1.0; + *v + }; + app.session.script_frames = true; + let source = "var v = app.activeDocument.views[0]; vc.log(v.bounds[2] - v.bounds[0]); v.zoom = 2;\ + v.centerPoint = [10, 20]; v.screenMode = ScreenMode.FULLSCREEN;"; + app.run("script.run", json!({"source": source, "name": "v.js"})).unwrap(); + finish(&mut app); + let report = app.session.script_report().cloned().unwrap(); + assert_eq!(report["log"][0].as_f64(), Some(600.0), "the bounds use the physical camera scale"); + let now = *app.view().unwrap(); + assert!(now.zoom > before.zoom && now.center != before.center); + assert_eq!(app.ui.screen_mode, 2); +} + /// With two files picked, the file dialog lists them in a scrolled group named Picked files. #[test] fn a_scripts_file_dialog_lists_several_picked_files_in_a_named_group() { diff --git a/docs/mcp.md b/docs/mcp.md index dcf534cf3a..6d44ea3762 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2819,7 +2819,21 @@ other files through `$`: `DocumentPreviewMode.PixelPreview` throws an error that says it is not available yet, and no document is made. `showOptionsDialog` true throws `Dialog unavailable` with no document made. A `Document` (https://ai-scripting.docsforadobe.dev/jsobjref/Document/) has `name`, `width`, `height`, `rulerUnits`, `documentColorSpace`, `rulerOrigin`, `convertCoordinate(point, source, - destination)`, `pageItems` and `selection`. `pageItems` (https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/) + destination)`, `pageItems`, `selection` and `views`. `views` (https://ai-scripting.docsforadobe.dev/jsobjref/Views/) + lists each window, tab, or tiled pane the desktop app has drawn for the document, in view-number order. Each view + uses the size of the area it last drew the document in. A document the app has not drawn yet, and every document without a window (headless), + has none. `views` has `length`, `[i]` and `index(i)`. The view (https://ai-scripting.docsforadobe.dev/jsobjref/View/) has `typename`, + `parent`, `bounds` (`[left, top, right, bottom]` of the part of the document the canvas shows, the box around a + rotated canvas), `centerPoint`, `zoom` and `screenMode`, in the run's coordinate system. `zoom` is 1 at the window's + displayed 100%. With Display Print Size at 100% Zoom off, the range is 0.0313 to 640 (VectorCraft's own range). + With it enabled, the app divides these limits by the window's scale at 100% (the screen points per inch used for + that window divided by 72). A zoom outside that range, or a `centerPoint` outside the canvas after + coordinate conversion, throws a `RangeError`. A `centerPoint` that is not two numbers throws a `TypeError`. `screenMode` reads Normal as + `ScreenMode.MULTIWINDOW`, Full Screen Mode with Menu Bar as `ScreenMode.DESKTOP` and Full Screen Mode and + Presentation Mode as `ScreenMode.FULLSCREEN` (VectorCraft's own mapping); the screen mode is the app's, so setting it + on one view sets it on every view. Changing a view runs no command, adds + no undo step and stays when the run fails. A view object keeps its target when windows are renumbered. While its + document remains open, closing its window makes it throw `Stale view`. `pageItems` (https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/) lists every object in the document's layers, the objects inside groups, compound paths, blends, envelopes, repeats and intertwines included, and has `length`, `[i]`, `index(key)`, `getByName(name)` and `removeAll()`; `i in` either collection is true for each diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index f9fe4c08cb..c084421ee1 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1102,7 +1102,8 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - The control server writes each reply through a 64 KiB buffer. On Windows 11 it sends the 17 MB `document.inspect` reply of a document with 50,000 objects on one layer to a client over loopback in 0.09 s instead of 34 s. - Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`. - Scripts: `PageItem.tags` reads, adds, renames and deletes an object's tags, name and value pairs that the native file keeps, and `Document.tags` reads, renames and deletes the tags of every page item but adds none (its `add` throws; a script adds a tag through the page item's `tags`), as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Tags/ and https://ai-scripting.docsforadobe.dev/jsobjref/Tag/ describe them, through `object.tags` and the `object.tag.*` commands, at most 64 tags an object (`docs/mcp.md`). `crates/engine/src/tests/script_tags.rs`. - - Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). A script can check a member with `hasOwnProperty`, and can read a collection by name and name `activeDocument`, `documents` and `selection` without `app.` (https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/). `app.executeMenuCommand` runs the menu items Select All, Deselect, Group, Ungroup, Make and Release Clipping Mask, Make and Release Compound Path, and Fit to Artwork Bounds by their menu command names (https://community.adobe.com/questions-652/a-list-of-illustrator-menu-commands-we-can-call-from-javascript-769510, https://gist.github.com/shalakolee/df3246659d4289eb99149b9ed00a00ee). The `parent` of a page item at the top of a layer is a `Layer` with `name`, `typename` and `toString`. `Document.layers`, `Document.activeLayer`, paths, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. + - Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). A script can check a member with `hasOwnProperty`, and can read a collection by name and name `activeDocument`, `documents` and `selection` without `app.` (https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/). `app.executeMenuCommand` runs the menu items Select All, Deselect, Group, Ungroup, Make and Release Clipping Mask, Make and Release Compound Path, and Fit to Artwork Bounds by their menu command names (https://community.adobe.com/questions-652/a-list-of-illustrator-menu-commands-we-can-call-from-javascript-769510, https://gist.github.com/shalakolee/df3246659d4289eb99149b9ed00a00ee). The `parent` of a page item at the top of a layer is a `Layer` with `name`, `typename` and `toString`. + `Document.views` lists the document's drawn windows with their bounds, center, zoom and screen mode (https://ai-scripting.docsforadobe.dev/jsobjref/View/). Zoom follows each window's displayed percentage, including display density with Display Print Size at 100% Zoom enabled; bounds retain the physical camera scale. View objects keep their targets when windows are renumbered. View changes run no command, add no undo step, and remain when a script fails. A center outside the canvas after coordinate conversion throws a `RangeError`. `Document.layers`, `Document.activeLayer`, paths, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`. - Scripts: a document's variables and data sets, the variables its page items are bound to, Lock Variables, and importing and exporting a variable library through a `File`, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Variables/, https://ai-scripting.docsforadobe.dev/jsobjref/Variable/, https://ai-scripting.docsforadobe.dev/jsobjref/Datasets/ and https://ai-scripting.docsforadobe.dev/jsobjref/Dataset/ describe them; `variable.setBinding` binds one object for one slot, and `dataset.update {name}` updates a data set that is not the active one (`docs/mcp.md`). `crates/engine/src/tests/script_variables.rs`. - Scripts: Window › Script Console shows each run's `$.write` and `$.writeln` output, `vc.log` entries, uncaught error with the script's name, line and column, and a report of its time, host calls and slowest commands, keeping at most 2,048 lines and counting the lines it dropped. `script.run`'s report carries the same data, and `script.console`, `script.console.clear` and `ui.copyScriptConsole` read, clear and copy it. `crates/engine/src/tests/script_console.rs`. - Scripts: the status bar translates its own words around a failed run's error and the app's own error messages, and shows text the script threw itself (a value, an error it made, or an error whose name or message it changed) as it is, even when that text reads like one of the app's messages. `script.run`'s report gives `messageOrigin` (`script` or `built-in`), and the advice about objects other applications give their scripts follows only the app's own reference errors. VectorCraft's own rule. `crates/js/src/interp_tests.rs`, `crates/engine/src/tests/script_run.rs`, `crates/ui-egui/src/chrome/tests.rs`.