mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-29 01:34:29 +01:00
Merge pull request #9291 from dotCooCoo/feat/scripts-document-views
Scripts: Document.views exposes each drawn document window
This commit is contained in:
14 files changed
+680
-12
No files matched your search
@@ -3,6 +3,44 @@ use super::history::{History, HistoryEntry};
|
||||
use super::interaction::{Interaction, LastTransform, UndoGroup};
|
||||
use super::{Arc, Document, NodeId, NodeKind, Selection, Value, cmd, file_access};
|
||||
|
||||
/// A document's window as the desktop app shows it ([`crate::Session::window_views`]).
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct WindowView {
|
||||
/// The document point at the centre of the canvas.
|
||||
pub center: vectorcraft_geom::Point,
|
||||
/// The zoom is 1 at the window's displayed 100%.
|
||||
pub zoom: f64,
|
||||
/// The camera uses this scale at the window's displayed 100%.
|
||||
pub zoom_baseline: f64,
|
||||
/// The view's rotation in degrees, clockwise on screen.
|
||||
pub rotation: f64,
|
||||
/// The canvas's width and height in document points at a zoom of 1.
|
||||
pub size: [f64; 2],
|
||||
/// View › Screen Mode: 0 Normal, 1 Full Screen Mode with Menu Bar, 2 Full Screen Mode, 3
|
||||
/// Presentation Mode (`view.screenMode`).
|
||||
pub screen_mode: u8,
|
||||
}
|
||||
|
||||
impl WindowView {
|
||||
/// The physical camera scale stays within these limits.
|
||||
pub const ZOOM_RANGE: (f64, f64) = (0.0313, 640.0);
|
||||
|
||||
/// `zoom_range` returns this window's allowed displayed zoom ratios.
|
||||
pub fn zoom_range(&self) -> (f64, f64) {
|
||||
let (min, max) = Self::ZOOM_RANGE;
|
||||
(min / self.zoom_baseline, max / self.zoom_baseline)
|
||||
}
|
||||
|
||||
/// The part of the document the canvas shows: the box around its four corners, which a
|
||||
/// rotated view turns.
|
||||
pub fn visible(&self) -> vectorcraft_geom::Rect {
|
||||
let (sin, cos) = self.rotation.to_radians().sin_cos();
|
||||
let (w, h) = (self.size[0] / self.zoom / 2.0, self.size[1] / self.zoom / 2.0);
|
||||
let (x, y) = (w * cos.abs() + h * sin.abs(), w * sin.abs() + h * cos.abs());
|
||||
vectorcraft_geom::Rect::new(self.center.x - x, self.center.y - y, self.center.x + x, self.center.y + y)
|
||||
}
|
||||
}
|
||||
|
||||
/// Per-document editing state.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct DocState {
|
||||
|
||||
@@ -375,6 +375,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 desktop app supplies each window by (document uid, runtime window identity) while a
|
||||
/// script runs. Scripts read them as `Document.views`, and the app applies their zoom, center,
|
||||
/// and screen mode. This list is empty without windows (headless).
|
||||
/// View state: not saved, not undoable, and a run that fails keeps what it changed.
|
||||
pub window_views: Vec<((u64, u64), WindowView)>,
|
||||
/// Write recovery copies of the unsaved documents before a run, and don't start without them.
|
||||
pub script_copy_first: bool,
|
||||
/// While the active tool's actions run: their commands aren't "a command from outside the
|
||||
@@ -499,7 +504,7 @@ pub(crate) use command_sets::SELECTS_GIVEN_IDS;
|
||||
#[cfg(test)]
|
||||
use command_sets::given_ids;
|
||||
pub use command_sets::{DRAWS_SHAPE, FIT_ACTIVE_ARTBOARD, ON_ACTIVE_ARTBOARD, waits_for_plugin_loads, waits_for_tool_edit};
|
||||
pub use doc_state::{DocState, LayersReveal, OpenRows, RecalledSelection};
|
||||
pub use doc_state::{DocState, LayersReveal, OpenRows, RecalledSelection, WindowView};
|
||||
pub use error::{EngineError, READ_ONLY_LOCATION, Result, SCRIPT_BUSY};
|
||||
#[cfg(test)]
|
||||
use history::history_budget_for;
|
||||
|
||||
@@ -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 and layers, the object's id and the document's
|
||||
@@ -46,6 +48,15 @@
|
||||
//! must be one of that document's that can be selected, or nothing changes. `undefined` throws.
|
||||
//! - `controlBounds` is the visible bounds, widened to take in the direction points of every path
|
||||
//! in the object.
|
||||
//! - `Document.views` holds the document's drawn windows ([`crate::Session::window_views`]),
|
||||
//! in view-number order, and none without one. View objects keep their window's identity when
|
||||
//! windows are renumbered. The screen mode is the app's:
|
||||
//! setting it on one view sets it on every view. Its `zoom` is 1 at the window's displayed 100%;
|
||||
//! the physical camera scale ranges from 0.0313 to 640, and the allowed zoom ratios account for
|
||||
//! the window's display density with Display Print Size at 100% Zoom enabled. `screenMode` reads
|
||||
//! Presentation Mode as `ScreenMode.FULLSCREEN`. Changing a view runs no command, is not
|
||||
//! undoable and stays when the run fails.
|
||||
//! A center outside the canvas after coordinate conversion throws a `RangeError`.
|
||||
//! - Members the help pages list that are not here yet throw an error that says so, and `reflect`
|
||||
//! leaves them out.
|
||||
//! - Assigning `hidden`, `locked`, `opacity`, `position`, `left`, `top`, `width` or `height` to an
|
||||
@@ -76,7 +87,7 @@ use vectorcraft_js::{
|
||||
};
|
||||
|
||||
use super::{HISTORY_LOST, Host, Link, Savepoint, command, command_value, current, data_size};
|
||||
use crate::{DocState, Document, NodeId, NodeKind, Session};
|
||||
use crate::{DocState, Document, NodeId, NodeKind, Session, WindowView};
|
||||
|
||||
mod tags;
|
||||
mod variables;
|
||||
@@ -102,6 +113,8 @@ pub const STALE_ITEM: &str = "Stale page item";
|
||||
pub const STALE_DOCUMENT: &str = "Stale document";
|
||||
/// The error of `index` and `getByName` when nothing matches.
|
||||
pub const NOT_FOUND: &str = "Not found";
|
||||
/// The error for a view whose document no longer has a window, or that came from an earlier run.
|
||||
pub const STALE_VIEW: &str = "Stale view";
|
||||
/// The most objects one read of a selection gives, and the most a selection assignment takes.
|
||||
pub const MAX_LISTED: usize = 10_000;
|
||||
/// The longest name an object or a path query may have, in bytes.
|
||||
@@ -1481,6 +1494,179 @@ fn doc_selection(h: &Host, a: &[Data]) -> Answer {
|
||||
selection_of(h, doc.uid)
|
||||
}
|
||||
|
||||
fn doc_views(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = this_doc(h, a)?;
|
||||
Ok(host_ref("Views", &[float(h.run), float(doc.uid)]))
|
||||
}
|
||||
|
||||
// ---- Views and View ----
|
||||
|
||||
fn views_doc(h: &Host, a: &[Data]) -> std::result::Result<Doc, HostError> {
|
||||
doc_of(h, arg(a, 0), "Views")
|
||||
}
|
||||
|
||||
fn window_of(h: &Host, doc: Doc, id: u64) -> Option<WindowView> {
|
||||
h.session.borrow().window_views.iter().find(|((uid, window), _)| *uid == doc.uid && *window == id).map(|(_, v)| *v)
|
||||
}
|
||||
|
||||
fn views_length(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = views_doc(h, a)?;
|
||||
Ok(num(h.session.borrow().window_views.iter().filter(|((uid, _), _)| *uid == doc.uid).count() as f64))
|
||||
}
|
||||
|
||||
fn views_typename(h: &Host, a: &[Data]) -> Answer {
|
||||
views_doc(h, a)?;
|
||||
Ok(text("Views"))
|
||||
}
|
||||
|
||||
fn views_parent(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = views_doc(h, a)?;
|
||||
Ok(doc_ref(h, doc.uid))
|
||||
}
|
||||
|
||||
fn views_to_string(h: &Host, a: &[Data]) -> Answer {
|
||||
views_doc(h, a)?;
|
||||
Ok(text("[Views]"))
|
||||
}
|
||||
|
||||
fn views_at(h: &Host, a: &[Data]) -> Answer {
|
||||
let doc = views_doc(h, a)?;
|
||||
let index = match arg(a, 1) {
|
||||
Data::Number(n) => whole(*n).and_then(|n| usize::try_from(n).ok()),
|
||||
_ => None,
|
||||
};
|
||||
let Some(index) = index else { return Ok(Data::Undefined) };
|
||||
let key = h.session.borrow().window_views.iter().filter(|((uid, _), _)| *uid == doc.uid).nth(index).map(|(key, _)| *key);
|
||||
Ok(key.map_or(Data::Undefined, |(uid, id)| host_ref("View", &[float(h.run), float(uid), float(id)])))
|
||||
}
|
||||
|
||||
/// `views.index(key)`: the view at index `key`. A view has no name, so a name finds nothing.
|
||||
fn views_index(h: &Host, a: &[Data]) -> Answer {
|
||||
match arg(a, 1) {
|
||||
Data::String(_) => {
|
||||
views_doc(h, a)?;
|
||||
Err(HostError::Error(NOT_FOUND.into()))
|
||||
}
|
||||
Data::Number(_) => match views_at(h, a)? {
|
||||
Data::Undefined => Err(HostError::Error(NOT_FOUND.into())),
|
||||
d => Ok(d),
|
||||
},
|
||||
_ => Err(HostError::Type("give a name or an index".into())),
|
||||
}
|
||||
}
|
||||
|
||||
/// The document of a `View` and its window, which must still be shown.
|
||||
fn this_view(h: &Host, a: &[Data]) -> std::result::Result<(Doc, u64, WindowView), HostError> {
|
||||
let Some(handle) = handle_of(arg(a, 0), "View") else { return Err(HostError::Type("this is not a View".into())) };
|
||||
let &[run, uid, id] = handle.as_slice() else { return Err(HostError::Type("this is not a View".into())) };
|
||||
let doc = find_doc(h, run, uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?;
|
||||
let id = whole(id).ok_or_else(|| HostError::Error(STALE_VIEW.into()))?;
|
||||
let v = window_of(h, doc, id).ok_or_else(|| HostError::Error(STALE_VIEW.into()))?;
|
||||
Ok((doc, id, v))
|
||||
}
|
||||
|
||||
/// Reads the view with `f`, given the document's script coordinates.
|
||||
fn read_view(h: &Host, a: &[Data], f: impl FnOnce(&Frame, Coords, &WindowView) -> Data) -> Answer {
|
||||
let (doc, _, v) = this_view(h, a)?;
|
||||
with_doc(h, doc, |_, st| Ok(f(&frame(st)?, h.dom.coords.get(), &v)))
|
||||
}
|
||||
|
||||
/// Changes the window of `doc` with `f`. No command runs: the change is not undoable, does not
|
||||
/// join the run's undo step and stays when the run fails.
|
||||
fn set_window(h: &Host, doc: Doc, id: u64, f: impl FnOnce(&mut WindowView)) -> Answer {
|
||||
let mut s = h.session.borrow_mut();
|
||||
let v = s
|
||||
.window_views
|
||||
.iter_mut()
|
||||
.find(|((uid, window), _)| *uid == doc.uid && *window == id)
|
||||
.map(|(_, v)| v)
|
||||
.ok_or_else(|| HostError::Error(STALE_VIEW.into()))?;
|
||||
f(v);
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
fn view_typename(h: &Host, a: &[Data]) -> Answer {
|
||||
this_view(h, a)?;
|
||||
Ok(text("View"))
|
||||
}
|
||||
|
||||
fn view_parent(h: &Host, a: &[Data]) -> Answer {
|
||||
let (doc, _, _) = this_view(h, a)?;
|
||||
Ok(doc_ref(h, doc.uid))
|
||||
}
|
||||
|
||||
fn view_to_string(h: &Host, a: &[Data]) -> Answer {
|
||||
this_view(h, a)?;
|
||||
Ok(text("[View]"))
|
||||
}
|
||||
|
||||
/// `bounds`: `[left, top, right, bottom]` of the part of the document the canvas shows.
|
||||
fn view_bounds(h: &Host, a: &[Data]) -> Answer {
|
||||
read_view(h, a, |f, c, v| f.bounds(c, v.visible()))
|
||||
}
|
||||
|
||||
fn view_center(h: &Host, a: &[Data]) -> Answer {
|
||||
read_view(h, a, |f, c, v| pair(f.to_script(c, v.center)))
|
||||
}
|
||||
|
||||
fn view_set_center(h: &Host, a: &[Data]) -> Answer {
|
||||
let (doc, id, _) = this_view(h, a)?;
|
||||
let p = point(arg(a, 1), "centerPoint")?;
|
||||
let to = with_doc(h, doc, |_, st| frame(st).map(|f| f.to_document(h.dom.coords.get(), p)))?;
|
||||
if to.x.abs() > crate::MAX_COORD || to.y.abs() > crate::MAX_COORD {
|
||||
return Err(HostError::Range("centerPoint is outside the canvas".into()));
|
||||
}
|
||||
set_window(h, doc, id, |v| v.center = to)
|
||||
}
|
||||
|
||||
fn view_zoom(h: &Host, a: &[Data]) -> Answer {
|
||||
let (_, _, v) = this_view(h, a)?;
|
||||
Ok(num(v.zoom))
|
||||
}
|
||||
|
||||
fn view_set_zoom(h: &Host, a: &[Data]) -> Answer {
|
||||
let (doc, id, v) = this_view(h, a)?;
|
||||
let z = number(arg(a, 1), "zoom")?;
|
||||
let (min, max) = v.zoom_range();
|
||||
if !(min..=max).contains(&z) {
|
||||
return Err(HostError::Range(format!("zoom must be from {min} to {max}")));
|
||||
}
|
||||
set_window(h, doc, id, |v| v.zoom = z)
|
||||
}
|
||||
|
||||
/// The `ScreenMode` value of each of the app's screen modes: Presentation Mode reads as
|
||||
/// `FULLSCREEN`.
|
||||
fn screen_mode_name(mode: u8) -> &'static str {
|
||||
match mode {
|
||||
0 => "ScreenMode.MULTIWINDOW",
|
||||
1 => "ScreenMode.DESKTOP",
|
||||
_ => "ScreenMode.FULLSCREEN",
|
||||
}
|
||||
}
|
||||
|
||||
fn view_screen_mode(h: &Host, a: &[Data]) -> Answer {
|
||||
let (_, _, v) = this_view(h, a)?;
|
||||
Ok(text(screen_mode_name(v.screen_mode)))
|
||||
}
|
||||
|
||||
fn view_set_screen_mode(h: &Host, a: &[Data]) -> Answer {
|
||||
let (_, _, v) = this_view(h, a)?;
|
||||
let mode = match arg(a, 1) {
|
||||
Data::String(s) if s == "ScreenMode.MULTIWINDOW" => 0,
|
||||
Data::String(s) if s == "ScreenMode.DESKTOP" => 1,
|
||||
Data::String(s) if s == "ScreenMode.FULLSCREEN" => 2,
|
||||
_ => return Err(HostError::Type("give a ScreenMode value".into())),
|
||||
};
|
||||
if screen_mode_name(v.screen_mode) == screen_mode_name(mode) {
|
||||
return Ok(Data::Undefined);
|
||||
}
|
||||
// The screen mode is the app's, so every view shows the new one.
|
||||
for (_, v) in &mut h.session.borrow_mut().window_views {
|
||||
v.screen_mode = mode;
|
||||
}
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
/// The selection of the document `uid`: a new list of the selected objects, topmost first as
|
||||
/// `pageItems` lists them, empty when nothing is selected.
|
||||
fn selection_of(h: &Host, uid: u64) -> Answer {
|
||||
@@ -2329,6 +2515,7 @@ const ENUMS: &[(&str, &[&str])] = &[
|
||||
("RulerUnits", &["Centimeters", "Qs", "Inches", "Pixels", "Millimeters", "Unknown", "Picas", "Points"]),
|
||||
("DocumentColorSpace", &["CMYK", "RGB"]),
|
||||
("CoordinateSystem", &["ARTBOARDCOORDINATESYSTEM", "DOCUMENTCOORDINATESYSTEM"]),
|
||||
("ScreenMode", &["DESKTOP", "FULLSCREEN", "MULTIWINDOW"]),
|
||||
("DocumentArtboardLayout", &["Column", "GridByCol", "GridByRow", "RLGridByCol", "RLGridByRow", "RLRow", "Row"]),
|
||||
("DocumentPresetType", &["BasicCMYK", "BasicRGB", "Mobile", "Print", "Video", "Web"]),
|
||||
("DocumentPreviewMode", &["DefaultPreview", "OverprintPreview", "PixelPreview"]),
|
||||
@@ -2450,16 +2637,43 @@ fn classes(link: &Link) -> Vec<HostClass> {
|
||||
),
|
||||
("pageItems", get(l, doc_page_items), MemberInfo { collection: true, ..typed("PageItems") }),
|
||||
("selection", property(l, doc_selection, doc_set_selection), typed("*")),
|
||||
("views", get(l, doc_views), MemberInfo { collection: true, ..typed("Views") }),
|
||||
("toString", method(l, doc_to_string), returns("string", &[])),
|
||||
]);
|
||||
document.extend(
|
||||
["layers", "artboards", "pathItems", "groupItems", "textFrames", "swatches", "symbols", "views", "activeLayer", "saveAs", "close"]
|
||||
["layers", "artboards", "pathItems", "groupItems", "textFrames", "swatches", "symbols", "activeLayer", "saveAs", "close"]
|
||||
.into_iter()
|
||||
.map(|m| later(l, "Document", m)),
|
||||
);
|
||||
document.extend(variables::document_members(l));
|
||||
document.push(("tags".into(), get(l, tags::doc_tags), MemberInfo { collection: true, ..typed("Tags") }));
|
||||
classes.push(class("Document", None, document, None));
|
||||
classes.push(class(
|
||||
"Views",
|
||||
None,
|
||||
named(vec![
|
||||
("typename", get(l, views_typename), typed("string")),
|
||||
("length", get(l, views_length), typed("number")),
|
||||
("parent", get(l, views_parent), typed("Document")),
|
||||
("index", method(l, views_index), returns("View", &[("itemKey", "*")])),
|
||||
("toString", method(l, views_to_string), returns("string", &[])),
|
||||
]),
|
||||
Some(function(l, views_at)),
|
||||
));
|
||||
classes.push(class(
|
||||
"View",
|
||||
None,
|
||||
named(vec![
|
||||
("typename", get(l, view_typename), typed("string")),
|
||||
("parent", get(l, view_parent), typed("Views")),
|
||||
("bounds", get(l, view_bounds), typed("Array")),
|
||||
("centerPoint", property(l, view_center, view_set_center), typed("Array")),
|
||||
("zoom", property(l, view_zoom, view_set_zoom), typed("number")),
|
||||
("screenMode", property(l, view_screen_mode, view_set_screen_mode), typed("ScreenMode")),
|
||||
("toString", method(l, view_to_string), returns("string", &[])),
|
||||
]),
|
||||
None,
|
||||
));
|
||||
classes.push(class(
|
||||
"PageItems",
|
||||
None,
|
||||
|
||||
@@ -190,6 +190,7 @@ impl Session {
|
||||
startup_failures: vec![],
|
||||
script_high_water: Default::default(),
|
||||
script_in_run: false,
|
||||
window_views: vec![],
|
||||
script_copy_first: cfg!(target_arch = "wasm32"),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -193,6 +193,140 @@ fn ruler_origin_round_trips_without_moving_art() {
|
||||
assert!(failure(&mut s, "app.activeDocument.rulerOrigin = [1e12, 0];").contains("outside the canvas"));
|
||||
}
|
||||
|
||||
/// A window on the document of [`doc`] that shows 300 × 200 pt around (200, 150) at 200%.
|
||||
fn window() -> WindowView {
|
||||
WindowView {
|
||||
center: vectorcraft_geom::Point::new(200.0, 150.0),
|
||||
zoom: 2.0,
|
||||
zoom_baseline: 1.0,
|
||||
rotation: 0.0,
|
||||
size: [600.0, 400.0],
|
||||
screen_mode: 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Shows the active document in the window `v`.
|
||||
fn show(s: &mut Session, v: WindowView) {
|
||||
let uid = s.active().unwrap().uid;
|
||||
s.window_views = vec![((uid, 1), v)];
|
||||
}
|
||||
|
||||
/// The window of the active document.
|
||||
fn shown(s: &Session) -> Option<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); vc.log(0 in v); vc.log('a' in v);";
|
||||
assert_eq!(log(&mut s, none), vec![json!(0), json!(true), json!(false), json!(false)], "a document without a window has no view");
|
||||
show(&mut s, window());
|
||||
// A rectangle drawn over the visible part of the document has the view's bounds.
|
||||
let r = window().visible();
|
||||
rect(&mut s, r.x0, r.y0, r.width(), r.height());
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var d = app.activeDocument; var v = d.views[0]; vc.log(d.views.length); vc.log(v.typename);\
|
||||
vc.log(v.parent === d); vc.log(v.bounds); var r = d.pageItems[0];\
|
||||
vc.log(r.geometricBounds); vc.log(v.centerPoint); vc.log(r.position[0] + r.width / 2);\
|
||||
vc.log(r.position[1] - r.height / 2);",
|
||||
);
|
||||
assert_eq!(out[..3], [json!(1), json!("View"), json!(true)]);
|
||||
assert_eq!(out[3], out[4], "the view's bounds are the visible area");
|
||||
assert_eq!(out[5], json!([out[6], out[7]]), "the centre is the middle of the visible area");
|
||||
// Turning the view shows more of the document around the same centre.
|
||||
show(&mut s, WindowView { rotation: 30.0, ..window() });
|
||||
let turned = log(&mut s, "vc.log(app.activeDocument.views[0].bounds);");
|
||||
let width = |b: &Value| b[2].as_f64().unwrap() - b[0].as_f64().unwrap();
|
||||
assert!(width(&turned[0]) > width(&out[3]));
|
||||
let names = log(&mut s, "var d = app.activeDocument; vc.log(String(d.views) + String(d.views[0]));");
|
||||
assert_eq!(names, vec![json!("[Views][View]")]);
|
||||
assert_eq!(log(&mut s, "var v = app.activeDocument.views; vc.log(0 in v); vc.log(1 in v);"), vec![json!(true), json!(false)]);
|
||||
// A named engine keeps the views from an earlier run, but they are stale.
|
||||
run(&mut s, "#targetengine keep\nvar vs = app.activeDocument.views, v = vs[0];").unwrap();
|
||||
for member in ["String(vs)", "String(v)"] {
|
||||
let e = failure(&mut s, &format!("#targetengine keep\n{member};"));
|
||||
assert!(e.contains("Stale document"), "{member}: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn setting_the_zoom_changes_the_view_without_an_undo_step() {
|
||||
let (mut s, ..) = doc();
|
||||
show(&mut s, window());
|
||||
// Another document's window.
|
||||
s.window_views.push(((u64::MAX, 1), window()));
|
||||
let steps = undo_steps(&s);
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var v = app.activeDocument.views[0]; var b = v.bounds; v.zoom = 4; vc.log(v.zoom);\
|
||||
vc.log(v.bounds[2] - v.bounds[0] < b[2] - b[0]); v.centerPoint = [100, 100]; vc.log(v.centerPoint);\
|
||||
v.screenMode = ScreenMode.FULLSCREEN; vc.log(v.screenMode);",
|
||||
);
|
||||
assert_eq!(out, vec![json!(4), json!(true), json!([100, 100]), json!("ScreenMode.FULLSCREEN")]);
|
||||
let now = shown(&s).unwrap();
|
||||
assert!(now.zoom > window().zoom);
|
||||
assert!(now.center != window().center && now.screen_mode != window().screen_mode);
|
||||
assert_eq!(s.window_views[1].1.screen_mode, now.screen_mode, "the screen mode is the same in every window");
|
||||
assert_eq!(s.window_views[1].1.zoom, window().zoom, "the zoom is each window's own");
|
||||
assert_eq!(undo_steps(&s), steps, "a view change is not undoable");
|
||||
// A bad value throws and leaves the view as it is.
|
||||
let bad = [
|
||||
("v.zoom = 0;", "RangeError"),
|
||||
("v.zoom = 1000;", "RangeError"),
|
||||
("v.zoom = '2';", "TypeError"),
|
||||
("v.centerPoint = [1];", "TypeError"),
|
||||
("v.centerPoint = [1e12, 0];", "RangeError"),
|
||||
("v.screenMode = 'FULLSCREEN';", "TypeError"),
|
||||
];
|
||||
for (bad, name) in bad {
|
||||
let out = log(&mut s, &format!("var v = app.activeDocument.views[0]; try {{ {bad} vc.log('set'); }} catch (e) {{ vc.log(e.name); }}"));
|
||||
assert_eq!(out, vec![json!(name)], "{bad}");
|
||||
assert_eq!(shown(&s), Some(now), "{bad}");
|
||||
}
|
||||
// A run that fails after changing the view keeps the change.
|
||||
failure(&mut s, "app.activeDocument.views[0].zoom = 1; throw new Error('stop');");
|
||||
assert_eq!(shown(&s).map(|v| v.zoom), Some(1.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn view_centers_stay_inside_the_canvas_after_coordinate_conversion() {
|
||||
let (mut s, ..) = doc();
|
||||
let origin = vectorcraft_geom::Point::new(3.0e6, 3.0e6);
|
||||
s.edit("Move Artboard", |d, _| {
|
||||
d.artboards[0].rect = vectorcraft_geom::Rect::from_origin_size(origin, (400.0, 300.0));
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
show(&mut s, window());
|
||||
let steps = undo_steps(&s);
|
||||
for coordinates in ["ARTBOARDCOORDINATESYSTEM", "DOCUMENTCOORDINATESYSTEM"] {
|
||||
let script_point = |p: vectorcraft_geom::Point| {
|
||||
let y = if coordinates == "ARTBOARDCOORDINATESYSTEM" { p.y - origin.y } else { origin.y + 300.0 - p.y };
|
||||
[p.x - origin.x, y]
|
||||
};
|
||||
for bound in [-MAX_COORD, MAX_COORD] {
|
||||
for horizontal in [false, true] {
|
||||
let point = |n| if horizontal { vectorcraft_geom::Point::new(n, 0.0) } else { vectorcraft_geom::Point::new(0.0, n) };
|
||||
let before = shown(&s);
|
||||
let [x, y] = script_point(point(bound + bound.signum()));
|
||||
let source = format!(
|
||||
"app.coordinateSystem = CoordinateSystem.{coordinates}; var v = app.activeDocument.views[0]; \
|
||||
try {{ v.centerPoint = [{x}, {y}]; vc.log('set'); }} catch (e) {{ vc.log(e.name); }}"
|
||||
);
|
||||
assert_eq!(log(&mut s, &source), vec![json!("RangeError")], "{source}");
|
||||
assert_eq!(shown(&s), before, "a rejected center leaves the view unchanged");
|
||||
let [x, y] = script_point(point(bound));
|
||||
log(&mut s, &format!("app.coordinateSystem = CoordinateSystem.{coordinates}; app.activeDocument.views[0].centerPoint = [{x}, {y}];"));
|
||||
assert_eq!(shown(&s).unwrap().center, point(bound), "the canvas boundary is allowed");
|
||||
}
|
||||
}
|
||||
}
|
||||
assert_eq!(undo_steps(&s), steps);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn page_item_properties_join_one_undo_step() {
|
||||
let (mut s, a, _) = doc();
|
||||
|
||||
Reference in new issue
Block a user