mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-29 01:34:29 +01:00
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.
This commit is contained in:
1 parent
dc9adb195d
commit
5986c0d94b
10 files changed
+398
-8
No files matched your search
@@ -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 {
|
||||
|
||||
@@ -311,6 +311,11 @@ pub struct Session {
|
||||
pub(crate) script_high_water: std::collections::HashMap<u64, u64>,
|
||||
/// 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;
|
||||
|
||||
@@ -2,8 +2,10 @@
|
||||
//! them, as the help pages <https://ai-scripting.docsforadobe.dev/jsobjref/Application/>,
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/Documents/>,
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/Document/>,
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/> and
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/> describe them.
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/>,
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/>,
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/Views/> and
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/View/> 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, HostError> {
|
||||
doc_of(h, arg(a, 0), "Views")
|
||||
}
|
||||
|
||||
/// The window of `doc`, when the app shows one.
|
||||
fn window_of(h: &Host, doc: Doc) -> Option<WindowView> {
|
||||
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,
|
||||
|
||||
@@ -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"),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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<WindowView> {
|
||||
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();
|
||||
|
||||
@@ -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<u64> = 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::<Vec<u64>>()
|
||||
};
|
||||
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);
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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);
|
||||
|
||||
+11
-1
@@ -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
|
||||
|
||||
@@ -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`.
|
||||
|
||||
Reference in new issue
Block a user