From 5986c0d94bf8603b82ca687029056020dd249eef Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 00:24:55 -0800 Subject: [PATCH 1/5] Scripts: Document.views gives the document's view with its bounds, center and zoom Document.views holds one view while the desktop app shows the document on its canvas: every document's while documents are under the tabs, and only the current document's while they are tiled or one floats in a window. Without a window (headless) it holds none. The view has typename, parent, bounds (the part of the document the canvas shows), centerPoint, zoom (1 is 100%, from 0.0313 to 640) and screenMode. Setting zoom, centerPoint or screenMode changes the window when the slice ends, runs no command and adds no undo step, and a run that fails keeps the change. The screen mode is the app's, so setting it on one view sets it on every view. A bad value throws and leaves the view as it was. Docs: docs/mcp.md, docs/target-app-parity.md. --- crates/engine/src/doc_state.rs | 30 ++++ crates/engine/src/lib.rs | 7 +- crates/engine/src/script/dom.rs | 191 +++++++++++++++++++++++- crates/engine/src/session/documents.rs | 1 + crates/engine/src/tests/script_dom.rs | 73 +++++++++ crates/ui-egui/src/doc_windows/tests.rs | 17 +++ crates/ui-egui/src/script_runs.rs | 51 ++++++- crates/ui-egui/src/tests/script_run.rs | 22 +++ docs/mcp.md | 12 +- docs/target-app-parity.md | 2 +- 10 files changed, 398 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/doc_state.rs b/crates/engine/src/doc_state.rs index cabc774737..6b76a8033d 100644 --- a/crates/engine/src/doc_state.rs +++ b/crates/engine/src/doc_state.rs @@ -3,6 +3,36 @@ 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: 1 is 100%. + pub zoom: 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 smallest and largest zoom the canvas shows. + pub const ZOOM_RANGE: (f64, f64) = (0.0313, 640.0); + + /// 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 e2e6430f1e..c0127177d3 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -311,6 +311,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 window of each document the desktop app shows, by [`DocState::uid`], which the app + /// keeps current while a script runs: a script reads it as `Document.views[0]`, and the app + /// takes the zoom, centre and screen mode a script sets. Empty without windows (headless). + /// View state: not saved, not undoable, and a run that fails keeps what it changed. + pub window_views: Vec<(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 @@ -432,7 +437,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_tool_edit}; -pub use doc_state::{DocState, OpenRows, RecalledSelection}; +pub use doc_state::{DocState, 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 cb901014b5..a6da0ff398 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, the object's id, and every read looks the @@ -25,6 +27,11 @@ //! - `app.activeDocument` with no document open throws `No active document`. //! - Assigning `Document.selection` takes one object, a list of them, `null` or `[]`; every object //! must be one of that document's that can be selected, or nothing changes. +//! - `Document.views` holds one view while the desktop app gives the document's window +//! ([`crate::Session::window_views`]), and none without one. The screen mode is the app's: +//! setting it on one view sets it on every view. Its `zoom` is 1 at 100%, from 0.0313 to 640; `screenMode` reads +//! Presentation Mode as `ScreenMode.FULLSCREEN`. Changing a view runs no command, is not +//! undoable and stays when the run fails. //! - Members the help pages list that are not here yet throw an error that says so. use std::cell::{Cell, RefCell}; @@ -37,7 +44,7 @@ use vectorcraft_geom::{Point, Rect}; use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostItem, HostMember, Realm, RunError, host_ref, host_ref_parts}; 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}; /// The error for a member read or called with no document open. pub const NO_ACTIVE_DOCUMENT: &str = "No active document"; @@ -47,6 +54,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. @@ -1214,6 +1223,154 @@ 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") +} + +/// The window of `doc`, when the app shows one. +fn window_of(h: &Host, doc: Doc) -> Option { + h.session.borrow().window_views.iter().find(|(uid, _)| *uid == doc.uid).map(|(_, v)| *v) +} + +fn views_length(h: &Host, a: &[Data]) -> Answer { + let doc = views_doc(h, a)?; + Ok(num(if window_of(h, doc).is_some() { 1.0 } else { 0.0 })) +} + +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_at(h: &Host, a: &[Data]) -> Answer { + let doc = views_doc(h, a)?; + let first = matches!(arg(a, 1), Data::Number(n) if *n == 0.0); + Ok(if first && window_of(h, doc).is_some() { host_ref("View", &[float(h.run), float(doc.uid)]) } else { Data::Undefined }) +} + +/// `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, WindowView), HostError> { + let doc = doc_of(h, arg(a, 0), "View")?; + let v = window_of(h, doc).ok_or_else(|| HostError::Error(STALE_VIEW.into()))?; + Ok((doc, 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, f: impl FnOnce(&mut WindowView)) -> Answer { + let mut s = h.session.borrow_mut(); + let v = s.window_views.iter_mut().find(|(uid, _)| *uid == doc.uid).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)) +} + +/// `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, _) = 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)))?; + set_window(h, doc, |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, _) = this_view(h, a)?; + let z = number(arg(a, 1), "zoom")?; + let (min, max) = WindowView::ZOOM_RANGE; + if !(min..=max).contains(&z) { + return Err(HostError::Range(format!("zoom must be from {min} to {max}"))); + } + set_window(h, doc, |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`: `null` when nothing is selected, otherwise a new list of /// the selected objects. fn selection_of(h: &Host, uid: u64) -> Answer { @@ -1913,6 +2070,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"]), @@ -1991,13 +2149,38 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), ("convertCoordinate", method(l, doc_convert)), ("pageItems", get(l, doc_page_items)), ("selection", property(l, doc_selection, doc_set_selection)), + ("views", get(l, doc_views)), ]); 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)), ); classes.push(class("Document", None, document, None)); + classes.push(class( + "Views", + None, + named(vec![ + ("typename", get(l, views_typename)), + ("length", get(l, views_length)), + ("parent", get(l, views_parent)), + ("index", method(l, views_index)), + ]), + Some(function(l, views_at)), + )); + classes.push(class( + "View", + None, + named(vec![ + ("typename", get(l, view_typename)), + ("parent", get(l, view_parent)), + ("bounds", get(l, view_bounds)), + ("centerPoint", property(l, view_center, view_set_center)), + ("zoom", property(l, view_zoom, view_set_zoom)), + ("screenMode", property(l, view_screen_mode, view_set_screen_mode)), + ]), + None, + )); classes.push(class( "PageItems", None, diff --git a/crates/engine/src/session/documents.rs b/crates/engine/src/session/documents.rs index 61dbdb4491..24144f5f17 100644 --- a/crates/engine/src/session/documents.rs +++ b/crates/engine/src/session/documents.rs @@ -166,6 +166,7 @@ impl Session { script_frames: false, 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 60e3a71521..174ec1a67a 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -192,6 +192,79 @@ 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, 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, 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);"; + assert_eq!(log(&mut s, none), vec![json!(0), json!(true)], "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[d.pageItems.length - 1];\ + 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])); +} + +#[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, 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. + for bad in ["v.zoom = 0;", "v.zoom = 1000;", "v.zoom = '2';", "v.centerPoint = [1];", "v.screenMode = 'FULLSCREEN';"] { + failure(&mut s, &format!("var v = app.activeDocument.views[0]; {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 page_item_properties_join_one_undo_step() { let (mut s, a, _) = doc(); diff --git a/crates/ui-egui/src/doc_windows/tests.rs b/crates/ui-egui/src/doc_windows/tests.rs index 7fede442da..d8e58d65a4 100644 --- a/crates/ui-egui/src/doc_windows/tests.rs +++ b/crates/ui-egui/src/doc_windows/tests.rs @@ -143,6 +143,23 @@ fn float_in_window_moves_the_current_document_out_of_the_tabs() { assert_eq!(app.ui.floating.len(), 1); } +#[test] +fn a_script_sees_a_view_only_for_windows_of_the_canvass_size() { + let mut app = app_with(3); + let ctx = egui::Context::default(); + frame(&mut app, &ctx, vec![]); + let uids: Vec = app.session.documents().iter().map(|d| d.uid).collect(); + let shared = |app: &mut VectorcraftApp| { + app.views.iter_mut().for_each(|v| v.fitted = true); + crate::script_runs::share_views(app).into_iter().map(|(uid, _)| uid).collect::>() + }; + assert_eq!(shared(&mut app), uids, "tabbed documents share the canvas's size"); + app.run("window.arrange.floatInWindow", json!({})).unwrap(); + frame(&mut app, &ctx, vec![]); + frame(&mut app, &ctx, vec![]); + assert_eq!(shared(&mut app), [uids[2]], "only the current document's window holds the canvas"); +} + #[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/script_runs.rs b/crates/ui-egui/src/script_runs.rs index 7bc52f35b1..b01d893003 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::json; +use vectorcraft_engine::WindowView; use crate::VectorcraftApp; use crate::dialogs::script_run; @@ -21,7 +22,10 @@ pub fn poll(app: &mut VectorcraftApp) { } let name = app.session.script_name().unwrap_or_default(); let cursor_settings = (app.session.caps_lock, app.session.prefs.use_precise_cursors); - 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 { // The app draws no more frames while the run waits: its question opens in this one. ask(app); return; @@ -45,6 +49,51 @@ pub fn poll(app: &mut VectorcraftApp) { app.sync_views(); } +/// Gives each document whose window has the canvas's size its view, which a running script reads +/// as `Document.views`: every document's while the documents are under the tabs, and only the +/// current document's, whose window holds the canvas, while they are tiled or a document floats in +/// a window of its own. A document without one gets none. → the views given, for [`take_views`]. +pub(crate) fn share_views(app: &mut VectorcraftApp) -> Vec<(u64, WindowView)> { + let ui_zoom = f64::from(app.canvas_ui_zoom); + let size = app.canvas_rect.map(|r| [f64::from(r.width()) * ui_zoom, f64::from(r.height()) * ui_zoom]); + let mode = app.ui.screen_mode; + let tabbed = app.canvas.panes.last.is_empty() && app.ui.floating.is_empty(); + let current = app.session.active().map(|d| d.uid); + let shared: Vec<(u64, WindowView)> = match size { + Some(size) => app + .view_uids + .iter() + .zip(&app.views) + .filter(|(uid, v)| v.fitted && (tabbed || current == Some(**uid))) + .map(|(uid, v)| (*uid, WindowView { center: v.center, zoom: v.zoom, rotation: v.rotation, size, screen_mode: mode })) + .collect(), + None => vec![], + }; + app.session.window_views.clone_from(&shared); + shared +} + +/// Takes the zoom, centre and screen mode a script gave the views [`share_views`] gave. +pub(crate) fn take_views(app: &mut VectorcraftApp, shared: &[(u64, WindowView)]) { + let (min, max) = WindowView::ZOOM_RANGE; + for (uid, before) in shared { + let Some(now) = app.session.window_views.iter().find(|(u, _)| u == uid).map(|(_, v)| *v) else { continue }; + if now == *before { + continue; + } + if let Some(v) = app.view_uids.iter().position(|u| u == uid).and_then(|k| app.views.get_mut(k)) { + v.zoom = now.zoom.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); + } +} + /// Opens what the run waits at, once no other dialog is open: the script's own dialog, or the /// question about its growth. Closes the script's dialog when the run no longer waits at it. /// → true while the run waits. diff --git a/crates/ui-egui/src/tests/script_run.rs b/crates/ui-egui/src/tests/script_run.rs index fee27caa13..22db45fde5 100644 --- a/crates/ui-egui/src/tests/script_run.rs +++ b/crates/ui-egui/src/tests/script_run.rs @@ -640,6 +640,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(); + app.canvas_rect = Some(egui::Rect::from_min_size(egui::pos2(0.0, 0.0), egui::vec2(600.0, 400.0))); + let before = { + let v = app.view_mut().unwrap(); + 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 view is as wide as the canvas at 100%"); + let now = *app.view().unwrap(); + assert!(now.zoom > before.zoom && now.center != before.center); + assert_eq!(app.ui.screen_mode, 2); +} + #[test] fn a_new_app_shows_the_warning_by_default() { assert!(Session::new().prefs.show_external_script_warning); diff --git a/docs/mcp.md b/docs/mcp.md index 4685f408d7..a82e6b349d 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2642,7 +2642,17 @@ app through the global object `vc`, and writes to the Script Console and runs ot `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/) + holds one view while the document's window is the desktop app's canvas: every document's while the documents are + under the tabs, and only the current document's while they are tiled or one floats in a window of its own. Other + documents, and every document without a window (headless), have 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 100% and goes + from 0.0313 to 640 (VectorCraft's own range); a zoom outside it throws a `RangeError`. `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 whose document no longer has a window throws `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 3b252b56a6..1f1f563b16 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1024,7 +1024,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur - Synthetic input validates complete gestures before queue mutation: at most 256 drag steps, 16 clicks and 1,024 pending events; up to 64 control requests per frame, with later requests retained for the next frame (#1709). - 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: 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`). Layers, 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`). `Document.views` gives the document's window as a view with its bounds, center, zoom and screen mode, which a script can change (https://ai-scripting.docsforadobe.dev/jsobjref/View/). Layers, paths, type and the other classes are not there yet. `crates/engine/src/tests/script_dom.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`. - Scripts: the `$` object has the other members the Dollar object page lists (https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/), from `$.about()` to `$.version`, and scripts have the global `localize(object, ...values)` (https://extendscript.docsforadobe.dev/extendscript-tools-features/localizing-extendscript-strings/), `toSource(value)` and `Object.prototype.toSource()`. Each run starts with the interface's locale, and what a script changes in `$` lasts only for that run. `crates/engine/src/tests/script_dollar.rs`, `crates/js/src/extension_tests.rs`. From 98a6ed7fc759688b4e90a8aca59f37bb7d60204b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 01:06:23 -0800 Subject: [PATCH 2/5] Scripts: each view is sized as the area its document was last drawn in Since the move to the craft UI framework each document's view keeps the area it last drew the document in, so Document.views now gives a view for every document the app has drawn, in a tab, a tiled pane or a floating window, sized as that area. A document the app has not drawn yet has no view. View and Views also get toString, as the other script objects have. --- crates/engine/src/script/dom.rs | 2 ++ crates/engine/src/tests/script_dom.rs | 4 ++- crates/ui-egui/src/doc_windows/tests.rs | 17 ++++++------- crates/ui-egui/src/script_runs.rs | 33 +++++++++++-------------- crates/ui-egui/src/tests/script_run.rs | 2 +- docs/mcp.md | 6 ++--- 6 files changed, 32 insertions(+), 32 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 9ddde38e80..9659514491 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -2305,6 +2305,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), ("length", get(l, views_length)), ("parent", get(l, views_parent)), ("index", method(l, views_index)), + ("toString", class_text("Views")), ]), Some(function(l, views_at)), )); @@ -2318,6 +2319,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), ("centerPoint", property(l, view_center, view_set_center)), ("zoom", property(l, view_zoom, view_set_zoom)), ("screenMode", property(l, view_screen_mode, view_set_screen_mode)), + ("toString", class_text("View")), ]), None, )); diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index f8aa54db37..2721923650 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -222,7 +222,7 @@ fn the_view_shows_the_part_of_the_document_its_window_shows() { 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[d.pageItems.length - 1];\ + 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);", ); @@ -234,6 +234,8 @@ fn the_view_shows_the_part_of_the_document_its_window_shows() { 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]")]); } #[test] diff --git a/crates/ui-egui/src/doc_windows/tests.rs b/crates/ui-egui/src/doc_windows/tests.rs index a985c261a6..cf21effb94 100644 --- a/crates/ui-egui/src/doc_windows/tests.rs +++ b/crates/ui-egui/src/doc_windows/tests.rs @@ -191,20 +191,19 @@ fn float_in_window_moves_the_current_document_out_of_the_tabs() { } #[test] -fn a_script_sees_a_view_only_for_windows_of_the_canvass_size() { +fn a_script_sees_each_window_at_its_own_size() { let mut app = app_with(3); - let ctx = egui::Context::default(); + let ctx = crate::testing::ui_context(); frame(&mut app, &ctx, vec![]); - let uids: Vec = app.session.documents().iter().map(|d| d.uid).collect(); - let shared = |app: &mut VectorcraftApp| { - app.views.iter_mut().for_each(|v| v.fitted = true); - crate::script_runs::share_views(app).into_iter().map(|(uid, _)| uid).collect::>() - }; - assert_eq!(shared(&mut app), uids, "tabbed documents share the canvas's size"); app.run("window.arrange.floatInWindow", json!({})).unwrap(); frame(&mut app, &ctx, vec![]); frame(&mut app, &ctx, vec![]); - assert_eq!(shared(&mut app), [uids[2]], "only the current document's window holds the canvas"); + 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] diff --git a/crates/ui-egui/src/script_runs.rs b/crates/ui-egui/src/script_runs.rs index e1d2e0b0de..14364ad861 100644 --- a/crates/ui-egui/src/script_runs.rs +++ b/crates/ui-egui/src/script_runs.rs @@ -40,26 +40,23 @@ pub fn poll(app: &mut VectorcraftApp) { app.sync_views(); } -/// Gives each document whose window has the canvas's size its view, which a running script reads -/// as `Document.views`: every document's while the documents are under the tabs, and only the -/// current document's, whose window holds the canvas, while they are tiled or a document floats in -/// a window of its own. A document without one gets none. → the views given, for [`take_views`]. +/// Gives each document whose view has been drawn its view, which a running script reads as +/// `Document.views`, with the size of the area that view last drew its art in. A document without +/// one gets none. → the views given, for [`take_views`]. pub(crate) fn share_views(app: &mut VectorcraftApp) -> Vec<(u64, WindowView)> { - let ui_zoom = f64::from(app.canvas_ui_zoom); - let size = app.canvas_rect.map(|r| [f64::from(r.width()) * ui_zoom, f64::from(r.height()) * ui_zoom]); + // 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 tabbed = app.canvas.panes.last.is_empty() && app.ui.floating.is_empty(); - let current = app.session.active().map(|d| d.uid); - let shared: Vec<(u64, WindowView)> = match size { - Some(size) => app - .view_uids - .iter() - .zip(&app.views) - .filter(|(uid, v)| v.fitted && (tabbed || current == Some(**uid))) - .map(|(uid, v)| (*uid, WindowView { center: v.center, zoom: v.zoom, rotation: v.rotation, size, screen_mode: mode })) - .collect(), - None => vec![], - }; + let shared: Vec<(u64, WindowView)> = app + .view_uids + .iter() + .zip(&app.views) + .filter(|(_, v)| v.fitted && v.rect.width() > 0.0 && v.rect.height() > 0.0) + .map(|(uid, v)| { + let size = [f64::from(v.rect.width()) * scaling, f64::from(v.rect.height()) * scaling]; + (*uid, WindowView { center: v.center, zoom: v.zoom, rotation: v.rotation, size, screen_mode: mode }) + }) + .collect(); app.session.window_views.clone_from(&shared); shared } diff --git a/crates/ui-egui/src/tests/script_run.rs b/crates/ui-egui/src/tests/script_run.rs index 1c8406cdb9..28a3c32649 100644 --- a/crates/ui-egui/src/tests/script_run.rs +++ b/crates/ui-egui/src/tests/script_run.rs @@ -469,9 +469,9 @@ fn a_scripts_file_dialog_keeps_at_most_2048_picked_files() { #[test] fn a_script_sees_the_window_and_sets_its_zoom_centre_and_screen_mode() { let mut app = app(); - app.canvas_rect = Some(egui::Rect::from_min_size(egui::pos2(0.0, 0.0), egui::vec2(600.0, 400.0))); 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 diff --git a/docs/mcp.md b/docs/mcp.md index a9f1575d6e..a62288107f 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2694,9 +2694,9 @@ app through the global object `vc`, and writes to the Script Console and runs ot `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`, `selection` and `views`. `views` (https://ai-scripting.docsforadobe.dev/jsobjref/Views/) - holds one view while the document's window is the desktop app's canvas: every document's while the documents are - under the tabs, and only the current document's while they are tiled or one floats in a window of its own. Other - documents, and every document without a window (headless), have none. `views` has `length`, `[i]` and `index(i)`. The view (https://ai-scripting.docsforadobe.dev/jsobjref/View/) has `typename`, + holds one view once the desktop app has drawn the document in a window, a tab or a tiled pane, sized as 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 100% and goes from 0.0313 to 640 (VectorCraft's own range); a zoom outside it throws a `RangeError`. `screenMode` reads Normal as From d97786358d6d2e4c5d50c5cc25347cb2a84c2327 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 13:57:25 -0800 Subject: [PATCH 3/5] Tests: list View, Views and ScreenMode in the script host inventory Document.views is read-only, so its row no longer lists a setter. --- crates/engine/tests/it/script_host_vs_scriptcheck.rs | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/crates/engine/tests/it/script_host_vs_scriptcheck.rs b/crates/engine/tests/it/script_host_vs_scriptcheck.rs index 25067f5c0e..5fae9bb86e 100644 --- a/crates/engine/tests/it/script_host_vs_scriptcheck.rs +++ b/crates/engine/tests/it/script_host_vs_scriptcheck.rs @@ -77,7 +77,7 @@ 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= ZOrderMethod", + Documents ElementPlacement Layer PageItem PageItems RulerUnits ScreenMode selection selection= View Views ZOrderMethod", ), ("Application.", "prototype"), ( @@ -101,8 +101,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= 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"), @@ -130,6 +134,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"), ]; From 165423a9c0f65a1158dc83f1b953246bbb8ff93d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 22:20:39 -0800 Subject: [PATCH 4/5] Scripts: Views and View toString refuse a stale collection or view A collection or view kept by a named engine from an earlier run now throws on toString() as typename does. The tests also check that `k in document.views` is false for an index or name with no view, and the error type of each bad view value. docs/mcp.md says a centerPoint outside the canvas throws a RangeError. --- crates/engine/src/script/dom.rs | 14 ++++++++++++-- crates/engine/src/tests/script_dom.rs | 24 ++++++++++++++++++++---- docs/mcp.md | 3 ++- 3 files changed, 34 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index 9659514491..96df496731 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -1299,6 +1299,11 @@ fn views_parent(h: &Host, a: &[Data]) -> Answer { 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 first = matches!(arg(a, 1), Data::Number(n) if *n == 0.0); @@ -1352,6 +1357,11 @@ fn view_parent(h: &Host, a: &[Data]) -> Answer { 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())) @@ -2305,7 +2315,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), ("length", get(l, views_length)), ("parent", get(l, views_parent)), ("index", method(l, views_index)), - ("toString", class_text("Views")), + ("toString", method(l, views_to_string)), ]), Some(function(l, views_at)), )); @@ -2319,7 +2329,7 @@ pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), ("centerPoint", property(l, view_center, view_set_center)), ("zoom", property(l, view_zoom, view_set_zoom)), ("screenMode", property(l, view_screen_mode, view_set_screen_mode)), - ("toString", class_text("View")), + ("toString", method(l, view_to_string)), ]), None, )); diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 2721923650..15e82aafda 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -213,8 +213,8 @@ fn shown(s: &Session) -> Option { #[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);"; - assert_eq!(log(&mut s, none), vec![json!(0), json!(true)], "a document without a window has no view"); + 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(); @@ -236,6 +236,13 @@ fn the_view_shows_the_part_of_the_document_its_window_shows() { 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] @@ -259,8 +266,17 @@ fn setting_the_zoom_changes_the_view_without_an_undo_step() { 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. - for bad in ["v.zoom = 0;", "v.zoom = 1000;", "v.zoom = '2';", "v.centerPoint = [1];", "v.screenMode = 'FULLSCREEN';"] { - failure(&mut s, &format!("var v = app.activeDocument.views[0]; {bad}")); + 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. diff --git a/docs/mcp.md b/docs/mcp.md index edc5818d49..89ba0d4a99 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2755,7 +2755,8 @@ app through the global object `vc`, and writes to the Script Console and runs ot 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 100% and goes - from 0.0313 to 640 (VectorCraft's own range); a zoom outside it throws a `RangeError`. `screenMode` reads Normal as + from 0.0313 to 640 (VectorCraft's own range); a zoom outside it, or a `centerPoint` outside the canvas, throws a + `RangeError`, and 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 From 80a24bf8a6b2bc6f7e211abceb376c757757d463 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 09:36:45 -0800 Subject: [PATCH 5/5] Use each window's displayed zoom in script views --- crates/engine/src/doc_state.rs | 12 +++- crates/engine/src/script/dom.rs | 8 ++- crates/engine/src/tests/script_dom.rs | 9 ++- crates/ui-egui/src/doc_windows/tests.rs | 78 +++++++++++++++++++++++++ crates/ui-egui/src/script_runs.rs | 13 +++-- crates/ui-egui/src/tests/script_run.rs | 2 +- docs/mcp.md | 6 +- docs/target-app-parity.md | 2 +- 8 files changed, 116 insertions(+), 14 deletions(-) diff --git a/crates/engine/src/doc_state.rs b/crates/engine/src/doc_state.rs index a25bb6ee83..98cdda5b92 100644 --- a/crates/engine/src/doc_state.rs +++ b/crates/engine/src/doc_state.rs @@ -8,8 +8,10 @@ use super::{Arc, Document, NodeId, NodeKind, Selection, Value, cmd, file_access} pub struct WindowView { /// The document point at the centre of the canvas. pub center: vectorcraft_geom::Point, - /// The zoom: 1 is 100%. + /// 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. @@ -20,9 +22,15 @@ pub struct WindowView { } impl WindowView { - /// The smallest and largest zoom the canvas shows. + /// 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 { diff --git a/crates/engine/src/script/dom.rs b/crates/engine/src/script/dom.rs index a5fda3464e..578d88d48a 100644 --- a/crates/engine/src/script/dom.rs +++ b/crates/engine/src/script/dom.rs @@ -46,7 +46,9 @@ //! - `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 100%, from 0.0313 to 640; `screenMode` reads +//! 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`. @@ -1457,9 +1459,9 @@ fn view_zoom(h: &Host, a: &[Data]) -> Answer { } fn view_set_zoom(h: &Host, a: &[Data]) -> Answer { - let (doc, id, _) = this_view(h, a)?; + let (doc, id, v) = this_view(h, a)?; let z = number(arg(a, 1), "zoom")?; - let (min, max) = WindowView::ZOOM_RANGE; + let (min, max) = v.zoom_range(); if !(min..=max).contains(&z) { return Err(HostError::Range(format!("zoom must be from {min} to {max}"))); } diff --git a/crates/engine/src/tests/script_dom.rs b/crates/engine/src/tests/script_dom.rs index 33a047d887..de87e603a3 100644 --- a/crates/engine/src/tests/script_dom.rs +++ b/crates/engine/src/tests/script_dom.rs @@ -195,7 +195,14 @@ fn ruler_origin_round_trips_without_moving_art() { /// 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, rotation: 0.0, size: [600.0, 400.0], screen_mode: 0 } + 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`. diff --git a/crates/ui-egui/src/doc_windows/tests.rs b/crates/ui-egui/src/doc_windows/tests.rs index 6325b89787..5033868701 100644 --- a/crates/ui-egui/src/doc_windows/tests.rs +++ b/crates/ui-egui/src/doc_windows/tests.rs @@ -206,9 +206,86 @@ fn a_script_sees_each_window_at_its_own_size() { 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(); @@ -243,6 +320,7 @@ fn a_script_lists_and_changes_each_view_of_one_document() { #[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(); diff --git a/crates/ui-egui/src/script_runs.rs b/crates/ui-egui/src/script_runs.rs index 98ebd1f051..7c19c580c7 100644 --- a/crates/ui-egui/src/script_runs.rs +++ b/crates/ui-egui/src/script_runs.rs @@ -54,15 +54,18 @@ pub(crate) fn share_views(app: &mut VectorcraftApp) -> Vec<((u64, u64), WindowVi if !v.fitted || v.rect.width() <= 0.0 || v.rect.height() <= 0.0 { return None; } - let size = [f64::from(v.rect.width()) * scaling, f64::from(v.rect.height()) * scaling]; - Some(((uid, v.runtime_id), WindowView { center: v.center, zoom: v.zoom, rotation: v.rotation, size, screen_mode: mode })) + 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 } -/// Takes the zoom, centre and screen mode a script gave the views [`share_views`] gave. +/// 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 { @@ -71,7 +74,9 @@ pub(crate) fn take_views(app: &mut VectorcraftApp, shared: &[((u64, u64), Window continue; } if let Some(v) = crate::doc_windows::view_by_id_mut(app, *key) { - v.zoom = now.zoom.clamp(min, max); + if now.zoom != before.zoom { + v.zoom = (now.zoom * now.zoom_baseline).clamp(min, max); + } v.center = now.center; } } diff --git a/crates/ui-egui/src/tests/script_run.rs b/crates/ui-egui/src/tests/script_run.rs index 4db1df9f39..bba49c669e 100644 --- a/crates/ui-egui/src/tests/script_run.rs +++ b/crates/ui-egui/src/tests/script_run.rs @@ -522,7 +522,7 @@ fn a_script_sees_the_window_and_sets_its_zoom_centre_and_screen_mode() { 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 view is as wide as the canvas at 100%"); + 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); diff --git a/docs/mcp.md b/docs/mcp.md index be9717d940..790b34c018 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -2792,8 +2792,10 @@ other files through `$`: 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 100% and goes - from 0.0313 to 640 (VectorCraft's own range). A zoom outside it, or a `centerPoint` outside the canvas after + 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 diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index fc88749a13..4aa3945b0a 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -1056,7 +1056,7 @@ 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: 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/). 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`. + `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: 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`. - Scripts: the `$` object has the other members the Dollar object page lists (https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/), from `$.about()` to `$.version`, and scripts have the global `localize(object, ...values)` (https://extendscript.docsforadobe.dev/extendscript-tools-features/localizing-extendscript-strings/), `toSource(value)` and `Object.prototype.toSource()`. Each run starts with the interface's locale, and what a script changes in `$` lasts only for that run. `crates/engine/src/tests/script_dollar.rs`, `crates/js/src/extension_tests.rs`.