mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-05 05:22:58 -05:00
Merge main into feat/scripts-api-d1b-prefs-matrix-clipboard
This commit is contained in:
commit
ab35e04329
37 files changed
+1730
-271
No files matched your search
@@ -124,6 +124,8 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
|
||||
|
||||
## Progress log
|
||||
|
||||
- 2026-12-02: The desktop Print dialog looks up installed printers in the background. Named printers become selectable after the lookup returns and the dialog applies the list. PDF File is available at once. Physical printing waits for the list to be applied, and Done can save settings while the lookup runs. The dialog shows and announces discovery and disables physical Print until the list is applied.
|
||||
|
||||
- 2026-11-20: Color conversion indexes global swatch bases and linked-paint lookups (#8804); scores, estimates and measured budgets unchanged.
|
||||
|
||||
- 2026-11-18: Built-in symbol library Media Controls: adds a seventh procedural symbol library (Window › Symbol Libraries, the Symbols panel's Symbol Libraries Menu) containing six original vector symbols (Play, Pause, Stop, Skip Next, Shuffle, Repeat) generated in code without default 9-slice guides (part of Gap 5). Headline numbers unchanged.
|
||||
|
||||
@@ -19,6 +19,9 @@ impl PrintService for SystemPrint {
|
||||
let note = system::print(job)?;
|
||||
Ok(sent(job.title, job.printer, ¬e))
|
||||
}
|
||||
fn shared_printers(&self) -> Option<vectorcraft_ui_egui::print::SharedPrintersFn> {
|
||||
Some(std::sync::Arc::new(system::queues))
|
||||
}
|
||||
fn shared_print(&self) -> Option<vectorcraft_ui_egui::print::SharedPrintFn> {
|
||||
Some(std::sync::Arc::new(|job| system::print(job).map(|note| sent(job.title, job.printer, ¬e))))
|
||||
}
|
||||
@@ -145,6 +148,10 @@ mod system {
|
||||
pub fn printers() -> Vec<Printer> {
|
||||
craft::print::printers().into_iter().map(Printer::from).collect()
|
||||
}
|
||||
/// The installed queues and the default one, without asking each driver for its capabilities.
|
||||
pub fn queues() -> Vec<Printer> {
|
||||
craft::print::printer_queues().into_iter().map(Printer::from).collect()
|
||||
}
|
||||
/// The paper sizes of an installed printer's driver: its CUPS PPD, or Windows' printer settings.
|
||||
pub fn papers(printer: &str) -> Vec<Paper> {
|
||||
#[cfg(windows)]
|
||||
|
||||
@@ -173,13 +173,14 @@ fn curves_area(curves: &[CubicBez]) -> f64 {
|
||||
curves.iter().map(|c| c.signed_area()).sum()
|
||||
}
|
||||
|
||||
/// Cubic curves along the ellipse with semi-axes `a`, `b` from angle `t0` to `t1`.
|
||||
/// Cubic curves along the ellipse with semi-axes `a`, `b` from angle `t0` to `t1`, one for each
|
||||
/// quarter turn or part of one.
|
||||
fn ellipse_arc(out: &mut Vec<CubicBez>, a: f64, b: f64, t0: f64, t1: f64) {
|
||||
if t1 <= t0 {
|
||||
return;
|
||||
}
|
||||
let at = |th: f64| Point::new(a * th.cos(), b * th.sin());
|
||||
let n = ((t1 - t0) / std::f64::consts::FRAC_PI_4).ceil().max(1.0);
|
||||
let n = ((t1 - t0) / std::f64::consts::FRAC_PI_2).ceil().max(1.0);
|
||||
let d = (t1 - t0) / n;
|
||||
let k = 4.0 / 3.0 * (d / 4.0).tan();
|
||||
for i in 0..n as usize {
|
||||
@@ -294,20 +295,27 @@ fn spot(t: f64, h: f64, kind: SpotKind) -> BezPath {
|
||||
return four_quadrants(&spot_quadrant(t, h, kind));
|
||||
}
|
||||
let mut bp = BezPath::new();
|
||||
let mut add = |curves: Vec<CubicBez>, first: bool| {
|
||||
let mut end: Option<Point> = None;
|
||||
// Corners that meet at a point on the cell's side are joined without an anchor of their own.
|
||||
let mut add = |curves: Vec<CubicBez>| {
|
||||
for (k, c) in curves.iter().enumerate() {
|
||||
if k == 0 {
|
||||
if first { bp.move_to(c.p0) } else { bp.line_to(c.p0) }
|
||||
match end {
|
||||
None => bp.move_to(c.p0),
|
||||
Some(e) if e.distance(c.p0) < 1e-9 => {}
|
||||
Some(_) => bp.line_to(c.p0),
|
||||
}
|
||||
}
|
||||
bp.curve_to(c.p1, c.p2, c.p3);
|
||||
end = Some(c.p3);
|
||||
}
|
||||
};
|
||||
// Round the corners counterclockwise, each one's hole the dot of the opposite tone.
|
||||
let q1 = spot_quadrant(1.0 - t.min(1.0), h, kind);
|
||||
add(reversed(&mapped(&q1, |p| Point::new(h - p.x, h - p.y))), true);
|
||||
add(mapped(&q1, |p| Point::new(p.x - h, h - p.y)), false);
|
||||
add(reversed(&mapped(&q1, |p| Point::new(p.x - h, p.y - h))), false);
|
||||
add(mapped(&q1, |p| Point::new(h - p.x, p.y - h)), false);
|
||||
add(reversed(&mapped(&q1, |p| Point::new(h - p.x, h - p.y))));
|
||||
add(mapped(&q1, |p| Point::new(p.x - h, h - p.y)));
|
||||
add(reversed(&mapped(&q1, |p| Point::new(p.x - h, p.y - h))));
|
||||
add(mapped(&q1, |p| Point::new(h - p.x, p.y - h)));
|
||||
bp.close_path();
|
||||
bp
|
||||
}
|
||||
@@ -410,21 +418,28 @@ fn cell_dot(t: f64, h: f64, kind: CellKind) -> PathData {
|
||||
}
|
||||
|
||||
/// The closed path through `q1` (from the x axis to the y axis) and its mirror images in the other
|
||||
/// three quadrants, counterclockwise.
|
||||
/// three quadrants, counterclockwise. Quadrants that meet on an axis are joined without an anchor
|
||||
/// of their own at the join.
|
||||
fn four_quadrants(q1: &[CubicBez]) -> BezPath {
|
||||
let mut bp = BezPath::new();
|
||||
let mut add = |curves: Vec<CubicBez>, first: bool| {
|
||||
let mut end: Option<Point> = None;
|
||||
let mut add = |curves: Vec<CubicBez>| {
|
||||
for (k, c) in curves.iter().enumerate() {
|
||||
if k == 0 {
|
||||
if first { bp.move_to(c.p0) } else { bp.line_to(c.p0) }
|
||||
match end {
|
||||
None => bp.move_to(c.p0),
|
||||
Some(e) if e.distance(c.p0) < 1e-9 => {}
|
||||
Some(_) => bp.line_to(c.p0),
|
||||
}
|
||||
}
|
||||
bp.curve_to(c.p1, c.p2, c.p3);
|
||||
end = Some(c.p3);
|
||||
}
|
||||
};
|
||||
add(q1.to_vec(), true);
|
||||
add(reversed(&mapped(q1, |p| Point::new(-p.x, p.y))), false);
|
||||
add(mapped(q1, |p| Point::new(-p.x, -p.y)), false);
|
||||
add(reversed(&mapped(q1, |p| Point::new(p.x, -p.y))), false);
|
||||
add(q1.to_vec());
|
||||
add(reversed(&mapped(q1, |p| Point::new(-p.x, p.y))));
|
||||
add(mapped(q1, |p| Point::new(-p.x, -p.y)));
|
||||
add(reversed(&mapped(q1, |p| Point::new(p.x, -p.y))));
|
||||
bp.close_path();
|
||||
bp
|
||||
}
|
||||
@@ -731,6 +746,7 @@ mod tests {
|
||||
use super::*;
|
||||
use vectorcraft_doc::Effect;
|
||||
use vectorcraft_geom::Shape;
|
||||
use vectorcraft_geom::kurbo::PathEl;
|
||||
|
||||
/// A black square's samples: `side` points of black from (10, 10), white around it.
|
||||
fn black_square(side: f64, h: &Halftone) -> (Samples, Rect) {
|
||||
@@ -833,6 +849,31 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dot_inside_its_cell_is_four_curves() {
|
||||
for shape in [DotShape::Circle, DotShape::Ellipse] {
|
||||
let bp = shape.path(0.2, 10.0).to_bezpath();
|
||||
let curves = bp.elements().iter().filter(|el| matches!(el, PathEl::CurveTo(..))).count();
|
||||
let lines = bp.elements().iter().filter(|el| matches!(el, PathEl::LineTo(..))).count();
|
||||
assert_eq!((curves, lines), (4, 0), "{shape:?}: {:?}", bp.elements());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dot_quadrants_join_without_a_repeated_anchor() {
|
||||
for shape in [DotShape::Circle, DotShape::Ellipse, DotShape::Diamond, DotShape::Euclidean, DotShape::Elliptical] {
|
||||
for t in [0.2, 0.45, 0.55, 0.6, 0.85] {
|
||||
for sp in &shape.path(t, 10.0).subpaths {
|
||||
let n = sp.anchors.len();
|
||||
for i in 0..n {
|
||||
let (a, b) = (sp.anchors[i].p, sp.anchors[(i + 1) % n].p);
|
||||
assert!(a.distance(b) > 1e-6, "{shape:?} at {t}: {:?}", sp.anchors);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn euclidean_dots_meet_corner_to_corner_at_half() {
|
||||
let s = DotShape::Euclidean;
|
||||
|
||||
@@ -24,7 +24,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"New…",
|
||||
["File"],
|
||||
None,
|
||||
"{preset?: a name from file.newPresets (start from it; the other params change it), name?|title?: document name (default Untitled-N), width?: pt=612|\"210 mm\", height?: pt=792 (each more than 0 and at most 3,999,856 pt, as artboard.new takes them), units?: \"Pixels\"|\"Points\"|\"Picas\"|\"Inches\"|\"Millimeters\"|\"Centimeters\"|\"Feet\"|\"Yards\"|\"Meters\"|\"Feet & Inches\" (default: prefs unitsGeneral, as print presets; screen presets: Pixels), orientation?: \"portrait\"|\"landscape\" (swaps width and height to match), artboards?: n (a whole number, 1–1000), artboardLayout?: {layout?: \"gridByRow\"|\"gridByColumn\"|\"row\"|\"column\", columns?: n (a whole number, 1–1000; default: all in one row), rows?: n (a whole number, 1–1000; gridByColumn only, an error with another layout: that many rows, in place of columns; a preset keeps them until columns without rows or another layout is given), spacing?: pt=20, rightToLeft?: bool}, bleed?: pt|[top, bottom, left, right]|{top?, …} (0–72 pt), backgroundContents?: \"transparent\"|\"white\" (a white artboard background, not an object), colorMode?: \"rgb\"|\"cmyk\" (a CMYK document starts with CMYK swatches and stores the colours applied to it as CMYK), rasterEffectsPpi?: 72|150|300 (1–2400), previewMode?: \"default\"|\"pixel\"|\"overprint\" (overprint turns Overprint Preview on, pixel Pixel Preview in the app; default leaves both), alignNewObjectsToPixelGrid?: bool (Advanced Options › Align New Objects to Pixel Grid: paths drawn in the document are pixel-aligned; default on for the Mobile and Web presets, else off; document.setup changes it later), profile?: a category of file.newPresets|null (the New Document profile the document starts from, see file.newProfiles; default: a built-in preset's category, kept by the saved and Recent presets made from it; null or no preset: the defaults), created?: Unix seconds|null (File Info's created date; default now, recorded in the journal so a replay matches), size?: a preset's size label (a preset file.newPresets lists can be passed back; ignored)} → {index, previewMode, profile?: the profile applied, warnings?: [text] (a color profile the profile's file carries that can't be used), profileError?: {profile, reason} (its file is a link or a folder, could not be read, was larger than 64 MiB or is not a native document, or the request may not read the profiles folder, a reason that leaves out the folder's path: the document has the defaults)}; the size is remembered in file.newPresets' Recent",
|
||||
"{preset?: a name from file.newPresets (start from it; the other params change it), presetCategory?: a category of file.newPresets (preset names a preset of that category; default: a saved preset first, then the built-in ones), name?|title?: document name (default Untitled-N), width?: pt=612|\"210 mm\", height?: pt=792 (each more than 0 and at most 3,999,856 pt, as artboard.new takes them), units?: \"Pixels\"|\"Points\"|\"Picas\"|\"Inches\"|\"Millimeters\"|\"Centimeters\"|\"Feet\"|\"Yards\"|\"Meters\"|\"Feet & Inches\" (default: prefs unitsGeneral, as print presets; screen presets: Pixels), orientation?: \"portrait\"|\"landscape\" (swaps width and height to match), artboards?: n (a whole number, 1–1000), artboardLayout?: {layout?: \"gridByRow\"|\"gridByColumn\"|\"row\"|\"column\", columns?: n (a whole number, 1–1000; default: all in one row), rows?: n (a whole number, 1–1000; gridByColumn only, an error with another layout: that many rows, in place of columns; a preset keeps them until columns without rows or another layout is given), spacing?: pt=20, rightToLeft?: bool}, bleed?: pt|[top, bottom, left, right]|{top?, …} (0–72 pt), backgroundContents?: \"transparent\"|\"white\" (a white artboard background, not an object), colorMode?: \"rgb\"|\"cmyk\" (a CMYK document starts with CMYK swatches and stores the colours applied to it as CMYK), rasterEffectsPpi?: 72|150|300 (1–2400), previewMode?: \"default\"|\"pixel\"|\"overprint\" (overprint turns Overprint Preview on, pixel Pixel Preview in the app; default leaves both), alignNewObjectsToPixelGrid?: bool (Advanced Options › Align New Objects to Pixel Grid: paths drawn in the document are pixel-aligned; default on for the Mobile and Web presets, else off; document.setup changes it later), profile?: a category of file.newPresets|null (the New Document profile the document starts from, see file.newProfiles; default: a built-in preset's category, kept by the saved and Recent presets made from it; null or no preset: the defaults), created?: Unix seconds|null (File Info's created date; default now, recorded in the journal so a replay matches), size?: a preset's size label (a preset file.newPresets lists can be passed back; ignored)} → {index, previewMode, profile?: the profile applied, warnings?: [text] (a color profile the profile's file carries that can't be used), profileError?: {profile, reason} (its file is a link or a folder, could not be read, was larger than 64 MiB or is not a native document, or the request may not read the profiles folder, a reason that leaves out the folder's path: the document has the defaults)}; the size is remembered in file.newPresets' Recent",
|
||||
always,
|
||||
super::newdoc::file_new
|
||||
),
|
||||
|
||||
@@ -858,6 +858,18 @@ pub fn find(s: &Session, name: &str) -> Option<DocSettings> {
|
||||
.or_else(|| CATEGORIES.iter().flat_map(|c| builtin(c, s.default_units())).find(|p| p.name.eq_ignore_ascii_case(name)))
|
||||
}
|
||||
|
||||
/// The preset the `preset` param of `cmd` names, looked up in the category `presetCategory` names
|
||||
/// when it is given ([`category`]) and with [`find`] otherwise; the starting settings without
|
||||
/// `preset`.
|
||||
fn preset_param(s: &Session, p: &Value, cmd: &str) -> Result<DocSettings> {
|
||||
let Some(name) = str_param(p, "preset") else { return Ok(s.default_settings()) };
|
||||
let found = match str_param(p, "presetCategory") {
|
||||
Some(c) => category(s, c).and_then(|ps| ps.into_iter().find(|q| q.name.eq_ignore_ascii_case(name.trim()))),
|
||||
None => find(s, name),
|
||||
};
|
||||
found.ok_or_else(|| bad(cmd, format!("no preset called `{name}` (see file.newPresets)")))
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// New Document's starting settings: Letter in Preferences ▸ Units ▸ General.
|
||||
fn default_settings(&self) -> DocSettings {
|
||||
@@ -871,10 +883,7 @@ const RECENT: usize = 12;
|
||||
/// `file.new`: a new document from a preset and/or explicit settings.
|
||||
pub(crate) fn file_new(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "file.new";
|
||||
let base = match str_param(p, "preset") {
|
||||
Some(name) => find(s, name).ok_or_else(|| bad(C, format!("no preset called `{name}` (see file.newPresets)")))?,
|
||||
None => s.default_settings(),
|
||||
};
|
||||
let base = preset_param(s, p, C)?;
|
||||
// A preset keeps its name in Recent unless its size changed (turning it doesn't count).
|
||||
let sorted = |d: &DocSettings| (d.width.min(d.height), d.width.max(d.height), d.units);
|
||||
let size = str_param(p, "preset").map(|_| sorted(&base));
|
||||
@@ -964,10 +973,7 @@ fn save(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
.map(str::trim)
|
||||
.filter(|n| !n.is_empty() && n.chars().count() <= 64)
|
||||
.ok_or_else(|| bad(C, "give the preset a name (1–64 characters)"))?;
|
||||
let base = match str_param(p, "preset") {
|
||||
Some(from) => find(s, from).ok_or_else(|| bad(C, format!("no preset called `{from}` (see file.newPresets)")))?,
|
||||
None => s.default_settings(),
|
||||
};
|
||||
let base = preset_param(s, p, C)?;
|
||||
let mut preset = base.with_params_inner(p, C, s.replaying())?;
|
||||
preset.name = name.to_string();
|
||||
let saved = &mut s.prefs.new_doc_presets;
|
||||
|
||||
@@ -419,7 +419,8 @@ impl FolderStore {
|
||||
|
||||
/// Does `path` still name `file`? On Unix the two must be the same file (device and inode); on
|
||||
/// Windows they must be the same file (volume serial number and file index); elsewhere `path`
|
||||
/// must exist. When either file can't be read, it does not.
|
||||
/// must exist. A link at `path` is not followed, so it names the link and not `file`. When
|
||||
/// either file can't be read, it does not.
|
||||
pub(crate) fn still_named(file: &std::fs::File, path: &std::path::Path) -> bool {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
@@ -431,8 +432,19 @@ impl FolderStore {
|
||||
}
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use std::os::windows::fs::OpenOptionsExt as _;
|
||||
// FILE_FLAG_OPEN_REPARSE_POINT opens a link itself rather than its target, and
|
||||
// FILE_FLAG_BACKUP_SEMANTICS lets a folder be opened, as `same_file::Handle::from_path`
|
||||
// opens one.
|
||||
const FILE_FLAG_OPEN_REPARSE_POINT: u32 = 0x0020_0000;
|
||||
const FILE_FLAG_BACKUP_SEMANTICS: u32 = 0x0200_0000;
|
||||
let opened = file.try_clone().and_then(same_file::Handle::from_file);
|
||||
match (opened, same_file::Handle::from_path(path)) {
|
||||
let named = std::fs::OpenOptions::new()
|
||||
.read(true)
|
||||
.custom_flags(FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS)
|
||||
.open(path)
|
||||
.and_then(same_file::Handle::from_file);
|
||||
match (opened, named) {
|
||||
(Ok(a), Ok(b)) => a == b,
|
||||
_ => false,
|
||||
}
|
||||
|
||||
@@ -470,8 +470,9 @@ pub struct Prefs {
|
||||
pub script_preferences: std::collections::BTreeMap<String, ScriptPreference>,
|
||||
}
|
||||
|
||||
/// A value a script stored with `app.preferences`, with the type it was stored as.
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
/// A value a script stored with `app.preferences`, with the type it was stored as. Two real
|
||||
/// values are equal when their bits are, so 0 and -0 differ.
|
||||
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum ScriptPreference {
|
||||
Boolean(bool),
|
||||
@@ -480,6 +481,18 @@ pub enum ScriptPreference {
|
||||
String(String),
|
||||
}
|
||||
|
||||
impl PartialEq for ScriptPreference {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
match (self, other) {
|
||||
(Self::Boolean(a), Self::Boolean(b)) => a == b,
|
||||
(Self::Integer(a), Self::Integer(b)) => a == b,
|
||||
(Self::Real(a), Self::Real(b)) => a.to_bits() == b.to_bits(),
|
||||
(Self::String(a), Self::String(b)) => a == b,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The default Hold Shortcut Delay, in seconds (VectorCraft's own value).
|
||||
pub const KEY_HOLD_DELAY: f64 = 0.35;
|
||||
/// The range of the Hold Shortcut Delay, in seconds.
|
||||
|
||||
@@ -482,6 +482,12 @@ impl Dialogs {
|
||||
true
|
||||
}
|
||||
|
||||
/// Whether the waiting dialog is the confirm [`Dialogs::ask`] opened to turn off the external
|
||||
/// script warning, whatever a script's own dialogs say.
|
||||
pub(crate) fn asks_warning_off(&self) -> bool {
|
||||
self.waiting.borrow().is_some() && self.on_yes.get() == Some(OnYes::ExternalScriptWarningOff)
|
||||
}
|
||||
|
||||
/// What the person approved with Yes to a confirm from [`Dialogs::ask`], once.
|
||||
pub(crate) fn take_approved(&self) -> Option<OnYes> {
|
||||
self.approved.take()
|
||||
|
||||
@@ -106,6 +106,7 @@ mod save_open;
|
||||
mod tags;
|
||||
mod text;
|
||||
mod tracing;
|
||||
mod transform;
|
||||
mod variables;
|
||||
|
||||
pub use variables::{MAX_HANDLES, STALE_DATASET, STALE_VARIABLE};
|
||||
@@ -915,7 +916,8 @@ fn restore_layer(h: &Host, uid: u64, layer: Option<NodeId>, rows: &[NodeId]) ->
|
||||
/// commands changed it (commands given ids select them first), direct-selected anchors, segments,
|
||||
/// ruler guides, slices, the key, a Layers panel target and an object chosen inside a dynamic
|
||||
/// symbol instance or an Objects on Path group included, less the objects that are now deleted,
|
||||
/// hidden or locked. `f`'s commands and the steps that put things back succeed or fail together
|
||||
/// hidden or locked; the current layer, which selecting art changes, is put back too while it is
|
||||
/// still a layer that can be edited. `f`'s commands and the steps that put things back succeed or fail together
|
||||
/// ([`atomically`]): when putting back the selection, the layer or the active document fails, `f`'s
|
||||
/// changes are undone as well.
|
||||
fn on_doc<T>(
|
||||
@@ -2930,17 +2932,21 @@ fn place(h: &Host, doc: Doc, id: NodeId, to: &Destination) -> std::result::Resul
|
||||
(_, None) => count,
|
||||
};
|
||||
let at = if clips { at.max(1) } else { at };
|
||||
// The index `node.move` puts the object at: art stays below the ruler guides.
|
||||
// This is `Node::insert_index` on the parent's children without the object, read in place
|
||||
// so that no list of them is copied.
|
||||
let node = d.node(id).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?;
|
||||
let rest = || d.children(Some(to.parent)).into_iter().flatten().filter(|n| n.id != id);
|
||||
let start = rest().enumerate().filter(|(_, n)| !n.is_ruler_guide()).last().map_or(0, |(i, _)| i + 1);
|
||||
let i = at.min(rest().count());
|
||||
let at = if node.is_ruler_guide() { i.max(start) } else { i.min(start) };
|
||||
// An image left or put first in an ordinary group named as a tracing would make that group
|
||||
// one, in the group it leaves as in the group it goes into.
|
||||
let left = from.and_then(|(p, ..)| p).filter(|p| *p != to.parent);
|
||||
if makes_tracing(d, to.parent, id, Some(at)) || left.is_some_and(|p| makes_tracing(d, p, id, None)) {
|
||||
return Err(HostError::Error(NOT_A_TRACING.into()));
|
||||
}
|
||||
// The index `node.move` puts the object at: art stays below the ruler guides.
|
||||
let node = d.node(id).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?;
|
||||
let rest: Vec<Arc<crate::doc::Node>> =
|
||||
d.children(Some(to.parent)).map(|c| c.iter().filter(|n| n.id != id).cloned().collect()).unwrap_or_default();
|
||||
Ok::<_, HostError>(crate::doc::Node::insert_index(&rest, at, node))
|
||||
Ok::<_, HostError>(at)
|
||||
})?;
|
||||
let now = with_doc(h, doc, |_, st| st.doc.position(id));
|
||||
if now.is_some_and(|(p, i, _)| p == Some(to.parent) && i == index) {
|
||||
@@ -3158,6 +3164,7 @@ const ENUMS: &[(&str, &[&str])] = &[
|
||||
("RulerUnits", &["Centimeters", "Qs", "Inches", "Pixels", "Millimeters", "Unknown", "Picas", "Points"]),
|
||||
("DocumentColorSpace", &["CMYK", "RGB"]),
|
||||
("CoordinateSystem", &["ARTBOARDCOORDINATESYSTEM", "DOCUMENTCOORDINATESYSTEM"]),
|
||||
("Transformation", &["BOTTOM", "BOTTOMLEFT", "BOTTOMRIGHT", "CENTER", "DOCUMENTORIGIN", "LEFT", "RIGHT", "TOP", "TOPLEFT", "TOPRIGHT"]),
|
||||
("ScreenMode", &["DESKTOP", "FULLSCREEN", "MULTIWINDOW"]),
|
||||
("DocumentArtboardLayout", &["Column", "GridByCol", "GridByRow", "RLGridByCol", "RLGridByRow", "RLRow", "Row"]),
|
||||
("DocumentPresetType", &["BasicCMYK", "BasicRGB", "Mobile", "Print", "Video", "Web"]),
|
||||
@@ -3384,6 +3391,69 @@ fn classes(link: &Link) -> Vec<HostClass> {
|
||||
("remove", method(l, item_remove), returns("undefined", &[])),
|
||||
("zOrder", method(l, item_z_order), returns("undefined", &[("zOrderCmd", "ZOrderMethod")])),
|
||||
("toString", method(l, item_to_string), returns("string", &[])),
|
||||
(
|
||||
"translate",
|
||||
method(l, transform::translate),
|
||||
returns(
|
||||
"undefined",
|
||||
&[
|
||||
("deltaX", "number"),
|
||||
("deltaY", "number"),
|
||||
("transformObjects", "boolean"),
|
||||
("transformFillPatterns", "boolean"),
|
||||
("transformFillGradients", "boolean"),
|
||||
("transformStrokePatterns", "boolean"),
|
||||
],
|
||||
),
|
||||
),
|
||||
(
|
||||
"rotate",
|
||||
method(l, transform::rotate),
|
||||
returns(
|
||||
"undefined",
|
||||
&[
|
||||
("angle", "number"),
|
||||
("changePositions", "boolean"),
|
||||
("changeFillPatterns", "boolean"),
|
||||
("changeFillGradients", "boolean"),
|
||||
("changeStrokePattern", "boolean"),
|
||||
("rotateAbout", "Transformation"),
|
||||
],
|
||||
),
|
||||
),
|
||||
(
|
||||
"resize",
|
||||
method(l, transform::resize),
|
||||
returns(
|
||||
"undefined",
|
||||
&[
|
||||
("scaleX", "number"),
|
||||
("scaleY", "number"),
|
||||
("changePositions", "boolean"),
|
||||
("changeFillPatterns", "boolean"),
|
||||
("changeFillGradients", "boolean"),
|
||||
("changeStrokePattern", "boolean"),
|
||||
("changeLineWidths", "number"),
|
||||
("scaleAbout", "Transformation"),
|
||||
],
|
||||
),
|
||||
),
|
||||
(
|
||||
"transform",
|
||||
method(l, transform::transform),
|
||||
returns(
|
||||
"undefined",
|
||||
&[
|
||||
("transformationMatrix", "Matrix"),
|
||||
("changePositions", "boolean"),
|
||||
("changeFillPatterns", "boolean"),
|
||||
("changeFillGradients", "boolean"),
|
||||
("changeStrokePattern", "boolean"),
|
||||
("changeLineWidths", "number"),
|
||||
("transformAbout", "Transformation"),
|
||||
],
|
||||
),
|
||||
),
|
||||
]);
|
||||
page_item.extend(
|
||||
[
|
||||
@@ -3398,10 +3468,6 @@ fn classes(link: &Link) -> Vec<HostClass> {
|
||||
"wrapOffset",
|
||||
"wrapped",
|
||||
"bringInPerspective",
|
||||
"resize",
|
||||
"rotate",
|
||||
"transform",
|
||||
"translate",
|
||||
]
|
||||
.into_iter()
|
||||
.map(|m| later(l, "PageItem", m)),
|
||||
|
||||
@@ -24,7 +24,7 @@ use vectorcraft_js::{Data, HostError, MemberInfo};
|
||||
use super::{Answer, Described, Host, Link, arg, method, named, num, returns, text};
|
||||
|
||||
/// A matrix's six values: `[a, b, c, d, tx, ty]`.
|
||||
type Matrix = [f64; 6];
|
||||
pub(super) type Matrix = [f64; 6];
|
||||
|
||||
const KEYS: [&str; 6] = ["mValueA", "mValueB", "mValueC", "mValueD", "mValueTX", "mValueTY"];
|
||||
|
||||
@@ -85,7 +85,7 @@ fn record(m: Matrix) -> Answer {
|
||||
}
|
||||
|
||||
/// The matrix argument `d`.
|
||||
fn matrix(d: &Data, what: &str) -> std::result::Result<Matrix, HostError> {
|
||||
pub(super) fn matrix(d: &Data, what: &str) -> std::result::Result<Matrix, HostError> {
|
||||
let bad = || HostError::Type(format!("{what} must be a Matrix"));
|
||||
let Data::Object(items) = d else { return Err(bad()) };
|
||||
let mut m = [0.0; 6];
|
||||
@@ -241,18 +241,18 @@ fn nearest(sums: Parts) -> f64 {
|
||||
v
|
||||
}
|
||||
|
||||
fn translate(dx: f64, dy: f64) -> Matrix {
|
||||
pub(super) fn translate(dx: f64, dy: f64) -> Matrix {
|
||||
[1.0, 0.0, 0.0, 1.0, dx, dy]
|
||||
}
|
||||
|
||||
/// A scale by `sx` and `sy` percent.
|
||||
fn scaled(sx: f64, sy: f64) -> Matrix {
|
||||
pub(super) fn scaled(sx: f64, sy: f64) -> Matrix {
|
||||
[sx / 100.0, 0.0, 0.0, sy / 100.0, 0.0, 0.0]
|
||||
}
|
||||
|
||||
/// A turn of `degrees` counterclockwise, exact at quarter turns. The remainder keeps the sign of
|
||||
/// `degrees` and is exact, so an angle next to a quarter turn is not rounded onto it.
|
||||
fn rotate(degrees: f64) -> Matrix {
|
||||
pub(super) fn rotate(degrees: f64) -> Matrix {
|
||||
let turn = degrees % 360.0;
|
||||
let (sin, cos) = match turn {
|
||||
0.0 => (0.0, 1.0),
|
||||
@@ -411,7 +411,19 @@ fn determinant(m: Matrix) -> Wide {
|
||||
products_difference(m[0], m[3], m[1], m[2])
|
||||
}
|
||||
|
||||
fn singular(m: Matrix) -> bool {
|
||||
/// The square root of the size of `m`'s determinant: the factor by which `m` scales lengths on
|
||||
/// average. It is infinite only when that factor is too large for a number.
|
||||
pub(super) fn area_scale(m: Matrix) -> f64 {
|
||||
let d = determinant(m);
|
||||
let (mut v, mut e) = (d.m.abs(), d.e);
|
||||
if e % 2 != 0 {
|
||||
v *= 2.0;
|
||||
e -= 1;
|
||||
}
|
||||
Wide::new(v.sqrt(), e / 2).value()
|
||||
}
|
||||
|
||||
pub(super) fn singular(m: Matrix) -> bool {
|
||||
determinant(m).m == 0.0
|
||||
}
|
||||
|
||||
|
||||
@@ -70,8 +70,8 @@ use vectorcraft_tools::params::gradient_params;
|
||||
|
||||
use super::{
|
||||
Answer, Coords, Described, Doc, Item, Link, NOT_FOUND, ON_LOCKED_ARTBOARD, STALE_ITEM, arg, boolean, class, colors, command, command_value,
|
||||
coordinate, doc_of, edit_item, editable, find_doc, float, frame, get, given, handle_of, id_of, id_parts, item_of, item_rect, later, method,
|
||||
named, num, number, on_doc, pair, point, point_get, point_method, point_property, property, returns, this_doc, typed, whole, with_doc,
|
||||
coordinate, doc_of, edit_item, editable, find_doc, float, frame, get, given, handle_of, id_of, id_parts, item_of, later, method, named, num,
|
||||
number, on_doc, pair, point, point_get, point_method, point_property, property, returns, this_doc, typed, whole, with_doc,
|
||||
};
|
||||
use crate::{DocState, NodeId, NodeKind};
|
||||
|
||||
@@ -1139,131 +1139,37 @@ fn path_set_stroke_overprint(h: &super::Host, a: &[Data]) -> Answer {
|
||||
set_overprint(h, a, false)
|
||||
}
|
||||
|
||||
// ---- PathItem transforms ----
|
||||
// ---- PathItem stroke weights for `resize` ----
|
||||
|
||||
/// The member of `Transformation` that `d` names (left out: `CENTER`).
|
||||
fn about_name(d: &Data) -> std::result::Result<&'static str, HostError> {
|
||||
let name = match d {
|
||||
Data::Undefined => "Transformation.CENTER",
|
||||
Data::String(s) => s.as_str(),
|
||||
_ => return Err(HostError::Type("give a Transformation value".into())),
|
||||
};
|
||||
let members = ENUMS.iter().find(|(e, _)| *e == "Transformation").map_or(&[][..], |(_, m)| *m);
|
||||
let member = name.strip_prefix("Transformation.").and_then(|m| members.iter().find(|x| **x == m));
|
||||
member.copied().ok_or_else(|| HostError::Type("give a Transformation value".into()))
|
||||
}
|
||||
|
||||
/// The point of the path's geometric bounds `r`, in document coordinates, that the `Transformation`
|
||||
/// member `name` ([`about_name`]) names.
|
||||
fn about(h: &super::Host, item: Item, name: &str, r: Rect) -> std::result::Result<Point, HostError> {
|
||||
let (cx, cy) = ((r.x0 + r.x1) / 2.0, (r.y0 + r.y1) / 2.0);
|
||||
Ok(match name {
|
||||
"CENTER" => Point::new(cx, cy),
|
||||
"TOP" => Point::new(cx, r.y0),
|
||||
"BOTTOM" => Point::new(cx, r.y1),
|
||||
"LEFT" => Point::new(r.x0, cy),
|
||||
"RIGHT" => Point::new(r.x1, cy),
|
||||
"TOPLEFT" => Point::new(r.x0, r.y0),
|
||||
"TOPRIGHT" => Point::new(r.x1, r.y0),
|
||||
"BOTTOMLEFT" => Point::new(r.x0, r.y1),
|
||||
"BOTTOMRIGHT" => Point::new(r.x1, r.y1),
|
||||
"DOCUMENTORIGIN" => with_doc(h, item.doc, |_, st| Ok::<_, HostError>(frame(st)?.to_document(Coords::Document, [0.0, 0.0])))?,
|
||||
_ => return Err(HostError::Type("give a Transformation value".into())),
|
||||
})
|
||||
}
|
||||
|
||||
/// The `objects` and `patterns` options of a transform command from the four flags from `i`:
|
||||
/// objects, fill patterns, fill gradients and stroke patterns, each left out or true or false.
|
||||
fn transform_options(a: &[Data], i: usize, params: &mut Value) -> std::result::Result<(), HostError> {
|
||||
let names = ["changePositions", "changeFillPatterns", "changeFillGradients", "changeStrokePattern"];
|
||||
let mut flags = [None; 4];
|
||||
for (k, name) in names.iter().enumerate() {
|
||||
flags[k] = given(arg(a, i + k)).map(|d| boolean(d, name)).transpose()?;
|
||||
}
|
||||
if flags[2] == Some(false) {
|
||||
return Err(HostError::Error(format!("{} false is not available yet: gradients move with the art", names[2])));
|
||||
}
|
||||
if let (Some(f), Some(s)) = (flags[1], flags[3])
|
||||
&& f != s
|
||||
{
|
||||
return Err(HostError::Error(format!("{} and {} must be the same here", names[1], names[3])));
|
||||
}
|
||||
if let Some(o) = params.as_object_mut() {
|
||||
if let Some(b) = flags[0] {
|
||||
o.insert("objects".into(), json!(b));
|
||||
}
|
||||
if let Some(b) = flags[1].or(flags[3]) {
|
||||
o.insert("patterns".into(), json!(b));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `translate(deltaX = 0, deltaY = 0, transformObjects?, transformFillPatterns?, ...)`.
|
||||
fn path_translate(h: &super::Host, a: &[Data]) -> Answer {
|
||||
let dx = given(arg(a, 1)).map_or(Ok(0.0), |d| coordinate(d, "deltaX"))?;
|
||||
let dy = given(arg(a, 2)).map_or(Ok(0.0), |d| coordinate(d, "deltaY"))?;
|
||||
let item = this_path(h, a)?;
|
||||
let mut params = json!({"dx": dx, "dy": if h.dom.coords.get() == Coords::Document { -dy } else { dy }});
|
||||
transform_options(a, 3, &mut params)?;
|
||||
if dx != 0.0 || dy != 0.0 {
|
||||
edit_path(h, item, "object.move", params)?;
|
||||
}
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
/// `rotate(angle, changePositions?, ..., rotateAbout?)`: counterclockwise on the page for a
|
||||
/// positive angle.
|
||||
fn path_rotate(h: &super::Host, a: &[Data]) -> Answer {
|
||||
let angle = number(arg(a, 1), "angle")?;
|
||||
let item = this_path(h, a)?;
|
||||
let place = about_name(arg(a, 6))?;
|
||||
let mut params = json!({"angle": angle});
|
||||
transform_options(a, 2, &mut params)?;
|
||||
if angle.rem_euclid(360.0) != 0.0
|
||||
&& let (Some(r), _) = item_rect(h, item, false)?
|
||||
{
|
||||
let origin = about(h, item, place, r)?;
|
||||
params["origin"] = json!([origin.x, origin.y]);
|
||||
edit_path(h, item, "object.rotate", params)?;
|
||||
}
|
||||
Ok(Data::Undefined)
|
||||
}
|
||||
|
||||
/// `resize(scaleX, scaleY, changePositions?, ..., changeLineWidths?, scaleAbout?)`: 100 is 100%;
|
||||
/// `changeLineWidths` scales the stroke weight by that percent.
|
||||
fn path_resize(h: &super::Host, a: &[Data]) -> Answer {
|
||||
let sx = number(arg(a, 1), "scaleX")?;
|
||||
let sy = number(arg(a, 2), "scaleY")?;
|
||||
if sx == 0.0 || sy == 0.0 || sx.abs() > 100_000.0 || sy.abs() > 100_000.0 {
|
||||
return Err(HostError::Range("scaleX and scaleY must not be 0 and at most 100000 percent".into()));
|
||||
}
|
||||
let widths = given(arg(a, 7)).map(|d| number(d, "changeLineWidths")).transpose()?;
|
||||
if widths.is_some_and(|w| !(0.0..=100_000.0).contains(&w)) {
|
||||
/// The stroke weight `resize`'s `changeLineWidths` of `percent` gives the path `item`, or `None`
|
||||
/// when the weight stays. A `custom` percent, one other than the resize's own scale, is at most
|
||||
/// 100000.
|
||||
pub(super) fn resized_stroke_weight(h: &super::Host, item: Item, percent: f64, custom: bool) -> std::result::Result<Option<f64>, HostError> {
|
||||
if custom && !(0.0..=100_000.0).contains(&percent) {
|
||||
return Err(HostError::Range("changeLineWidths must be from 0 to 100000 percent".into()));
|
||||
}
|
||||
let item = this_path(h, a)?;
|
||||
let place = about_name(arg(a, 8))?;
|
||||
let mut params = json!({"sx": sx, "sy": sy, "basis": "page", "strokes": false});
|
||||
transform_options(a, 3, &mut params)?;
|
||||
let width = look(h, item)?.width;
|
||||
let new_width = widths.map(|w| width * w / 100.0);
|
||||
if new_width.is_some_and(|w| w > MAX_STROKE_WIDTH) {
|
||||
let new_width = width * percent / 100.0;
|
||||
if new_width > MAX_STROKE_WIDTH {
|
||||
return Err(HostError::Range("changeLineWidths would make the stroke weight more than 1000 points".into()));
|
||||
}
|
||||
if (sx != 100.0 || sy != 100.0)
|
||||
&& let (Some(r), _) = item_rect(h, item, false)?
|
||||
{
|
||||
let origin = about(h, item, place, r)?;
|
||||
params["origin"] = json!([origin.x, origin.y]);
|
||||
edit_path(h, item, "object.scale", params)?;
|
||||
}
|
||||
if let Some(w) = new_width
|
||||
&& (w - width).abs() > 1e-9
|
||||
{
|
||||
edit_path(h, item, "stroke.set", json!({"weight": w}))?;
|
||||
}
|
||||
Ok(Data::Undefined)
|
||||
Ok(((new_width - width).abs() > 1e-9).then_some(new_width))
|
||||
}
|
||||
|
||||
/// Whether `item` is a path, so [`resized_stroke_weight`] applies to it.
|
||||
pub(super) fn is_path(h: &super::Host, item: Item) -> bool {
|
||||
with_doc(h, item.doc, |_, st| st.doc.node(item.id).is_some_and(|n| matches!(n.kind, NodeKind::Path { .. })))
|
||||
}
|
||||
|
||||
/// Whether the path `item` is a member of a compound path or compound shape, whose stroke the
|
||||
/// compound holds.
|
||||
pub(super) fn paint_held_by_compound(h: &super::Host, item: Item) -> bool {
|
||||
with_doc(h, item.doc, |_, st| st.doc.node(item.id).is_some_and(|n| paint_owner(&st.doc, item.id, n).id != item.id))
|
||||
}
|
||||
|
||||
/// Sets the stroke weight of the path `item` to `weight` points.
|
||||
pub(super) fn set_stroke_weight(h: &super::Host, item: Item, weight: f64) -> std::result::Result<(), HostError> {
|
||||
edit_path(h, item, "stroke.set", json!({"weight": weight})).map(|_| ())
|
||||
}
|
||||
|
||||
// ---- PathPoints ----
|
||||
@@ -1862,28 +1768,7 @@ fn renumber_selected(sel: &mut crate::doc::Selection, id: NodeId, s: usize, j: u
|
||||
|
||||
/// The members `PathItem` adds to `PageItem`'s.
|
||||
pub(super) fn path_item_members(l: &Link) -> Vec<Described> {
|
||||
let transform = |first: &[(&'static str, &'static str)]| {
|
||||
let mut args: Vec<(&str, &str)> = first.to_vec();
|
||||
args.extend([
|
||||
("changePositions", "boolean"),
|
||||
("changeFillPatterns", "boolean"),
|
||||
("changeFillGradients", "boolean"),
|
||||
("changeStrokePattern", "boolean"),
|
||||
]);
|
||||
args
|
||||
};
|
||||
let mut resize = transform(&[("scaleX", "number"), ("scaleY", "number")]);
|
||||
resize.extend([("changeLineWidths", "number"), ("scaleAbout", "Transformation")]);
|
||||
let mut rotate = transform(&[("angle", "number")]);
|
||||
rotate.push(("rotateAbout", "Transformation"));
|
||||
let translate = [
|
||||
("deltaX", "number"),
|
||||
("deltaY", "number"),
|
||||
("transformObjects", "boolean"),
|
||||
("transformFillPatterns", "boolean"),
|
||||
("transformFillGradients", "boolean"),
|
||||
("transformStrokePattern", "boolean"),
|
||||
];
|
||||
// `translate`, `rotate` and `resize` are `PageItem`'s ([`super::transform`]).
|
||||
let mut m = named(vec![
|
||||
("pathPoints", point_get(l, path_points), MemberInfo { collection: true, ..typed("PathPoints") }),
|
||||
("closed", point_property(l, path_closed, path_set_closed), typed("boolean")),
|
||||
@@ -1909,9 +1794,6 @@ pub(super) fn path_item_members(l: &Link) -> Vec<Described> {
|
||||
("strokeMiterLimit", property(l, path_miter, path_set_miter), typed("number")),
|
||||
("strokeDashes", property(l, path_dashes, path_set_dashes), typed("Array")),
|
||||
("strokeDashOffset", property(l, path_dash_offset, path_set_dash_offset), typed("number")),
|
||||
("translate", method(l, path_translate), returns("undefined", &translate)),
|
||||
("rotate", method(l, path_rotate), returns("undefined", &rotate)),
|
||||
("resize", method(l, path_resize), returns("undefined", &resize)),
|
||||
("selectedPathPoints", get(l, path_selected_points), typed("Array")),
|
||||
]);
|
||||
m.extend(["polarity", "resolution"].into_iter().map(|n| later(l, "PathItem", n)));
|
||||
|
||||
@@ -110,9 +110,10 @@ fn stored(h: &Host, key: &str) -> Option<ScriptPreference> {
|
||||
}
|
||||
|
||||
/// `Number(text)`: blank text is 0, `0x`, `0o` and `0b` start a whole number in base 16, 8 or 2,
|
||||
/// and text that is not a number is NaN.
|
||||
/// and text that is not a number is NaN. The whitespace trimmed is JavaScript's: Unicode's
|
||||
/// `White_Space` without U+0085 (NEXT LINE), and U+FEFF.
|
||||
fn text_number(t: &str) -> f64 {
|
||||
let t = t.trim_matches(|c: char| c.is_whitespace() || c == '\u{feff}');
|
||||
let t = t.trim_matches(|c: char| (c.is_whitespace() && c != '\u{85}') || c == '\u{feff}');
|
||||
if t.is_empty() {
|
||||
return 0.0;
|
||||
}
|
||||
@@ -123,9 +124,7 @@ fn text_number(t: &str) -> f64 {
|
||||
_ => 0,
|
||||
};
|
||||
if radix != 0 {
|
||||
let digits = t.get(2..).unwrap_or("");
|
||||
let whole = digits.chars().try_fold(0.0_f64, |n, c| c.to_digit(radix).map(|d| n * f64::from(radix) + f64::from(d)));
|
||||
return whole.filter(|_| !digits.is_empty()).unwrap_or(f64::NAN);
|
||||
return radix_number(t.get(2..).unwrap_or(""), radix).unwrap_or(f64::NAN);
|
||||
}
|
||||
match t.strip_prefix(['+', '-']).unwrap_or(t) {
|
||||
"Infinity" => {
|
||||
@@ -140,6 +139,44 @@ fn text_number(t: &str) -> f64 {
|
||||
}
|
||||
}
|
||||
|
||||
/// The whole number `digits` writes in base `radix` (16, 8 or 2), rounded once to the nearest
|
||||
/// number, ties to the even one, and infinite past the largest; `None` when it is empty or holds a
|
||||
/// character that is not a digit of that base.
|
||||
fn radix_number(digits: &str, radix: u32) -> Option<f64> {
|
||||
if digits.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let width = radix.trailing_zeros();
|
||||
// The first 64 bits from the leading 1, how many bits come after them, and whether any of
|
||||
// those is 1.
|
||||
let (mut top, mut taken, mut past, mut sticky) = (0u64, 0u32, 0u64, false);
|
||||
for c in digits.chars() {
|
||||
let d = c.to_digit(radix)?;
|
||||
for bit in (0..width).rev().map(|i| (d >> i) & 1 == 1) {
|
||||
if taken == 0 && !bit {
|
||||
continue;
|
||||
}
|
||||
if taken < 64 {
|
||||
top = (top << 1) | u64::from(bit);
|
||||
taken += 1;
|
||||
} else {
|
||||
past = past.saturating_add(1);
|
||||
sticky |= bit;
|
||||
}
|
||||
}
|
||||
}
|
||||
if taken <= 53 {
|
||||
return Some(top as f64);
|
||||
}
|
||||
// Keep 53 bits; the dropped ones round them to the nearest, ties to even.
|
||||
let drop = taken - 53;
|
||||
let (kept, rest, half) = (top >> drop, top & ((1u64 << drop) - 1), 1u64 << (drop - 1));
|
||||
let up = rest > half || (rest == half && (sticky || kept & 1 == 1));
|
||||
let kept = kept + u64::from(up);
|
||||
let exp = i32::try_from(u64::from(drop).saturating_add(past)).unwrap_or(i32::MAX).min(2000);
|
||||
Some(kept as f64 * 2f64.powi(exp))
|
||||
}
|
||||
|
||||
#[allow(clippy::cast_precision_loss)]
|
||||
fn as_number(v: &ScriptPreference) -> f64 {
|
||||
match v {
|
||||
|
||||
@@ -0,0 +1,348 @@
|
||||
//! The transform methods of a page item, `translate`, `rotate`, `resize` and `transform`, as the
|
||||
//! help page <https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/> describes them. Each one
|
||||
//! runs `object.transform` on the object, with its selection kept, so it joins the run's one undo
|
||||
//! step for the document; a call that changes nothing runs no command. `PathItem` uses these
|
||||
//! methods too.
|
||||
//!
|
||||
//! VectorCraft's own rules, which the help page does not state:
|
||||
//! - Offsets, angles and matrices are taken with Y up, as `Matrix` records are, whatever
|
||||
//! `app.coordinateSystem` is: `translate(0, 10)` moves the object up, and a positive angle turns
|
||||
//! it counterclockwise.
|
||||
//! - `rotate`, `resize` and `transform` act about the center of the object's geometric bounds,
|
||||
//! unless a `Transformation` value names another point of those bounds; `DOCUMENTORIGIN` is the
|
||||
//! bottom-left corner of the first artboard. A matrix's own translation is added after it acts
|
||||
//! about that point. The value is checked even when the call changes nothing.
|
||||
//! - Positions, pattern fills and pattern strokes, and gradients each follow their argument:
|
||||
//! positions and gradients default to `true`, and patterns to the Transform Pattern Tiles
|
||||
//! preference. Fill and stroke patterns transform together, and gradients with the object, so a
|
||||
//! call whose values differ, counting the defaults of the arguments it leaves out, throws an error
|
||||
//! that says so.
|
||||
//! - `changeLineWidths` is 100 (stroke weights stay, also the default) or the transformation's own
|
||||
//! scale in percent, the square root of the area it scales by (stroke weights and effects scale
|
||||
//! with it, as Scale Strokes & Effects does). `resize` on a path also takes any percent from 0 to
|
||||
//! 100000, which sets the stroke weight to that percent of what it was, up to 1000 points. Any
|
||||
//! other value, and a scale of strokes and effects with positions left as they are, throws an
|
||||
//! error that says so.
|
||||
//! - A locked or hidden object, one inside a locked or hidden layer or group, a group that holds a
|
||||
//! locked object, and an object on a locked artboard are refused with nothing changed, and so are
|
||||
//! a scale of 0, a matrix whose determinant is 0 and a transformation that would take the object
|
||||
//! past the canvas.
|
||||
|
||||
use serde_json::json;
|
||||
use vectorcraft_geom::{Affine, Point, Rect};
|
||||
use vectorcraft_js::{Data, HostError};
|
||||
|
||||
use super::matrix::{self, Matrix};
|
||||
use super::{Answer, Coords, Host, Item, arg, atomically, coordinate, edit_item, frame, number, paths, this_item, with_doc};
|
||||
|
||||
/// The error for an object on a locked artboard.
|
||||
const ON_LOCKED_ARTBOARD: &str = "cannot transform objects on a locked artboard";
|
||||
|
||||
/// The error for a locked object.
|
||||
const LOCKED: &str = "cannot transform locked objects";
|
||||
|
||||
/// The error for a hidden object.
|
||||
const HIDDEN: &str = "cannot transform hidden objects";
|
||||
|
||||
/// The identity matrix.
|
||||
const IDENTITY: Matrix = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0];
|
||||
|
||||
/// What a transform method changes besides the object's geometry.
|
||||
struct Options {
|
||||
/// Positions and orientations (`changePositions`, `transformObjects`).
|
||||
objects: bool,
|
||||
/// Pattern fills and strokes.
|
||||
patterns: bool,
|
||||
/// Stroke weights and effects (`changeLineWidths`).
|
||||
strokes: bool,
|
||||
}
|
||||
|
||||
/// An optional `true` or `false` argument.
|
||||
fn flag(d: &Data, what: &str) -> std::result::Result<Option<bool>, HostError> {
|
||||
match d {
|
||||
Data::Undefined => Ok(None),
|
||||
Data::Bool(b) => Ok(Some(*b)),
|
||||
_ => Err(HostError::Type(format!("{what} must be true or false"))),
|
||||
}
|
||||
}
|
||||
|
||||
/// The positions, fill patterns, fill gradients and stroke patterns arguments at `at` and after,
|
||||
/// with the names the method gives them.
|
||||
fn options(h: &Host, a: &[Data], at: usize, names: [&str; 4]) -> std::result::Result<Options, HostError> {
|
||||
let tiles = h.session.borrow().prefs.transform_pattern_tiles;
|
||||
let objects = flag(arg(a, at), names[0])?.unwrap_or(true);
|
||||
let fill = flag(arg(a, at + 1), names[1])?.unwrap_or(tiles);
|
||||
let gradients = flag(arg(a, at + 2), names[2])?.unwrap_or(true);
|
||||
let stroke = flag(arg(a, at + 3), names[3])?.unwrap_or(tiles);
|
||||
if fill != stroke {
|
||||
return Err(HostError::Error(format!("{} and {} must be the same here", names[1], names[3])));
|
||||
}
|
||||
if gradients != objects {
|
||||
return Err(HostError::Error(format!("{} different from {} is not available yet", names[2], names[0])));
|
||||
}
|
||||
Ok(Options { objects, patterns: fill, strokes: false })
|
||||
}
|
||||
|
||||
/// Whether `changeLineWidths` (`d`) is the scale of the linear part `m` of a matrix, so stroke
|
||||
/// weights and effects scale with it (`Some(true)`), or 100 (`Some(false)`); `None` for any other
|
||||
/// number.
|
||||
fn own_line_widths(d: &Data, m: Matrix) -> std::result::Result<(Option<bool>, f64, f64), HostError> {
|
||||
let lw = match d {
|
||||
Data::Undefined => return Ok((Some(false), 100.0, 100.0)),
|
||||
d => number(d, "changeLineWidths")?,
|
||||
};
|
||||
if lw < 0.0 {
|
||||
return Err(HostError::Range("changeLineWidths must not be negative".into()));
|
||||
}
|
||||
// The determinant is taken past the range of a number, so a scale whose square is too large
|
||||
// for one still has its own value.
|
||||
// 100 keeps the stroke weights, even for a scale within the tolerance of it.
|
||||
let own = matrix::area_scale(m) * 100.0;
|
||||
if (lw - 100.0).abs() <= 1e-9 {
|
||||
return Ok((Some(false), lw, own));
|
||||
}
|
||||
if lw > 0.0 && own.is_finite() && (lw - own).abs() <= 1e-9 * own {
|
||||
return Ok((Some((own - 100.0).abs() > 1e-9), lw, own));
|
||||
}
|
||||
Ok((None, lw, own))
|
||||
}
|
||||
|
||||
/// The error for a `changeLineWidths` the method does not take.
|
||||
fn other_line_widths(own: f64) -> HostError {
|
||||
HostError::Error(format!("changeLineWidths other than 100 or the scale itself ({own}) is not available yet"))
|
||||
}
|
||||
|
||||
/// Whether `changeLineWidths` (`d`) scales stroke weights for the linear part `m` of a matrix.
|
||||
fn line_widths(d: &Data, m: Matrix) -> std::result::Result<bool, HostError> {
|
||||
match own_line_widths(d, m)? {
|
||||
(Some(strokes), _, _) => Ok(strokes),
|
||||
(None, _, own) => Err(other_line_widths(own)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The member of `Transformation` that `d` names (left out: `CENTER`).
|
||||
fn anchor_name(d: &Data) -> std::result::Result<&str, HostError> {
|
||||
const MEMBERS: [&str; 10] = ["CENTER", "TOPLEFT", "TOP", "TOPRIGHT", "LEFT", "RIGHT", "BOTTOMLEFT", "BOTTOM", "BOTTOMRIGHT", "DOCUMENTORIGIN"];
|
||||
let name = match d {
|
||||
Data::Undefined => "CENTER",
|
||||
Data::String(s) => s.strip_prefix("Transformation.").unwrap_or(""),
|
||||
_ => "",
|
||||
};
|
||||
if MEMBERS.contains(&name) { Ok(name) } else { Err(HostError::Type("the point to transform about must be a Transformation value".into())) }
|
||||
}
|
||||
|
||||
/// The point of `r` (document coordinates, Y down) that the `Transformation` member `name`
|
||||
/// ([`anchor_name`]) names.
|
||||
fn anchor(h: &Host, item: Item, r: Rect, name: &str) -> std::result::Result<Point, HostError> {
|
||||
let (cx, cy) = ((r.x0 + r.x1) / 2.0, (r.y0 + r.y1) / 2.0);
|
||||
Ok(match name {
|
||||
"TOPLEFT" => Point::new(r.x0, r.y0),
|
||||
"TOP" => Point::new(cx, r.y0),
|
||||
"TOPRIGHT" => Point::new(r.x1, r.y0),
|
||||
"LEFT" => Point::new(r.x0, cy),
|
||||
"RIGHT" => Point::new(r.x1, cy),
|
||||
"BOTTOMLEFT" => Point::new(r.x0, r.y1),
|
||||
"BOTTOM" => Point::new(cx, r.y1),
|
||||
"BOTTOMRIGHT" => Point::new(r.x1, r.y1),
|
||||
"DOCUMENTORIGIN" => with_doc(h, item.doc, |_, st| frame(st).map(|f| f.to_document(Coords::Document, [0.0, 0.0])))?,
|
||||
_ => Point::new(cx, cy),
|
||||
})
|
||||
}
|
||||
|
||||
/// The matrix `m` (Y up) as it acts on the page (Y down), about `o`.
|
||||
fn on_page(m: Matrix, o: Point) -> Affine {
|
||||
let [a, b, c, d, tx, ty] = m;
|
||||
let (b, c, ty) = (0.0 - b, 0.0 - c, 0.0 - ty);
|
||||
if [a, b, c, d] == [1.0, 0.0, 0.0, 1.0] {
|
||||
return Affine::translate((tx, ty));
|
||||
}
|
||||
Affine::translate((o.x + tx, o.y + ty)) * Affine::new([a, b, c, d, 0.0, 0.0]) * Affine::translate((-o.x, -o.y))
|
||||
}
|
||||
|
||||
/// Whether the object `id` of `d` stays within the canvas under `xf` (page coordinates), symbol
|
||||
/// instances measured by their art as [`vectorcraft_doc::Document::bounds_of`] measures them. The
|
||||
/// object is measured whole, and a group is looked into object by object, as the native file's
|
||||
/// canvas check does (`vectorcraft_doc::canvas_range`), since a clipping group's bounds are its
|
||||
/// clipping path's and leave out the art it clips.
|
||||
fn fits(d: &vectorcraft_doc::Document, id: vectorcraft_doc::NodeId, xf: Affine) -> bool {
|
||||
fn within(n: &vectorcraft_doc::Node, symbols: &vectorcraft_doc::SymbolBoxes<'_>) -> bool {
|
||||
if matches!(n.kind, vectorcraft_doc::NodeKind::Group { .. } | vectorcraft_doc::NodeKind::Layer { .. }) {
|
||||
n.children().into_iter().flatten().all(|c| within(c, symbols))
|
||||
} else {
|
||||
n.geometric_bounds_with(symbols).is_none_or(crate::sanity::rect_in_range)
|
||||
}
|
||||
}
|
||||
d.node(id).is_some_and(|n| {
|
||||
let mut n = n.clone();
|
||||
n.transform(xf, false);
|
||||
within(&n, &d.symbol_boxes())
|
||||
})
|
||||
}
|
||||
|
||||
/// Applies `m` (Y up) to `item`, about the point `about` names (`None`: the matrix acts as a move,
|
||||
/// which needs no point), with `opts`, then sets the stroke weight of a path to `weight` points
|
||||
/// when it is given.
|
||||
fn apply(h: &Host, item: Item, m: Matrix, about: Option<&Data>, opts: &Options, weight: Option<f64>) -> Answer {
|
||||
let about = about.map(anchor_name).transpose()?;
|
||||
if m.iter().any(|v| !v.is_finite()) {
|
||||
return Err(HostError::Range("the transformation has a value too large for a number".into()));
|
||||
}
|
||||
if matrix::singular(m) {
|
||||
return Err(HostError::Error("the transformation is singular and would flatten the object".into()));
|
||||
}
|
||||
let (locked, hidden, on_locked, bounds, uses_pattern, clipped) = with_doc(h, item.doc, |_, st| {
|
||||
let d = &st.doc;
|
||||
let line = d.ancestry(item.id);
|
||||
let mut locked = line.as_ref().is_none_or(|a| a.iter().any(|i| d.node(*i).is_none_or(|n| n.locked)));
|
||||
let hidden = line.as_ref().is_none_or(|a| a.iter().chain(std::iter::once(&item.id)).any(|i| d.node(*i).is_none_or(|n| !n.visible)));
|
||||
let (mut uses, mut clipped) = (false, false);
|
||||
if let Some(n) = d.node(item.id) {
|
||||
n.walk(&mut |c| {
|
||||
locked |= c.locked;
|
||||
uses |= vectorcraft_doc::pattern::uses_pattern(c, None);
|
||||
clipped |=
|
||||
matches!(c.kind, vectorcraft_doc::NodeKind::Group { clip: true, .. } | vectorcraft_doc::NodeKind::Layer { clip: true, .. });
|
||||
});
|
||||
}
|
||||
(locked, hidden, d.on_locked_artboard(item.id), d.bounds_of(&[item.id], false), uses, clipped)
|
||||
});
|
||||
if locked {
|
||||
return Err(HostError::Error(format!("{LOCKED}: {}", item.id.0)));
|
||||
}
|
||||
if hidden {
|
||||
return Err(HostError::Error(format!("{HIDDEN}: {}", item.id.0)));
|
||||
}
|
||||
if on_locked {
|
||||
return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {}", item.id.0)));
|
||||
}
|
||||
// The identity acts the same about every point, so an object without bounds (an empty path)
|
||||
// takes it too.
|
||||
let o = match (about, bounds) {
|
||||
_ if m == IDENTITY => Point::ORIGIN,
|
||||
(Some(name), Some(r)) => anchor(h, item, r, name)?,
|
||||
(Some(_), None) => return Err(HostError::Error("the object has no bounds".into())),
|
||||
(None, _) => Point::ORIGIN,
|
||||
};
|
||||
let xf = on_page(m, o);
|
||||
if opts.strokes && !opts.objects {
|
||||
return Err(HostError::Error("changeLineWidths other than 100 with changePositions false is not available yet".into()));
|
||||
}
|
||||
if opts.objects && xf != Affine::IDENTITY {
|
||||
// The transformed corners of the bounds hold the transformed object. When one of them is
|
||||
// past the canvas, or the object holds a clipping group (whose bounds leave out the art
|
||||
// it clips), the transformed object itself is measured.
|
||||
let inside = |p: Point| p.x.abs() <= crate::MAX_COORD && p.y.abs() <= crate::MAX_COORD;
|
||||
let outside = bounds.is_some_and(|r| {
|
||||
let corners = [Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x0, r.y1), Point::new(r.x1, r.y1)];
|
||||
!corners.iter().all(|p| inside(xf * *p))
|
||||
});
|
||||
if (clipped || outside) && !with_doc(h, item.doc, |_, st| fits(&st.doc, item.id, xf)) {
|
||||
return Err(HostError::Range("the transformation would take the object past the canvas".into()));
|
||||
}
|
||||
}
|
||||
let c = xf.as_coeffs();
|
||||
let identity = xf == Affine::IDENTITY;
|
||||
let changes = if opts.objects { !identity } else { opts.patterns && uses_pattern && !identity };
|
||||
// The transformation and the stroke weight change together or not at all.
|
||||
atomically(h, |h| {
|
||||
if changes {
|
||||
let p = json!({"ids": [item.id.0], "matrix": c, "objects": opts.objects, "patterns": opts.patterns, "strokes": opts.strokes});
|
||||
edit_item(h, item, "object.transform", &p)?;
|
||||
}
|
||||
if let Some(w) = weight {
|
||||
paths::set_stroke_weight(h, item, w)?;
|
||||
}
|
||||
Ok(Data::Undefined)
|
||||
})
|
||||
}
|
||||
|
||||
/// `translate(deltaX?, deltaY?, transformObjects?, transformFillPatterns?, transformFillGradients?,
|
||||
/// transformStrokePatterns?)`: moves the object by `deltaX` and `deltaY` points (0 when left out).
|
||||
pub(super) fn translate(h: &Host, a: &[Data]) -> Answer {
|
||||
let delta = |i: usize, what: &str| match arg(a, i) {
|
||||
Data::Undefined => Ok(0.0),
|
||||
d => number(d, what),
|
||||
};
|
||||
let (dx, dy) = (delta(1, "deltaX")?, delta(2, "deltaY")?);
|
||||
let names = ["transformObjects", "transformFillPatterns", "transformFillGradients", "transformStrokePatterns"];
|
||||
let opts = options(h, a, 3, names)?;
|
||||
let item = this_item(h, a)?;
|
||||
// An offset past the canvas is refused only when the call moves the object or a pattern it
|
||||
// uses.
|
||||
let limit = coordinate(&Data::Number(dx), "deltaX").and_then(|_| coordinate(&Data::Number(dy), "deltaY"));
|
||||
if let Err(e) = limit {
|
||||
let moves = opts.objects
|
||||
|| opts.patterns
|
||||
&& with_doc(h, item.doc, |_, st| {
|
||||
st.doc.node(item.id).is_some_and(|n| {
|
||||
let mut uses = false;
|
||||
n.walk(&mut |c| uses |= vectorcraft_doc::pattern::uses_pattern(c, None));
|
||||
uses
|
||||
})
|
||||
});
|
||||
if moves {
|
||||
return Err(e);
|
||||
}
|
||||
}
|
||||
apply(h, item, matrix::translate(dx, dy), None, &opts, None)
|
||||
}
|
||||
|
||||
const CHANGE_NAMES: [&str; 4] = ["changePositions", "changeFillPatterns", "changeFillGradients", "changeStrokePattern"];
|
||||
|
||||
/// `rotate(angle, changePositions?, changeFillPatterns?, changeFillGradients?, changeStrokePattern?,
|
||||
/// rotateAbout?)`: turns the object by `angle` degrees, counterclockwise when it is positive.
|
||||
pub(super) fn rotate(h: &Host, a: &[Data]) -> Answer {
|
||||
let angle = number(arg(a, 1), "angle")?;
|
||||
let opts = options(h, a, 2, CHANGE_NAMES)?;
|
||||
apply(h, this_item(h, a)?, matrix::rotate(angle), Some(arg(a, 6)), &opts, None)
|
||||
}
|
||||
|
||||
/// `resize(scaleX, scaleY, changePositions?, changeFillPatterns?, changeFillGradients?,
|
||||
/// changeStrokePattern?, changeLineWidths?, scaleAbout?)`: scales the object by `scaleX` and
|
||||
/// `scaleY` percent along the page's axes.
|
||||
pub(super) fn resize(h: &Host, a: &[Data]) -> Answer {
|
||||
let (sx, sy) = (number(arg(a, 1), "scaleX")?, number(arg(a, 2), "scaleY")?);
|
||||
if sx == 0.0 || sy == 0.0 {
|
||||
return Err(HostError::Range("scaleX and scaleY must not be 0".into()));
|
||||
}
|
||||
let m = matrix::scaled(sx, sy);
|
||||
let mut opts = options(h, a, 3, CHANGE_NAMES)?;
|
||||
let item = this_item(h, a)?;
|
||||
let weight = match own_line_widths(arg(a, 7), m)? {
|
||||
// The compound holds a member's visible stroke, so its weight is set through the compound
|
||||
// as well as the member's own strokes and effects scaling, by the scale itself.
|
||||
(Some(true), _, own) if paths::is_path(h, item) && paths::paint_held_by_compound(h, item) => {
|
||||
opts.strokes = true;
|
||||
paths::resized_stroke_weight(h, item, own, false)?
|
||||
}
|
||||
(Some(strokes), _, _) => {
|
||||
opts.strokes = strokes;
|
||||
None
|
||||
}
|
||||
(None, lw, _) if paths::is_path(h, item) => paths::resized_stroke_weight(h, item, lw, true)?,
|
||||
(None, _, own) => return Err(other_line_widths(own)),
|
||||
};
|
||||
apply(h, item, m, Some(arg(a, 8)), &opts, weight)
|
||||
}
|
||||
|
||||
/// `transform(transformationMatrix, changePositions?, changeFillPatterns?, changeFillGradients?,
|
||||
/// changeStrokePattern?, changeLineWidths?, transformAbout?)`: applies a `Matrix` record to the
|
||||
/// object.
|
||||
pub(super) fn transform(h: &Host, a: &[Data]) -> Answer {
|
||||
let m = matrix::matrix(arg(a, 1), "transformationMatrix")?;
|
||||
let mut opts = options(h, a, 2, CHANGE_NAMES)?;
|
||||
let item = this_item(h, a)?;
|
||||
let weight = match own_line_widths(arg(a, 6), m)? {
|
||||
// As in `resize`: the compound holds a member's visible stroke, so its weight is set
|
||||
// through the compound as well.
|
||||
(Some(true), _, own) if paths::is_path(h, item) && paths::paint_held_by_compound(h, item) => {
|
||||
opts.strokes = true;
|
||||
paths::resized_stroke_weight(h, item, own, false)?
|
||||
}
|
||||
_ => {
|
||||
opts.strokes = line_widths(arg(a, 6), m)?;
|
||||
None
|
||||
}
|
||||
};
|
||||
apply(h, item, m, Some(arg(a, 7)), &opts, weight)
|
||||
}
|
||||
@@ -651,7 +651,8 @@ impl World {
|
||||
/// The commands that can change the clipboard and still fail, or still be put back because their
|
||||
/// result cannot reach the script, and that do not put it back themselves. The clipboard can hold
|
||||
/// a great deal, so a savepoint copies it only for these.
|
||||
const CAN_FAIL_AFTER_COPYING: &[&str] = &["action.batch", "artboard.copy", "artboard.cut", "command.batch", "edit.copy", "edit.cut"];
|
||||
const CAN_FAIL_AFTER_COPYING: &[&str] =
|
||||
&["action.batch", "artboard.copy", "artboard.cut", "clipboard.importSvg", "command.batch", "edit.copy", "edit.cut"];
|
||||
|
||||
/// The commands that remove a document's undo history, or the document: a savepoint keeps a whole
|
||||
/// copy of the histories for these. Any other command that removes or changes a step under the
|
||||
@@ -1363,8 +1364,9 @@ fn step(s: &mut Session, host: &Host, id: &str, params: &Value) -> Result<(Value
|
||||
raise_ids(s);
|
||||
s.script_style_trail = StyleTrail::start(s);
|
||||
let mutating = waits_for_tool_edit(id);
|
||||
// Inside an object-model call's own savepoint ([`dom`]), that savepoint puts a failure back.
|
||||
let save = (mutating && !host.dom.saving()).then(|| Savepoint::take(s, id));
|
||||
// Inside an object-model call's own savepoint ([`dom`]), that savepoint puts a failure back. A
|
||||
// query that fills the clipboard (`clipboard.importSvg`) takes one too, for the clipboard.
|
||||
let save = ((mutating || CAN_FAIL_AFTER_COPYING.contains(&id)) && !host.dom.saving()).then(|| Savepoint::take(s, id));
|
||||
let before: Vec<(u64, Arc<crate::Document>, u64)> =
|
||||
if mutating { s.docs.iter().map(|d| (d.uid, d.doc.clone(), d.doc.peek_next_id())).collect() } else { Vec::new() };
|
||||
crate::file_access::start_recording_writes();
|
||||
@@ -2113,6 +2115,13 @@ impl Session {
|
||||
self.script_key.as_ref().and_then(|k| with_job(k, |j| j.host.dialogs.waiting())).flatten()
|
||||
}
|
||||
|
||||
/// Whether [`Session::script_dialog`] is the confirm the app opened to turn off the external
|
||||
/// script warning, which only a person answers Yes to. A script's own confirm with the same
|
||||
/// text is not.
|
||||
pub fn script_dialog_turns_warning_off(&self) -> bool {
|
||||
self.script_dialog().is_some() && self.script_key.as_ref().and_then(|k| with_job(k, |j| j.host.dialogs.asks_warning_off())).unwrap_or(false)
|
||||
}
|
||||
|
||||
/// Gives the dialog the running script waits at its answer; the next [`Session::script_pump`]
|
||||
/// goes on from the call. → false when nothing waits, the answer is for another kind of
|
||||
/// dialog, or a prompt's text is longer than [`dialogs::MAX_PROMPT_BYTES`]. Yes to a confirm the
|
||||
|
||||
@@ -189,6 +189,7 @@ mod script_dom_images;
|
||||
mod script_dom_paths;
|
||||
mod script_dom_prefs;
|
||||
mod script_dom_tracing;
|
||||
mod script_dom_transform;
|
||||
mod script_engines;
|
||||
mod script_folder;
|
||||
mod script_include;
|
||||
|
||||
@@ -1559,7 +1559,7 @@ fn page_item_members_not_built_yet_throw_on_read_and_assignment() {
|
||||
for source in [
|
||||
"app.activeDocument.pageItems[0].isIsolated;",
|
||||
"app.activeDocument.pageItems[0].uuid = 'x';",
|
||||
"app.activeDocument.pageItems[0].transform(5);",
|
||||
"app.activeDocument.pageItems[0].bringInPerspective(0, 0);",
|
||||
] {
|
||||
assert!(failure(&mut s, source).contains("is not available yet"), "{source}");
|
||||
}
|
||||
@@ -1815,6 +1815,46 @@ fn document_preset_applies_only_its_given_fields() {
|
||||
assert_eq!(s.documents().len(), 2, "settings the built-in preset refuses make no document");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_startup_preset_uses_its_own_size_beside_a_saved_preset_of_the_same_name() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.newPresets.save", &json!({"name": "Letter", "width": 300, "height": 200})).unwrap();
|
||||
let first = crate::cmd::newdoc::category(&s, "Print").unwrap().remove(0);
|
||||
assert_eq!(first.name, "Letter");
|
||||
let out = log(&mut s, "var d = app.documents.addDocument('Print'); vc.log([d.width, d.height]);");
|
||||
assert_eq!((out[0][0].as_f64(), out[0][1].as_f64()), (Some(first.width), Some(first.height)), "{out:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn document_presets_hold_a_limited_amount_of_data() {
|
||||
let mut s = Session::new();
|
||||
// A 4,096-byte title fits and replacing it does not add up; one byte more is refused.
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var t = 'x'; for (var k = 0; k < 12; k++) t += t; var p = new DocumentPreset();\
|
||||
for (var k = 0; k < 20; k++) p.title = t; vc.log(p.title.length);",
|
||||
);
|
||||
assert_eq!(out, vec![json!(4096)]);
|
||||
let e = failure(&mut s, "var t = 'x'; for (var k = 0; k < 12; k++) t += t; var p = new DocumentPreset(); p.title = t + 'x';");
|
||||
assert!(e.contains("the title is too long"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn moving_art_on_another_layer_keeps_the_current_layer() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
let a = s.active().unwrap().current_layer().unwrap();
|
||||
s.execute("layer.new", &json!({})).unwrap();
|
||||
let b = s.active().unwrap().current_layer().unwrap();
|
||||
assert_ne!(a, b);
|
||||
rect(&mut s, 10.0, 20.0, 30.0, 40.0);
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
s.active_mut().unwrap().active_layer = Some(a);
|
||||
log(&mut s, "var i = app.activeDocument.pageItems[0]; i.left = i.left + 5; i.translate(5, 0);");
|
||||
assert_eq!(s.active().unwrap().current_layer(), Some(a));
|
||||
assert!(s.active().unwrap().selection.objects.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn headless_add_document_dialog_fails_without_creating() {
|
||||
let mut s = Session::new();
|
||||
@@ -2662,7 +2702,7 @@ fn page_items_report_their_available_members_as_their_own() {
|
||||
vc.log([p.hasOwnProperty('opacity'), p.hasOwnProperty('typename'), p.hasOwnProperty('duplicate'),\
|
||||
Object.prototype.hasOwnProperty.call(p, 'name'), p.propertyIsEnumerable('opacity'), d.hasOwnProperty('selection'),\
|
||||
app.hasOwnProperty('activeDocument')]);\
|
||||
vc.log([p.hasOwnProperty('isIsolated'), p.hasOwnProperty('transform'), d.hasOwnProperty('layers'),\
|
||||
vc.log([p.hasOwnProperty('isIsolated'), p.hasOwnProperty('bringInPerspective'), d.hasOwnProperty('layers'),\
|
||||
p.hasOwnProperty('nosuch'), p.hasOwnProperty('hasOwnProperty'), p.hasOwnProperty('constructor')]);\
|
||||
vc.log([keys.indexOf('opacity') >= 0, keys.indexOf('typename') >= 0, keys.indexOf('duplicate'), keys.indexOf('isIsolated')]);",
|
||||
);
|
||||
|
||||
@@ -734,6 +734,39 @@ fn filled_true_on_a_compound_member_places_the_gradient_on_the_compound() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resizing_a_compound_member_with_its_own_line_width_scales_the_compound_stroke() {
|
||||
let (mut s, a, b) = doc();
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
s.execute("object.compoundPath.make", &json!({})).unwrap();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var p = app.activeDocument.pathItems[0]; p.strokeWidth = 4; p.resize(50, 50, true, true, true, true, 50);\
|
||||
vc.log(p.strokeWidth); vc.log(app.activeDocument.pathItems[1].strokeWidth);",
|
||||
);
|
||||
assert_eq!(out, vec![json!(2), json!(2)], "the compound's stroke halves with the member");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transforming_a_compound_member_with_its_own_line_width_scales_the_compound_stroke() {
|
||||
let (mut s, a, b) = doc();
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
s.execute("object.compoundPath.make", &json!({})).unwrap();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var p = app.activeDocument.pathItems[0]; p.strokeWidth = 4; p.transform(app.getScaleMatrix(50), true, true, true, true, 50);\
|
||||
vc.log(p.strokeWidth); vc.log(app.activeDocument.pathItems[1].strokeWidth);",
|
||||
);
|
||||
assert_eq!(out, vec![json!(2), json!(2)], "transform scales the compound's stroke as resize does");
|
||||
// 100 keeps the weight even when the scale is within the tolerance of 100%.
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var p = app.activeDocument.pathItems[0]; p.transform(app.getScaleMatrix(100.00000005), true, true, true, true, 100);\
|
||||
vc.log(p.strokeWidth);",
|
||||
);
|
||||
assert_eq!(out, vec![json!(2)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_anchors_reads_smooth_false_as_a_corner() {
|
||||
let (mut s, a, _) = doc();
|
||||
@@ -1203,7 +1236,7 @@ fn locked_paths_and_wrong_objects_are_refused() {
|
||||
("app.activeDocument.pathItems[0].setEntirePath([[0, 0], [1, 1]]);", "Cannot edit PathItem"),
|
||||
("app.activeDocument.pathItems[0].pathPoints[0].anchor = [1, 1];", "Cannot edit PathItem"),
|
||||
("app.activeDocument.pathItems[0].strokeWidth = 3;", "Cannot edit PathItem"),
|
||||
("app.activeDocument.pathItems[0].translate(5, 5);", "Cannot edit PathItem"),
|
||||
("app.activeDocument.pathItems[0].translate(5, 5);", "cannot transform locked objects"),
|
||||
] {
|
||||
let e = failure(&mut s, source);
|
||||
assert!(e.contains(part), "{source}: {e}");
|
||||
@@ -1236,10 +1269,10 @@ fn rotate_positive_is_counterclockwise_and_transforms_move_and_scale() {
|
||||
assert_eq!(out[3], json!(6));
|
||||
assert!(failure(&mut s, "app.activeDocument.pathItems[0].rotate(10, true, true, true, true, 'CENTER');").contains("Transformation"));
|
||||
assert!(failure(&mut s, "app.activeDocument.pathItems[0].resize(0, 100);").contains("scaleX"));
|
||||
assert!(failure(&mut s, "app.activeDocument.pathItems[0].translate(1, 2, 'no');").contains("changePositions"));
|
||||
assert!(failure(&mut s, "app.activeDocument.pathItems[0].translate(1, 2, 'no');").contains("transformObjects"));
|
||||
let before = art(&s);
|
||||
for (source, part) in [
|
||||
("app.activeDocument.pathItems[0].translate(1, 2, true, true, false);", "changeFillGradients false"),
|
||||
("app.activeDocument.pathItems[0].translate(1, 2, true, false, false);", "transformFillGradients different from transformObjects"),
|
||||
("app.activeDocument.pathItems[0].rotate(10, true, true, true, false);", "must be the same"),
|
||||
("app.activeDocument.pathItems.ellipse(10, 10, 5, 5, false, true);", "inscribed"),
|
||||
(
|
||||
@@ -1543,18 +1576,16 @@ fn path_changes_refuse_paths_on_a_locked_artboard() {
|
||||
let (mut s, a, _) = doc();
|
||||
s.execute("artboard.setProps", &json!({"index": 0, "locked": true})).unwrap();
|
||||
let (before, steps) = (art(&s), undo_steps(&s));
|
||||
// Points (waiting and written at once), paint, stroke and a transform.
|
||||
for change in [
|
||||
"p.closed = false;",
|
||||
"p.pathPoints[0].anchor = [1, 2];",
|
||||
"p.setEntirePath([[0, 0], [10, 10]]);",
|
||||
"p.filled = false;",
|
||||
"p.strokeWidth = 7;",
|
||||
"p.translate(5, 5);",
|
||||
] {
|
||||
// Points (waiting and written at once), paint and stroke.
|
||||
for change in
|
||||
["p.closed = false;", "p.pathPoints[0].anchor = [1, 2];", "p.setEntirePath([[0, 0], [10, 10]]);", "p.filled = false;", "p.strokeWidth = 7;"]
|
||||
{
|
||||
let e = failure(&mut s, &format!("var p = app.activeDocument.pathItems[0]; {change}"));
|
||||
assert!(e.contains(&format!("Cannot edit PathItem {}: it is on a locked artboard", a.0)), "{change}: {e}");
|
||||
}
|
||||
// A transform is PageItem's, which refuses any object on a locked artboard.
|
||||
let e = failure(&mut s, "app.activeDocument.pathItems[0].translate(5, 5);");
|
||||
assert!(e.contains(&format!("cannot transform objects on a locked artboard: {}", a.0)), "{e}");
|
||||
let e = failure(&mut s, "app.activeDocument.pathItems.removeAll();");
|
||||
assert!(e.contains("cannot delete objects on a locked artboard"), "{e}");
|
||||
assert_eq!((art(&s), undo_steps(&s)), (before.clone(), steps));
|
||||
|
||||
@@ -106,6 +106,7 @@ fn yes_to_the_confirm_turns_the_warning_off() {
|
||||
preset: String::new(),
|
||||
};
|
||||
assert_eq!(s.script_dialog(), Some(want));
|
||||
assert!(s.script_dialog_turns_warning_off());
|
||||
assert!(s.prefs.show_external_script_warning, "nothing changes while the confirm waits");
|
||||
assert!(s.script_answer(DialogAnswer::Confirm(true)));
|
||||
let r = pump(&mut s).unwrap().unwrap();
|
||||
@@ -114,6 +115,17 @@ fn yes_to_the_confirm_turns_the_warning_off() {
|
||||
assert!(!s.prefs.show_external_script_warning);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_script_confirm_with_the_same_text_is_not_the_warning_question() {
|
||||
let mut s = Session::new();
|
||||
framed(&mut s, &format!("vc.log(confirm({}));", json!(WARNING_OFF_QUESTION)));
|
||||
assert_eq!(s.script_dialog().map(|d| d.message), Some(WARNING_OFF_QUESTION.to_string()));
|
||||
assert!(!s.script_dialog_turns_warning_off());
|
||||
assert!(s.script_answer(DialogAnswer::Confirm(true)));
|
||||
let r = pump(&mut s).unwrap().unwrap();
|
||||
assert_eq!(r["log"], json!([true]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn turning_the_warning_on_after_yes_keeps_it_on() {
|
||||
let mut s = Session::new();
|
||||
@@ -201,8 +213,15 @@ fn missing_keys_read_as_empty_values_and_getters_convert() {
|
||||
vc.log([isNaN(p.getRealPreference('x')), p.getIntegerPreference('x')]);\
|
||||
vc.log([p.getStringPreference('b'), p.getRealPreference('b'), p.getBooleanPreference('i'), p.getStringPreference('i')]);\
|
||||
var n = []; ['0x10', '0B101', '0o17', '-0x10', '0x', ' -Infinity ', '1e3', '.5', 'inf', '1_0'].forEach(function (t) {\
|
||||
p.setStringPreference('n', t); n.push(String(p.getRealPreference('n'))); }); vc.log(n.join(' '));",
|
||||
p.setStringPreference('n', t); n.push(String(p.getRealPreference('n'))); }); vc.log(n.join(' '));\
|
||||
p.setStringPreference('n', '0x200000000000018'); var r = [p.getRealPreference('n') === Math.pow(2, 57) + 32];\
|
||||
p.setStringPreference('n', '0x' + new Array(301).join('f')); r.push(String(p.getRealPreference('n')));\
|
||||
p.setStringPreference('n', '0b' + new Array(60).join('0') + '1' + new Array(53).join('0') + '1'); r.push(p.getRealPreference('n') === Math.pow(2, 53));\
|
||||
vc.log(r);",
|
||||
);
|
||||
// Each whole number in base 16, 8 or 2 is rounded once: 2^57 + 24 to 2^57 + 32, 1,200 bits to
|
||||
// Infinity, and 2^53 + 1 after leading zeros to 2^53 (ties to even).
|
||||
assert_eq!(out.pop(), Some(json!([true, "Infinity", true])));
|
||||
assert_eq!(out.pop(), Some(json!("16 5 15 NaN NaN -Infinity 1000 0.5 NaN NaN")));
|
||||
assert_eq!(
|
||||
out,
|
||||
@@ -210,6 +229,31 @@ fn missing_keys_read_as_empty_values_and_getters_convert() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_reads_trim_javascript_whitespace_only() {
|
||||
let mut s = Session::new();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var p = app.preferences; var r = [];\
|
||||
['\\u0085' + '42', '\\ufeff 42\\u00a0', '\\u2028' + '42\\u3000'].forEach(function (t) {\
|
||||
p.setStringPreference('n', t); r.push(String(p.getRealPreference('n'))); }); vc.log(r.join(' '));",
|
||||
);
|
||||
assert_eq!(out, vec![json!("NaN 42 42")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_real_preference_changes_between_zero_and_negative_zero() {
|
||||
let mut s = Session::new();
|
||||
log(&mut s, "app.preferences.setRealPreference('z', -0);");
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var p = app.preferences; vc.log(String(1 / p.getRealPreference('z'))); p.setRealPreference('z', 0); vc.log(String(1 / p.getRealPreference('z')));",
|
||||
);
|
||||
assert_eq!(out, vec![json!("-Infinity"), json!("Infinity")]);
|
||||
// The change is kept when the run's keys are merged with the app's.
|
||||
assert_eq!(stored(&s, "z").map(|v| matches!(v, ScriptPreference::Real(r) if r.to_bits() == 0)), Some(true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_arguments_throw_and_store_nothing() {
|
||||
let mut s = Session::new();
|
||||
@@ -474,6 +518,22 @@ fn concatenation_keeps_a_finite_result_whose_products_leave_the_range_of_a_numbe
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_concatenated_translation_next_to_the_largest_number_is_rounded_once() {
|
||||
let mut s = Session::new();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"function mat(v) { return {mValueA: v[0], mValueB: v[1], mValueC: v[2], mValueD: v[3], mValueTX: v[4], mValueTY: v[5]}; }\
|
||||
var a = Math.pow(2, 969), b = Math.pow(2, 970);\
|
||||
function tx(f, t) { try { return app.concatenateMatrix(mat([1, 0, 0, 1, Number.MAX_VALUE, f]), mat([1, 0, 1, 1, t, 0])).mValueTX === Number.MAX_VALUE; }\
|
||||
catch (e) { return e.name; } }\
|
||||
vc.log(tx(-a, b)); vc.log(tx(a, a));",
|
||||
);
|
||||
// MAX + 2^969 is below the halfway point to 2^1024, and MAX + 2^970 is that point, which rounds
|
||||
// to 2^1024.
|
||||
assert_eq!(out, vec![json!(true), json!("RangeError")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_turn_just_short_of_a_negative_quarter_turn_is_not_rounded_to_it() {
|
||||
let mut s = Session::new();
|
||||
@@ -655,11 +715,13 @@ fn a_copy_or_cut_the_run_puts_back_is_not_reported() {
|
||||
"try { vc.run('command.batch', {commands: [{command: 'edit.copy', params: {}}]}); } catch (e) { vc.log(e.name); }\
|
||||
try { vc.run('edit.cut'); } catch (e) { vc.log(e.name); }\
|
||||
try { vc.run('edit.copy'); } catch (e) { vc.log(e.name); }\
|
||||
try { vc.run('artboard.copy', {indices: [0]}); } catch (e) { vc.log(e.name); }",
|
||||
try { vc.run('artboard.copy', {indices: [0]}); } catch (e) { vc.log(e.name); }\
|
||||
try { vc.run('clipboard.importSvg', {svg: '<svg xmlns=\"http://www.w3.org/2000/svg\"><rect width=\"5\" height=\"5\"/></svg>'}); }\
|
||||
catch (e) { vc.log(e.name); }",
|
||||
);
|
||||
crate::script::TEST_RESULT_BYTES.with(|b| b.set(None));
|
||||
let r = r.unwrap();
|
||||
assert_eq!(r["log"], json!(["RangeError", "RangeError", "RangeError", "RangeError"]), "{r}");
|
||||
assert_eq!(r["log"], json!(["RangeError", "RangeError", "RangeError", "RangeError", "RangeError"]), "{r}");
|
||||
assert_eq!(r.get("copied"), None, "{r}");
|
||||
assert_eq!(s.copies, copies);
|
||||
assert!(s.clipboard_copied);
|
||||
|
||||
@@ -0,0 +1,341 @@
|
||||
//! The script object model: a page item's `translate`, `rotate`, `resize` and `transform`.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::*;
|
||||
|
||||
fn run(s: &mut Session, source: &str) -> Result<Value> {
|
||||
s.execute("script.run", &json!({"source": source, "name": "t.js"}))
|
||||
}
|
||||
|
||||
/// What the run logged.
|
||||
fn log(s: &mut Session, source: &str) -> Vec<Value> {
|
||||
let r = run(s, source).unwrap_or_else(|e| panic!("{source}: {e}"));
|
||||
r["log"].as_array().cloned().unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The message of the run's failure.
|
||||
fn failure(s: &mut Session, source: &str) -> String {
|
||||
run(s, source).map(|r| panic!("{source} ran: {r}")).unwrap_err().to_string()
|
||||
}
|
||||
|
||||
fn rect(s: &mut Session, x: f64, y: f64, w: f64, h: f64) -> NodeId {
|
||||
NodeId(s.execute("shape.rectangle", &json!({"x": x, "y": y, "width": w, "height": h})).unwrap()["id"].as_u64().unwrap())
|
||||
}
|
||||
|
||||
/// A 400 × 300 pt document with a 30 × 40 pt rectangle above a 50 × 50 pt one, so that `pageItems`
|
||||
/// (topmost first) lists the 30 × 40 pt one first.
|
||||
fn doc() -> (Session, NodeId, NodeId) {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
let b = rect(&mut s, 100.0, 100.0, 50.0, 50.0);
|
||||
let a = rect(&mut s, 10.0, 20.0, 30.0, 40.0);
|
||||
(s, a, b)
|
||||
}
|
||||
|
||||
fn undo_steps(s: &Session) -> usize {
|
||||
s.active().unwrap().history.undo.len()
|
||||
}
|
||||
|
||||
/// The numbers of a logged array, or a logged number as one.
|
||||
fn numbers(v: &Value) -> Vec<f64> {
|
||||
match v.as_array() {
|
||||
Some(a) => a.iter().map(|n| n.as_f64().unwrap()).collect(),
|
||||
None => vec![v.as_f64().unwrap()],
|
||||
}
|
||||
}
|
||||
|
||||
fn close(a: &[f64], b: &[f64]) -> bool {
|
||||
a.len() == b.len() && a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-6)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn translate_moves_by_the_offsets_with_y_up_in_one_undo_step() {
|
||||
let (mut s, a, _) = doc();
|
||||
let steps = undo_steps(&s);
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var i = app.activeDocument.pageItems[0]; var l = i.left, t = i.top;\
|
||||
i.translate(10, 0); vc.log([i.left - l, i.top - t]);\
|
||||
i.translate(0, 10); vc.log([i.left - l, i.top - t]);\
|
||||
app.coordinateSystem = CoordinateSystem.ARTBOARDCOORDINATESYSTEM; var t2 = i.top;\
|
||||
i.translate(0, 5); vc.log(i.top - t2);",
|
||||
);
|
||||
assert!(close(&numbers(&out[0]), &[10.0, 0.0]), "{out:?}");
|
||||
assert!(close(&numbers(&out[1]), &[10.0, 10.0]), "{out:?}");
|
||||
// With Y down from the artboard's top, a move up reads as a smaller top.
|
||||
assert!(close(&numbers(&out[2]), &[-5.0]), "{out:?}");
|
||||
assert_eq!(undo_steps(&s), steps + 1, "one undo step for the run");
|
||||
s.execute("edit.undo", &json!({})).unwrap();
|
||||
let r = s.active().unwrap().doc.bounds_of(&[a], false).unwrap();
|
||||
assert!(close(&[r.x0, r.y0], &[10.0, 20.0]), "{r:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rotate_turns_counterclockwise_about_the_center_or_the_named_point() {
|
||||
let (mut s, a, b) = doc();
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
s.execute("object.group", &json!({})).unwrap();
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var g = app.activeDocument.pageItems[0], r = g.geometricBounds; vc.log(g.typename);\
|
||||
vc.log([g.width, g.height, (r[0] + r[2]) / 2, (r[1] + r[3]) / 2]);\
|
||||
g.rotate(90); r = g.geometricBounds; vc.log([g.width, g.height, (r[0] + r[2]) / 2, (r[1] + r[3]) / 2]);",
|
||||
);
|
||||
assert_eq!(out[0], json!("GroupItem"));
|
||||
let (before, after) = (numbers(&out[1]), numbers(&out[2]));
|
||||
// The width and height trade places, and the center stays.
|
||||
assert!(close(&after, &[before[1], before[0], before[2], before[3]]), "{before:?} {after:?}");
|
||||
|
||||
// A positive angle about the bottom-left corner swings a rectangle to the left of that corner.
|
||||
let (mut s, _, _) = doc();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var i = app.activeDocument.pageItems[0]; vc.log(i.geometricBounds);\
|
||||
i.rotate(90, true, true, true, true, Transformation.BOTTOMLEFT); vc.log(i.geometricBounds);",
|
||||
);
|
||||
let (b0, b1) = (numbers(&out[0]), numbers(&out[1]));
|
||||
// [left, top, right, bottom], Y up: the 30 pt wide side now stands up, and the 40 pt tall side
|
||||
// lies to the left.
|
||||
assert!(close(&b1, &[b0[0] - 40.0, b0[3] + 30.0, b0[0], b0[3]]), "{b0:?} {b1:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resize_scales_about_the_center_and_line_widths_follow_their_argument() {
|
||||
let (mut s, _, _) = doc();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var p = app.activeDocument.pageItems, i = p[0], j = p[1];\
|
||||
function stroke(o) { return (o.visibleBounds[2] - o.visibleBounds[0]) - o.width; }\
|
||||
var r = i.geometricBounds, s0 = stroke(i); i.resize(50, 50); var q = i.geometricBounds;\
|
||||
vc.log([i.width, i.height, (q[0] + q[2]) - (r[0] + r[2]), (q[1] + q[3]) - (r[1] + r[3]), stroke(i) - s0]);\
|
||||
var s1 = stroke(j); j.resize(50, 50, true, true, true, true, 50); vc.log([s0, stroke(j) / s1]);",
|
||||
);
|
||||
let first = numbers(&out[0]);
|
||||
assert!(close(&first, &[15.0, 20.0, 0.0, 0.0, 0.0]), "{first:?}");
|
||||
let second = numbers(&out[1]);
|
||||
assert!(second[0] > 0.0, "the rectangles have a stroke: {second:?}");
|
||||
assert!(close(&second[1..], &[0.5]), "{second:?}");
|
||||
// On a path, any other line width sets the stroke weight to that percent of what it was.
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var i = app.activeDocument.pageItems[0], w = i.strokeWidth; i.resize(50, 50, true, true, true, true, 70); vc.log(i.strokeWidth / w);",
|
||||
);
|
||||
assert!(close(&numbers(&out[0]), &[0.7]), "{out:?}");
|
||||
// On a group, a line width that is neither 100 nor the scale itself is refused.
|
||||
s.execute("select.all", &json!({})).unwrap();
|
||||
s.execute("object.group", &json!({})).unwrap();
|
||||
let e = failure(&mut s, "app.activeDocument.pageItems[0].resize(50, 50, true, true, true, true, 70);");
|
||||
assert!(e.contains("changeLineWidths") && e.contains("not available yet"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transform_applies_a_matrix_record_about_the_center() {
|
||||
let (mut s, _, _) = doc();
|
||||
let steps = undo_steps(&s);
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var i = app.activeDocument.pageItems[0], r = i.geometricBounds;\
|
||||
i.transform(app.getRotationMatrix(45)); var q = i.geometricBounds;\
|
||||
vc.log([i.width, i.height, (q[0] + q[2]) - (r[0] + r[2]), (q[1] + q[3]) - (r[1] + r[3])]);\
|
||||
var l = i.left; i.transform(app.getTranslationMatrix(5, 0)); vc.log(i.left - l);",
|
||||
);
|
||||
let side = 70.0 / 2f64.sqrt();
|
||||
assert!(close(&numbers(&out[0]), &[side, side, 0.0, 0.0]), "{out:?}");
|
||||
assert!(close(&numbers(&out[1]), &[5.0]), "{out:?}");
|
||||
assert_eq!(undo_steps(&s), steps + 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transforms_that_change_nothing_add_no_undo_step() {
|
||||
let (mut s, _, _) = doc();
|
||||
let steps = undo_steps(&s);
|
||||
log(
|
||||
&mut s,
|
||||
"var i = app.activeDocument.pageItems[0]; i.translate(); i.translate(0, 0); i.rotate(0); i.rotate(360);\
|
||||
i.resize(100, 100); i.transform(app.getIdentityMatrix()); i.translate(10, 0, false, false, false, false);\
|
||||
i.translate(7000000, 0, false, false, false, false);\
|
||||
i.transform(app.getScaleMatrix(Math.pow(2, 600) * 100), false, false, false, false, 100);",
|
||||
);
|
||||
assert_eq!(undo_steps(&s), steps);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_scale_whose_square_is_too_large_for_a_number_keeps_its_own_line_width() {
|
||||
let (mut s, _, _) = doc();
|
||||
let call = "app.activeDocument.pageItems[0].transform(app.getScaleMatrix(Math.pow(2, 600) * 100), false, false, false, false, 70);";
|
||||
let e = failure(&mut s, call);
|
||||
assert!(e.contains("other than 100 or the scale itself"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_line_width_of_zero_is_not_the_scale_itself_however_small_the_scale() {
|
||||
let (mut s, _, _) = doc();
|
||||
let call = "app.activeDocument.pageItems[0].transform(app.getScaleMatrix(1e-10), true, false, true, false, 0);";
|
||||
let e = failure(&mut s, call);
|
||||
assert!(e.contains("other than 100 or the scale itself"), "{e}");
|
||||
// A positive request still matches a tiny scale of its own.
|
||||
log(&mut s, "app.activeDocument.pageItems[0].transform(app.getScaleMatrix(1e-10), true, false, true, false, 1e-10);");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_offset_past_the_canvas_is_taken_when_the_call_moves_nothing() {
|
||||
let (mut s, _, _) = doc();
|
||||
let before = s.active().unwrap().doc.clone();
|
||||
log(&mut s, "app.activeDocument.pageItems[0].translate(1e20, 0, false, false, false, false);");
|
||||
// The object uses no pattern, so moving patterns moves nothing either.
|
||||
log(&mut s, "app.activeDocument.pageItems[0].translate(1e20, 0, false, true, false, true);");
|
||||
assert_eq!(*s.active().unwrap().doc, *before);
|
||||
let e = failure(&mut s, "app.activeDocument.pageItems[0].translate(Infinity, 0, false, false, false, false);");
|
||||
assert!(e.contains("finite number"), "{e}");
|
||||
let e = failure(&mut s, "app.activeDocument.pageItems[0].translate(1e20, 0);");
|
||||
assert!(e.contains("outside the canvas"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_move_too_small_to_round_away_moves_the_object() {
|
||||
let (mut s, _, _) = doc();
|
||||
let steps = undo_steps(&s);
|
||||
let out = log(&mut s, "var i = app.activeDocument.pageItems[0], l = i.left; i.translate(5e-13, 0); vc.log(i.left > l);");
|
||||
assert_eq!(out, vec![json!(true)]);
|
||||
assert_eq!(undo_steps(&s), steps + 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_tiny_move_about_a_distant_center_moves_the_object() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
// The center is at x = 100, where 1e-15 rounds away; the left edge at 0 keeps it.
|
||||
rect(&mut s, 0.0, 0.0, 200.0, 10.0);
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var i = app.activeDocument.pageItems[0], l = i.left;\
|
||||
i.transform({mValueA: 1, mValueB: 0, mValueC: 0, mValueD: 1, mValueTX: 1e-15, mValueTY: 0}); vc.log(i.left > l);",
|
||||
);
|
||||
assert_eq!(out, vec![json!(true)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_scale_and_translation_about_the_center_straddle_the_origin() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
let line = NodeId(s.execute("shape.line", &json!({"x1": 127, "y1": 0, "x2": 129, "y2": 0})).unwrap()["id"].as_u64().unwrap());
|
||||
log(
|
||||
&mut s,
|
||||
"app.activeDocument.pageItems[0].transform({mValueA: Math.pow(2, -55), mValueB: 0, mValueC: 0, mValueD: 1, mValueTX: -128, mValueTY: 0});",
|
||||
);
|
||||
let r = s.active().unwrap().doc.bounds_of(&[line], false).unwrap();
|
||||
assert!(r.x0 < 0.0 && r.x1 > 0.0, "{r:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_clipped_object_moved_past_the_canvas_is_refused() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
let far = rect(&mut s, 0.9 * crate::MAX_COORD, 0.0, 10.0, 10.0);
|
||||
let mask = rect(&mut s, 0.0, 0.0, 10.0, 10.0);
|
||||
s.execute("select.set", &json!({"ids": [far.0, mask.0]})).unwrap();
|
||||
s.execute("object.clippingMask.make", &json!({})).unwrap();
|
||||
let before = s.active().unwrap().doc.clone();
|
||||
let e = failure(&mut s, &format!("app.activeDocument.pageItems[0].translate({}, 0);", 0.2 * crate::MAX_COORD));
|
||||
assert!(e.contains("past the canvas"), "{e}");
|
||||
assert_eq!(s.active().unwrap().doc.node(far), before.node(far));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_transformation_whose_bounds_reach_past_the_canvas_is_kept_when_the_art_does_not() {
|
||||
let mut s = Session::new();
|
||||
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
|
||||
// A diagonal line through the origin, 0.6 of the canvas limit out each way.
|
||||
let a = 0.6 * crate::MAX_COORD;
|
||||
let line = NodeId(s.execute("shape.line", &json!({"x1": -a, "y1": a, "x2": a, "y2": -a})).unwrap()["id"].as_u64().unwrap());
|
||||
s.execute("select.none", &json!({})).unwrap();
|
||||
// On the page (Y down), x' = x + y about the center: the line becomes upright at x = 0, while
|
||||
// a corner of its bounds would go to 1.2 times the limit.
|
||||
log(
|
||||
&mut s,
|
||||
"var m = {mValueA: 1, mValueB: 0, mValueC: -1, mValueD: 1, mValueTX: 0, mValueTY: 0};\
|
||||
app.activeDocument.pageItems[0].transform(m);",
|
||||
);
|
||||
let r = s.active().unwrap().doc.bounds_of(&[line], false).unwrap();
|
||||
assert!(r.width() < 1e-6 && (r.height() - 2.0 * a).abs() < 1e-3, "{r:?}");
|
||||
// The same shear twice takes the line itself past the canvas.
|
||||
let e = failure(
|
||||
&mut s,
|
||||
"var m = {mValueA: 1, mValueB: 0, mValueC: -2, mValueD: 1, mValueTX: 0, mValueTY: 0};\
|
||||
app.activeDocument.pageItems[0].transform(m);",
|
||||
);
|
||||
assert!(e.contains("past the canvas"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn locked_art_and_art_on_a_locked_artboard_are_refused() {
|
||||
let (mut s, a, b) = doc();
|
||||
let before = s.active().unwrap().doc.clone();
|
||||
let steps = undo_steps(&s);
|
||||
for call in ["translate(5, 0)", "rotate(30)", "resize(50, 50)", "transform(app.getScaleMatrix(200))"] {
|
||||
let e = failure(&mut s, &format!("var i = app.activeDocument.pageItems[0]; i.locked = true; i.{call};"));
|
||||
assert!(e.contains(&format!("cannot transform locked objects: {}", a.0)), "{call}: {e}");
|
||||
}
|
||||
assert_eq!(undo_steps(&s), steps);
|
||||
assert_eq!(*s.active().unwrap().doc, *before);
|
||||
// A group that holds a locked object is refused too.
|
||||
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
|
||||
s.execute("object.group", &json!({})).unwrap();
|
||||
s.execute("object.setProps", &json!({"ids": [b.0], "locked": true})).unwrap();
|
||||
let (before, steps) = (s.active().unwrap().doc.clone(), undo_steps(&s));
|
||||
let e = failure(&mut s, "app.activeDocument.pageItems[0].translate(5, 0);");
|
||||
assert!(e.contains("cannot transform locked objects"), "{e}");
|
||||
assert_eq!(undo_steps(&s), steps);
|
||||
assert_eq!(*s.active().unwrap().doc, *before);
|
||||
s.execute("object.setProps", &json!({"ids": [b.0], "locked": false})).unwrap();
|
||||
s.edit("Lock Artboard", |d, _| {
|
||||
d.artboards[0].locked = true;
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
let steps = undo_steps(&s);
|
||||
let e = failure(&mut s, "app.activeDocument.pageItems[1].rotate(45);");
|
||||
assert!(e.contains("cannot transform objects on a locked artboard"), "{e}");
|
||||
assert_eq!(undo_steps(&s), steps);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_arguments_throw_and_change_nothing() {
|
||||
let (mut s, _, _) = doc();
|
||||
let before = s.active().unwrap().doc.clone();
|
||||
let steps = undo_steps(&s);
|
||||
for (call, says) in [
|
||||
("rotate('x')", "angle must be a finite number"),
|
||||
("rotate()", "angle must be a finite number"),
|
||||
("resize(50)", "scaleY must be a finite number"),
|
||||
("resize(0, 50)", "must not be 0"),
|
||||
("resize(50, 50, true, true, true, true, -1)", "changeLineWidths must not be negative"),
|
||||
("transform({})", "transformationMatrix must be a Matrix"),
|
||||
("transform(app.getScaleMatrix(0))", "singular"),
|
||||
("translate(1, 0, 'yes')", "transformObjects must be true or false"),
|
||||
("translate(7000000, 0)", "past the canvas"),
|
||||
("translate('x')", "deltaX must be a finite number"),
|
||||
("translate(NaN)", "is not a finite number"),
|
||||
("rotate(5, true, false, false)", "changeFillGradients different from changePositions"),
|
||||
("rotate(5, true, true, true, false)", "changeFillPatterns and changeStrokePattern"),
|
||||
// Left out, the stroke pattern follows the Transform Pattern Tiles preference (off), and
|
||||
// gradients default to true.
|
||||
("rotate(5, true, true)", "changeFillPatterns and changeStrokePattern"),
|
||||
("translate(10, 0, false)", "transformFillGradients different from transformObjects"),
|
||||
("rotate(5, true, true, true, true, 'Transformation.NOPE')", "Transformation value"),
|
||||
("rotate(5, true, true, true, true, 3)", "Transformation value"),
|
||||
("resize(1e9, 1e9)", "past the canvas"),
|
||||
// Stroke weights cannot scale while the object stays where it is.
|
||||
("resize(50, 50, false, false, false, false, 50)", "with changePositions false is not available yet"),
|
||||
] {
|
||||
let e = failure(&mut s, &format!("app.activeDocument.pageItems[0].{call};"));
|
||||
assert!(e.contains(says), "{call}: {e}");
|
||||
}
|
||||
assert_eq!(undo_steps(&s), steps);
|
||||
assert_eq!(*s.active().unwrap().doc, *before);
|
||||
// A deleted object is stale before its arguments are used.
|
||||
let e = failure(&mut s, "var i = app.activeDocument.pageItems[0]; i.remove(); i.rotate(10);");
|
||||
assert!(e.contains("Stale page item"), "{e}");
|
||||
}
|
||||
@@ -58,8 +58,8 @@ const OUTSIDE: &[(&str, &str, &str)] = &[
|
||||
/// `Document.path` only name its file and folder. `app.open` reads the file it is given, and
|
||||
/// `PlacedItem.file=` and `PlacedItem.relink` read the image file they are given. Reading a
|
||||
/// preference changes nothing, and the matrix functions return new records. `app.copy` and `app.cut`
|
||||
/// fill VectorCraft's clipboard, which the desktop app offers to other apps after the run as
|
||||
/// Edit › Copy does.
|
||||
/// fill VectorCraft's clipboard, which the desktop app offers to other apps after the run as Edit ›
|
||||
/// Copy does.
|
||||
const INSIDE: &[(&str, &str)] = &[
|
||||
("", "$ File Folder UnitValue Window alert confirm localize prompt toSource"),
|
||||
("Window.", "alert confirm length prompt prototype"),
|
||||
@@ -106,10 +106,11 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
(
|
||||
"Application.prototype.",
|
||||
"activeDocument activeDocument= beep beep= concatenateMatrix concatenateRotationMatrix concatenateScaleMatrix \
|
||||
concatenateTranslationMatrix constructor coordinateSystem coordinateSystem= copy cut documents doScript executeMenuCommand \
|
||||
getIdentityMatrix getIsFileOpen getRotationMatrix getScaleMatrix getTranslationMatrix invertMatrix isEqualMatrix \
|
||||
isSingularMatrix loadAction loadAction= open paste PPDFileList preferences printPresetsList printerList redo redraw \
|
||||
selection selection= selectTool textFonts toString typename undo unloadAction unloadAction= userInteractionLevel \
|
||||
concatenateTranslationMatrix constructor coordinateSystem coordinateSystem= copy cut documents doScript \
|
||||
executeMenuCommand getIdentityMatrix getIsFileOpen getRotationMatrix getScaleMatrix getTranslationMatrix \
|
||||
invertMatrix isEqualMatrix isSingularMatrix loadAction loadAction= open paste PPDFileList preferences printPresetsList \
|
||||
printerList redo redraw selection selection= selectTool textFonts toString typename undo unloadAction unloadAction= \
|
||||
userInteractionLevel \
|
||||
userInteractionLevel=",
|
||||
),
|
||||
("Preferences.", "prototype"),
|
||||
@@ -151,8 +152,8 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
"artworkKnockout artworkKnockout= blendingMode blendingMode= bringInPerspective bringInPerspective= constructor \
|
||||
controlBounds duplicate editable geometricBounds height height= hidden hidden= isIsolated isIsolated= layer layer= \
|
||||
left left= locked locked= move name name= note note= opacity opacity= parent pixelAligned pixelAligned= position \
|
||||
position= remove resize resize= rotate rotate= selected selected= sliced sliced= tags toString top top= transform \
|
||||
transform= translate translate= typename uRL uRL= uuid uuid= visibilityVariable visibilityVariable= visibleBounds \
|
||||
position= remove resize rotate selected selected= sliced sliced= tags toString top top= transform translate \
|
||||
typename uRL uRL= uuid uuid= visibilityVariable visibilityVariable= visibleBounds \
|
||||
width width= wrapInside wrapInside= wrapOffset wrapOffset= wrapped wrapped= zOrder zOrderPosition",
|
||||
),
|
||||
("PlacedItems.", "prototype"),
|
||||
@@ -192,10 +193,10 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
(
|
||||
"PathItem.prototype.",
|
||||
"area clipping closed closed= constructor evenodd evenodd= fillColor fillColor= fillOverprint fillOverprint= filled \
|
||||
filled= guides guides= length pathPoints polarity polarity= resize resolution resolution= rotate selectedPathPoints \
|
||||
filled= guides guides= length pathPoints polarity polarity= resolution resolution= selectedPathPoints \
|
||||
setEntirePath strokeCap strokeCap= strokeColor strokeColor= strokeDashOffset strokeDashOffset= \
|
||||
strokeDashes strokeDashes= strokeJoin strokeJoin= strokeMiterLimit strokeMiterLimit= strokeOverprint strokeOverprint= \
|
||||
strokeWidth strokeWidth= stroked stroked= translate",
|
||||
strokeWidth strokeWidth= stroked stroked=",
|
||||
),
|
||||
("PathPoints.", "prototype"),
|
||||
("PathPoints.prototype.", "add constructor index length parent removeAll typename"),
|
||||
|
||||
@@ -118,6 +118,14 @@ pub fn stroke_contains(path: &BezPath, width: f64, tol: f64, p: Point) -> bool {
|
||||
/// filled shape doesn't touch it, so a marquee drawn over a background picks only what is on it
|
||||
/// (#1103).
|
||||
pub fn intersects_rect(path: &PathData, r: Rect) -> bool {
|
||||
// The control box holds every anchor and segment, and the path keeps it measured, so a path
|
||||
// whose control box lies wholly apart from the rect misses it without measuring its segments.
|
||||
// The test is strict: a control box that only touches the rect, or has no area, goes on to the
|
||||
// exact checks below.
|
||||
let (Some(c), n) = (path.control_bounds(), r.abs()) else { return false };
|
||||
if c.x1 < n.x0 || n.x1 < c.x0 || c.y1 < n.y0 || n.y1 < c.y0 {
|
||||
return false;
|
||||
}
|
||||
let Some(b) = path.bounds() else { return false };
|
||||
let degenerate = |x: Rect| x.width() == 0.0 || x.height() == 0.0;
|
||||
if b.intersect(r).area() <= 0.0 && !degenerate(b) && !degenerate(r) {
|
||||
@@ -238,6 +246,30 @@ mod tests {
|
||||
// zero-height marquee missing it
|
||||
assert!(!intersects_rect(&p, Rect::new(20.0, 5.0, 30.0, 5.0)));
|
||||
}
|
||||
|
||||
/// A marquee that lies apart from a path's control box misses it without measuring the path's
|
||||
/// segments. One that reaches the control box but not the curve is still judged on the curve.
|
||||
#[test]
|
||||
fn marquee_apart_from_the_control_box_measures_no_segment() {
|
||||
let p = shapes::ellipse(Rect::new(0.0, 0.0, 10.0, 10.0));
|
||||
let measured = crate::path::measured_segments;
|
||||
let before = measured();
|
||||
assert!(!intersects_rect(&p, Rect::new(20.0, 20.0, 30.0, 30.0)));
|
||||
assert!(!intersects_rect(&p, Rect::new(-30.0, 4.0, -20.0, 6.0)));
|
||||
assert_eq!(measured(), before, "a marquee apart from the control box measures nothing");
|
||||
// A curve whose handle reaches into the marquee while the curve stays below it.
|
||||
use crate::path::{Anchor, SubPath};
|
||||
let arch = PathData::new(vec![SubPath::new(
|
||||
vec![
|
||||
Anchor::with_handles(Point::new(0.0, 0.0), Point::new(0.0, 0.0), Point::new(0.0, 40.0)),
|
||||
Anchor::with_handles(Point::new(10.0, 0.0), Point::new(10.0, 40.0), Point::new(10.0, 0.0)),
|
||||
],
|
||||
false,
|
||||
)]);
|
||||
assert!(!intersects_rect(&arch, Rect::new(-1.0, 35.0, 11.0, 39.0)), "the curve peaks at y 30");
|
||||
assert!(measured() > before, "a marquee inside the control box measures the curve");
|
||||
assert!(intersects_rect(&arch, Rect::new(4.0, 25.0, 6.0, 35.0)), "a marquee across the peak");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -190,8 +190,10 @@ impl Indices {
|
||||
if self.lo >= self.hi {
|
||||
return Ok(None);
|
||||
}
|
||||
// The object may have become one of a host class with an indexer meanwhile, whose
|
||||
// elements are not properties: the rest of the range is then visited index by index.
|
||||
if self.sparse.as_ref().is_some_and(|s| s.epoch != interp.heap.index_epoch) {
|
||||
self.sparse = self.gather(interp)?;
|
||||
self.sparse = if interp.host_indexer(self.obj)?.is_some() { None } else { self.gather(interp)? };
|
||||
}
|
||||
let k = match &mut self.sparse {
|
||||
None if self.ascending => self.lo,
|
||||
|
||||
@@ -414,6 +414,11 @@ impl Interp {
|
||||
let v = self.call_data(&host, &name, &Value::Undefined, &args, &read);
|
||||
self.constructing = was;
|
||||
let v = v?;
|
||||
// `new` gives an object ([[Construct]]): a constructor that gives another value
|
||||
// is a TypeError.
|
||||
if !matches!(v, Value::Object(_)) {
|
||||
return Err(self.type_error(&format!("the constructor {name} did not give an object")));
|
||||
}
|
||||
if let Value::Object(o) = &v
|
||||
&& matches!(self.object(*o)?.class, Class::Ordinary)
|
||||
&& let Some(Prop::Data { value: Value::Object(proto), .. }) = self.find_property(callee, &key("prototype"))?
|
||||
|
||||
@@ -330,12 +330,15 @@ impl Interp {
|
||||
}
|
||||
}
|
||||
if let Some(id) = found {
|
||||
// Its indexer and the indices its prototypes hold can change with its class, so a list
|
||||
// of the indices it has is made again ([`crate::heap::Heap::index_epoch`]).
|
||||
let o = self.object_mut(id)?;
|
||||
if let Class::Host(h) = &mut o.class
|
||||
&& h.class != class
|
||||
{
|
||||
h.class = class;
|
||||
o.proto = Some(proto);
|
||||
self.heap.index_epoch = self.heap.index_epoch.wrapping_add(1);
|
||||
}
|
||||
return Ok(Value::Object(id));
|
||||
}
|
||||
|
||||
@@ -997,6 +997,40 @@ fn a_host_class_constructor_called_with_new_cannot_wait() {
|
||||
assert_eq!(could.get(), Some(false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_on_a_host_constructor_that_gives_a_value_other_than_an_object_throws() {
|
||||
let mut r = realm(1_000_000);
|
||||
let make: HostFunction = Rc::new(|_| Ok(Data::Undefined));
|
||||
with_thing(&mut r, Some(make));
|
||||
let out = r.run("var e; try { new Thing(); } catch (x) { e = x; } [e instanceof TypeError, typeof Thing()].join()").unwrap();
|
||||
assert_eq!(out, JsValue::String("true,undefined".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_array_method_visits_every_element_after_its_object_takes_a_class_with_an_indexer() {
|
||||
let mut r = realm(10_000_000);
|
||||
// `Base` has a length of 5,000, an element `0` on its prototype and no indexer; `Indexed`, of
|
||||
// the same family, gives `list[i]` for each index. `upgrade()` gives the same object as an
|
||||
// `Indexed`.
|
||||
let length: HostFunction = Rc::new(|_| Ok(Data::Number(5_000.0)));
|
||||
let zero: HostFunction = Rc::new(|_| Ok(Data::Number(0.0)));
|
||||
let upgrade: HostFunction = Rc::new(|_| Ok(host_ref("Indexed", &[1.0])));
|
||||
let members = vec![
|
||||
("length".to_string(), HostMember::Get(length)),
|
||||
("0".to_string(), HostMember::Get(zero)),
|
||||
("upgrade".to_string(), HostMember::Method(upgrade)),
|
||||
];
|
||||
let base = HostClass { name: "Base".into(), parent: None, members, info: Vec::new(), index: None, construct: None };
|
||||
let index: HostFunction = Rc::new(|a| Ok(a.get(1).cloned().unwrap_or(Data::Undefined)));
|
||||
let indexed =
|
||||
HostClass { name: "Indexed".into(), parent: Some("Base".into()), members: Vec::new(), info: Vec::new(), index: Some(index), construct: None };
|
||||
r.define_host_classes(vec![base, indexed], vec![("list".into(), host_ref("Base", &[1.0]))]).unwrap();
|
||||
let out = r
|
||||
.run("var n = 0; Array.prototype.forEach.call(list, function () { if (n === 0) list.upgrade(); n++; }); [list instanceof Indexed, n].join()")
|
||||
.unwrap();
|
||||
assert_eq!(out, JsValue::String("true,5000".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn array_methods_visit_every_element_of_a_long_host_list() {
|
||||
let mut r = realm(10_000_000);
|
||||
|
||||
@@ -1991,7 +1991,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"file.print",
|
||||
"Print…",
|
||||
"Cmd+P",
|
||||
"{} open the Print dialog (dialog `print`: the print.setup settings, preset (setting it loads that print preset; Save Preset… saves them as one), printer, toFile; Print keeps the settings with the document and prints, Done (discard: true) only keeps them); with params {preset? (a print preset's name: its settings instead of the document's), settings? (over the document's or the preset's), printer? (print.printers name; \"\" the default), toFile?, path?, format?: pdf|postscript, level?, flattenerPreset?, maxPages? (as engine file.print)} print without it: the print-ready PDF (engine file.print) goes to the printer → {pages, printer, printed: true, warnings}; with toFile, a path or no printing here (no print service) it is saved as a PDF at path (else a picked file, the web downloads it) → {path, pages, printed: false, warnings}; a PostScript file (format postscript, or a .ps path) is always saved that way; a job of more than maxPages pages is neither printed nor saved → {pages, format}",
|
||||
"{} open the Print dialog (dialog `print`: the print.setup settings, preset (setting it loads that print preset; Save Preset… saves them as one), printer, toFile; on desktop, installed printers appear once the background lookup has returned and the dialog has applied the list; ui.dialog.set accepts a named printer once it appears in the list; PDF File is available at once; Print keeps the settings with the document and prints, Done (discard: true) only keeps them); with params {preset? (a print preset's name: its settings instead of the document's), settings? (over the document's or the preset's), printer? (print.printers name; \"\" the default), toFile?, path?, format?: pdf|postscript, level?, flattenerPreset?, maxPages? (as engine file.print)} print without it: the print-ready PDF (engine file.print) goes to the printer → {pages, printer, printed: true, warnings}; with toFile, a path or no printing here (no print service) it is saved as a PDF at path (else a picked file, the web downloads it) → {path, pages, printed: false, warnings}; a PostScript file (format postscript, or a .ps path) is always saved that way; a job of more than maxPages pages is neither printed nor saved → {pages, format}",
|
||||
),
|
||||
(
|
||||
"print.printers",
|
||||
|
||||
@@ -1498,6 +1498,11 @@ fn dispatch(app: &mut VectorcraftApp, ctx: &egui::Context, method: &str, p: &Val
|
||||
};
|
||||
match (set, answer) {
|
||||
(Some(Ok(_)), Some(answer)) => {
|
||||
if answer == "ui.dialog.confirm"
|
||||
&& let Ok(id) = craft::automation::dialogs::dialog_id(host, ¶ms)
|
||||
{
|
||||
crate::dialogs::print::prepare_confirm(app, host, id);
|
||||
}
|
||||
craft::automation::dialogs::dialog_method(host, ctx, answer, &json!({ "dialog": params["dialog"] }))
|
||||
}
|
||||
// A set answers with the dialog it set, `{id, parent, key, fields}`, as production did.
|
||||
|
||||
@@ -24,7 +24,7 @@ use craft::print::ui::{
|
||||
};
|
||||
use craft::ui::buttons::ToggleButton;
|
||||
use craft::ui::choice::Checkbox;
|
||||
use craft::ui::contract::{Bind, Props as _, Show as _, ShowContainer as _};
|
||||
use craft::ui::contract::{Bind, Politeness, Props as _, Show as _, ShowContainer as _, announce};
|
||||
use craft::ui::dialog::{DialogId, StackDialog as _};
|
||||
use craft::ui::display::{Shade, Text};
|
||||
use craft::ui::layout::empty_cell;
|
||||
@@ -119,6 +119,9 @@ struct Open {
|
||||
papers_pending: bool,
|
||||
/// The ids of the Size choices the dialog was last given.
|
||||
media: Vec<String>,
|
||||
/// The printer discovery still running on a background job. The dialog takes its list once it has arrived, so
|
||||
/// PDF File stays available while the system's printers are looked up.
|
||||
discovery: Option<mpsc::Receiver<Vec<Printer>>>,
|
||||
}
|
||||
|
||||
/// The document (uid, revision) and the settings a cached preview belongs to.
|
||||
@@ -292,13 +295,14 @@ fn start(
|
||||
) -> Result<Value, String> {
|
||||
let dialogs = app.dialogs().ok_or("no window to show the dialog in")?;
|
||||
let ctx = app.ui_ctx.clone().ok_or("no window to show the dialog in")?;
|
||||
let (printers, service) = destinations(app);
|
||||
let background = shared_printers(app).is_some();
|
||||
let (printers, service) = if background { (listed(Vec::new(), true), true) } else { destinations(app) };
|
||||
let mut state = State::default();
|
||||
state.settings.destination = Destination::Printer(
|
||||
printers.iter().find(|p| p.default).or(printers.first().filter(|_| service)).map_or_else(|| PDF_FILE.to_string(), |p| p.name.clone()),
|
||||
);
|
||||
state.printers = printers;
|
||||
let header = if service && cfg!(windows) {
|
||||
let mut header = if service && cfg!(windows) {
|
||||
vec![
|
||||
Param::new("directPdf", tl!("Send PDF directly (bypass driver)"), ParamKind::bool(false))
|
||||
.tooltip(tl!("Writes the print-ready PDF to the printer's TCP/IP RAW port, for PCL-only drivers that change the custom page size.")),
|
||||
@@ -306,6 +310,10 @@ fn start(
|
||||
} else {
|
||||
vec![]
|
||||
};
|
||||
header.push(Param::custom("__discovery", "", |ui, fields, _| {
|
||||
let text = if fields.bool("__discovery") == Some(true) { tl!("Finding printers. PDF File and Done are available.") } else { "" };
|
||||
Text::new(text).show(ui)
|
||||
}));
|
||||
let taken: Vec<String> = taken_names(app);
|
||||
let named = editing.clone();
|
||||
let driver = driver(has_setup(app), &state.settings.destination);
|
||||
@@ -325,13 +333,30 @@ fn start(
|
||||
.json_form(|fields, out| out.extend(nested(form::json_of(&KEYS, fields))))
|
||||
.check_name(move |name: &str| refusal(&taken, &named, name).map(|_| PresetError::NameTaken))
|
||||
.held_ok();
|
||||
let discovery = (background && mode == PrintMode::Print).then(|| discover(app));
|
||||
if discovery.is_some() {
|
||||
hosted.set_settings_valid(false);
|
||||
hosted.set_field("__discovery", true.into());
|
||||
}
|
||||
// The name row is the dialog's own.
|
||||
if mode == PrintMode::PresetEditor {
|
||||
hosted.set_json_field(&ctx, "name", json!(name))?;
|
||||
}
|
||||
let id = dialogs.with(|h| h.open(hosted));
|
||||
app.print_dialog.open =
|
||||
Some(Open { id, mode, document, preset, editing, art: None, preview: None, driver, papers: (printer, papers), papers_pending, media });
|
||||
app.print_dialog.open = Some(Open {
|
||||
id,
|
||||
mode,
|
||||
document,
|
||||
preset,
|
||||
editing,
|
||||
art: None,
|
||||
preview: None,
|
||||
driver,
|
||||
papers: (printer, papers),
|
||||
papers_pending,
|
||||
media,
|
||||
discovery,
|
||||
});
|
||||
Ok(Value::Null)
|
||||
}
|
||||
|
||||
@@ -394,12 +419,49 @@ fn insert_at(map: &mut Map<String, Value>, path: &[&str], v: Value) {
|
||||
/// and PDF File last; and whether there is a print service.
|
||||
fn destinations(app: &mut VectorcraftApp) -> (Vec<Printer>, bool) {
|
||||
let service = app.services.print.is_some();
|
||||
let mut list: Vec<Printer> = app.services.print.as_mut().map(|s| s.printers()).unwrap_or_default();
|
||||
let list: Vec<Printer> = app.services.print.as_mut().map(|s| s.printers()).unwrap_or_default();
|
||||
(listed(list, service), service)
|
||||
}
|
||||
|
||||
/// The Printer list of the system's printers `list`: the default printer by itself when a print `service` names none,
|
||||
/// and PDF File last.
|
||||
fn listed(mut list: Vec<Printer>, service: bool) -> Vec<Printer> {
|
||||
if service && list.is_empty() {
|
||||
list.push(Printer::new("").label(tl!(DEFAULT_PRINTER)));
|
||||
}
|
||||
list.push(Printer::new(PDF_FILE).label(tl!(PDF_FILE)));
|
||||
(list, service)
|
||||
list
|
||||
}
|
||||
|
||||
/// The print service's background printer discovery, if it has one.
|
||||
fn shared_printers(app: &VectorcraftApp) -> Option<crate::print::SharedPrintersFn> {
|
||||
app.services.print.as_ref().and_then(|s| s.shared_printers())
|
||||
}
|
||||
|
||||
/// The Printer list for the dialog to take ([`HostedPrint::listen`]): found on a background job when the print service
|
||||
/// has a background discovery, otherwise listed here.
|
||||
fn discover(app: &mut VectorcraftApp) -> mpsc::Receiver<Vec<Printer>> {
|
||||
let (tx, rx) = mpsc::channel();
|
||||
match shared_printers(app) {
|
||||
Some(find) => {
|
||||
let ctx = app.ui_ctx.clone();
|
||||
app.jobs().spawn(
|
||||
"printer-discovery",
|
||||
Box::new(move || {
|
||||
// The dialog may have closed and dropped the receiver; nothing waits for the list then.
|
||||
let _ = tx.send(listed(find(), true));
|
||||
if let Some(ctx) = ctx {
|
||||
ctx.request_repaint();
|
||||
}
|
||||
}),
|
||||
);
|
||||
}
|
||||
None => {
|
||||
// The receiver is held by the dialog, so the send cannot fail.
|
||||
let _ = tx.send(destinations(app).0);
|
||||
}
|
||||
}
|
||||
rx
|
||||
}
|
||||
|
||||
/// Whether the print service can open a printer's settings (`print.printerSetup`).
|
||||
@@ -456,9 +518,25 @@ fn on<R>(dialogs: &WindowDialogs, f: impl FnOnce(&mut HostedPrint) -> R) -> Opti
|
||||
dialogs.with(|h| h.get_mut::<HostedPrint>().map(f))
|
||||
}
|
||||
|
||||
pub(crate) fn prepare_confirm(app: &VectorcraftApp, host: &mut craft::ui::dialog::DialogHost, id: DialogId) {
|
||||
if let Some(open) = &app.print_dialog.open
|
||||
&& open.id == id
|
||||
&& let Some(p) = host.get_mut::<HostedPrint>()
|
||||
{
|
||||
discovery_valid(p, open.mode, open.discovery.is_some());
|
||||
}
|
||||
}
|
||||
|
||||
/// Enables Print unless the dialog prints to a printer while the printer list is still being looked up.
|
||||
fn discovery_valid(p: &mut HostedPrint, mode: PrintMode, pending: bool) {
|
||||
let physical = matches!(&p.state().settings.destination, Destination::Printer(name) if name != PDF_FILE);
|
||||
p.set_settings_valid(mode != PrintMode::Print || !(pending || p.state().discovering()) || !physical);
|
||||
}
|
||||
|
||||
/// One pass of the pump over the open dialog; false once it has closed.
|
||||
fn serve(app: &mut VectorcraftApp, ctx: &egui::Context, dialogs: &WindowDialogs, open: &mut Open) -> bool {
|
||||
let setup = has_setup(app);
|
||||
// Setup… looks the printers up again on some systems, so the row shows it once the discovery has ended.
|
||||
let setup = has_setup(app) && open.discovery.is_none();
|
||||
let Some(mut d) = on(dialogs, |p| {
|
||||
// The printer row shows Setup… for the printer chosen, and none for PDF File.
|
||||
let driver = driver(setup, &p.state().settings.destination);
|
||||
@@ -576,6 +654,12 @@ fn serve(app: &mut VectorcraftApp, ctx: &egui::Context, dialogs: &WindowDialogs,
|
||||
.collect();
|
||||
on(dialogs, |p| p.set_presets(rows, held, vec![DEFAULT_PRESET.to_string()]));
|
||||
}
|
||||
if d.refresh {
|
||||
if open.discovery.is_none() {
|
||||
open.discovery = Some(discover(app));
|
||||
}
|
||||
announce(ctx, tl!("Finding printers. PDF File and Done are available."), Politeness::Polite);
|
||||
}
|
||||
if open.document.is_some_and(|document| app.session.active().is_none_or(|st| st.uid != document)) {
|
||||
let message = tl!("Return to the original drawing to print it");
|
||||
on(dialogs, |p| {
|
||||
@@ -592,12 +676,31 @@ fn serve(app: &mut VectorcraftApp, ctx: &egui::Context, dialogs: &WindowDialogs,
|
||||
open.driver = d.driver;
|
||||
ctx.request_repaint();
|
||||
}
|
||||
if d.refresh {
|
||||
let (list, _) = destinations(app);
|
||||
let (tx, rx) = mpsc::channel();
|
||||
// The receiver is held by the dialog below, so the send cannot fail.
|
||||
let _ = tx.send(list);
|
||||
on(dialogs, |p| p.listen(rx));
|
||||
let discovery_pending = open.discovery.is_some();
|
||||
if let Some(rx) = &open.discovery {
|
||||
let found = match rx.try_recv() {
|
||||
Ok(list) => Some(Some(list)),
|
||||
Err(mpsc::TryRecvError::Disconnected) => Some(None),
|
||||
Err(mpsc::TryRecvError::Empty) => None,
|
||||
};
|
||||
if let Some(list) = found {
|
||||
open.discovery = None;
|
||||
let (tx, rx) = mpsc::channel();
|
||||
// A discovery that stopped without a list leaves the default printer and PDF File.
|
||||
// The receiver is held by the dialog below, so the send cannot fail.
|
||||
let _ = tx.send(list.unwrap_or_else(|| listed(Vec::new(), true)));
|
||||
on(dialogs, |p| {
|
||||
p.listen(rx);
|
||||
p.state_mut().poll(ctx);
|
||||
let selected = match &p.state().settings.destination {
|
||||
Destination::Printer(name) if name.is_empty() => tl!(DEFAULT_PRINTER).to_string(),
|
||||
Destination::Printer(name) => name.clone(),
|
||||
_ => tl!(PDF_FILE).to_string(),
|
||||
};
|
||||
let message = crate::i18n::fmt(tl!("Printers are ready. Selected printer: {printer}."), &[("printer", &selected)]);
|
||||
announce(ctx, message, Politeness::Polite);
|
||||
});
|
||||
}
|
||||
}
|
||||
if let Some(printer) = d.setup
|
||||
&& let Err(e) = app.run("print.printerSetup", json!({ "printer": printer }))
|
||||
@@ -630,7 +733,10 @@ fn serve(app: &mut VectorcraftApp, ctx: &egui::Context, dialogs: &WindowDialogs,
|
||||
Err(_) => Some(tl!("Can't print these settings: see the Summary")),
|
||||
};
|
||||
on(dialogs, |p| {
|
||||
let pending = open.discovery.is_some() || p.state().discovering();
|
||||
p.set_sheet(sheet);
|
||||
discovery_valid(p, open.mode, pending);
|
||||
p.set_field("__discovery", pending.into());
|
||||
p.set_message(message.map(Into::into));
|
||||
});
|
||||
if changed {
|
||||
@@ -643,7 +749,15 @@ fn serve(app: &mut VectorcraftApp, ctx: &egui::Context, dialogs: &WindowDialogs,
|
||||
p.set_field("__inks", FieldValue::Json(inks));
|
||||
});
|
||||
}
|
||||
if let Some(answer) = d.ok {
|
||||
// Physical printing waits until the dialog has applied the discovered list.
|
||||
if open.mode == PrintMode::Print
|
||||
&& discovery_pending
|
||||
&& d.ok.as_ref().is_some_and(|answer| {
|
||||
matches!(answer.finish, PrintFinish::Print) && matches!(&answer.settings.destination, Destination::Printer(name) if name != PDF_FILE)
|
||||
})
|
||||
{
|
||||
on(dialogs, HostedPrint::release_ok);
|
||||
} else if let Some(answer) = d.ok {
|
||||
let result = accept(app, open, &answer, &d.name);
|
||||
on(dialogs, |p| p.answer_ok(result.map_err(Into::into)));
|
||||
}
|
||||
|
||||
@@ -66,6 +66,7 @@ use craft::ui::dialog::{
|
||||
use craft::ui::display::Text;
|
||||
use craft::ui::layout_components::Stack;
|
||||
use craft::ui::runtime::keys;
|
||||
use craft::ui::runtime::windows::WindowHost;
|
||||
use craft::ui::sections::{DialogRole, FooterButton};
|
||||
use craft::ui::text::TextField;
|
||||
use egui::Ui;
|
||||
@@ -73,7 +74,6 @@ use serde_json::{Value, json};
|
||||
use vectorcraft_engine::cmd::scripts::{RUN_EXTS, TOO_LARGE, runs};
|
||||
use vectorcraft_engine::file_access::ScopeHandle;
|
||||
use vectorcraft_engine::script::dialogs::{MAX_PROMPT_BYTES, cut_to, shown_text};
|
||||
use vectorcraft_engine::script::dom::preferences::WARNING_OFF_QUESTION;
|
||||
use vectorcraft_engine::script::files::{MAX_ENTRIES, PickAnswer, PickerKind, ScriptPicker};
|
||||
use vectorcraft_engine::script::printing::PreparedPrint;
|
||||
use vectorcraft_engine::script::{DialogAnswer, MAX_SOURCE_BYTES, ScriptDialog};
|
||||
@@ -184,6 +184,8 @@ pub(crate) struct ScriptAnswer {
|
||||
pub(crate) answer: &'static str,
|
||||
/// The text of a prompt.
|
||||
pub(crate) value: String,
|
||||
/// Automation gave the answer: `ui.dialog.confirm`, or a click in a pass automation drove.
|
||||
pub(crate) automated: bool,
|
||||
}
|
||||
|
||||
/// What a script's file dialog answers with.
|
||||
@@ -226,11 +228,15 @@ pub(crate) struct ScriptNotice {
|
||||
no_as_default: bool,
|
||||
value: String,
|
||||
answer: Option<&'static str>,
|
||||
/// The confirm is the app's own question before the external script warning turns off
|
||||
/// ([`vectorcraft_engine::Session::script_dialog_turns_warning_off`]), not a script's.
|
||||
warning_off: bool,
|
||||
}
|
||||
|
||||
impl ScriptNotice {
|
||||
fn new(d: &ScriptDialog) -> Self {
|
||||
fn new(d: &ScriptDialog, warning_off: bool) -> Self {
|
||||
Self {
|
||||
warning_off,
|
||||
kind: d.kind.id().to_string(),
|
||||
message: d.message.clone(),
|
||||
title: d.title.clone(),
|
||||
@@ -278,8 +284,8 @@ impl ScriptNotice {
|
||||
|
||||
/// The dialog's message: a script's own text as it is, and the question the app asks before a
|
||||
/// script turns off the external script warning in the current language.
|
||||
fn notice_message(message: &str) -> String {
|
||||
if message == WARNING_OFF_QUESTION { crate::i18n::msg(message) } else { message.to_string() }
|
||||
fn notice_message(message: &str, warning_off: bool) -> String {
|
||||
if warning_off { crate::i18n::msg(message) } else { message.to_string() }
|
||||
}
|
||||
|
||||
impl StackDialog for ScriptNotice {
|
||||
@@ -295,7 +301,7 @@ impl StackDialog for ScriptNotice {
|
||||
|
||||
fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option<DialogResult<ScriptAnswer>> {
|
||||
let (answers, buttons): (Vec<&'static str>, Vec<FooterButton>) = self.choices().into_iter().unzip();
|
||||
let message = shown_text(¬ice_message(&self.message), true);
|
||||
let message = shown_text(¬ice_message(&self.message, self.warning_off), true);
|
||||
let mut prompt = Prompt::new(self.heading(), message.clone()).answers(buttons);
|
||||
if self.error_icon {
|
||||
prompt = prompt.tone(Tone::Bad, tl!("The script reports an error."));
|
||||
@@ -316,12 +322,13 @@ impl StackDialog for ScriptNotice {
|
||||
self.value = cut_to(&self.value, MAX_PROMPT_BYTES).to_string();
|
||||
}
|
||||
let answer = *answers.get(picked?)?;
|
||||
Some(DialogResult::Ok(ScriptAnswer { kind: self.kind.clone(), answer, value: self.value.clone() }))
|
||||
let automated = WindowHost::of(ui.ctx()).injected_pass();
|
||||
Some(DialogResult::Ok(ScriptAnswer { kind: self.kind.clone(), answer, value: self.value.clone(), automated }))
|
||||
}
|
||||
|
||||
fn confirm(&mut self, _: &egui::Context) -> Option<ScriptAnswer> {
|
||||
let answer = self.answer.unwrap_or_else(|| self.default_answer());
|
||||
Some(ScriptAnswer { kind: self.kind.clone(), answer, value: self.value.clone() })
|
||||
Some(ScriptAnswer { kind: self.kind.clone(), answer, value: self.value.clone(), automated: true })
|
||||
}
|
||||
|
||||
fn json_fields(&self) -> Option<Value> {
|
||||
@@ -353,7 +360,7 @@ impl StackDialog for ScriptNotice {
|
||||
let Some(answer) = answers_for(&self.kind).split(", ").find(|answer| *answer == wanted) else {
|
||||
return Err(format!("`answer` for this {} dialog must be one of: {}", self.kind, answers_for(&self.kind)));
|
||||
};
|
||||
if answer == "yes" && self.message == WARNING_OFF_QUESTION {
|
||||
if answer == "yes" && self.warning_off {
|
||||
return Err(WARNING_BY_PERSON.into());
|
||||
}
|
||||
self.answer = Some(answer);
|
||||
@@ -735,7 +742,7 @@ pub(crate) fn open_growth(app: &VectorcraftApp) {
|
||||
|
||||
/// Shows the dialog the running script waits at.
|
||||
pub(crate) fn open_notice(app: &VectorcraftApp, d: &ScriptDialog) {
|
||||
open_over_window(app, ScriptNotice::new(d));
|
||||
open_over_window(app, ScriptNotice::new(d, app.session.script_dialog_turns_warning_off()));
|
||||
}
|
||||
|
||||
/// Shows the file dialog the running script waits at.
|
||||
@@ -890,13 +897,14 @@ pub(crate) fn settle_notice(app: &mut VectorcraftApp, result: DialogResult<Scrip
|
||||
"confirm" => "no",
|
||||
_ => "stop",
|
||||
};
|
||||
ScriptAnswer { kind, answer, value: String::new() }
|
||||
ScriptAnswer { kind, answer, value: String::new(), automated: false }
|
||||
}
|
||||
};
|
||||
// Only the person at the keyboard turns off the external script warning: Yes from a pass
|
||||
// automation drives is refused, the warning stays on, and the question opens again.
|
||||
let warning_off = app.session.script_dialog().is_some_and(|d| d.message == WARNING_OFF_QUESTION);
|
||||
if warning_off && answer.answer == "yes" && app.automation_is_acting() {
|
||||
// Only the person at the keyboard turns off the external script warning: Yes that automation
|
||||
// gave, or taken in a pass automation drives, is refused, the warning stays on, and the
|
||||
// question opens again.
|
||||
let warning_off = app.session.script_dialog_turns_warning_off();
|
||||
if warning_off && answer.answer == "yes" && (answer.automated || app.automation_is_acting()) {
|
||||
app.status(WARNING_BY_PERSON);
|
||||
if let Some(d) = app.session.script_dialog() {
|
||||
open_notice(app, &d);
|
||||
@@ -1168,3 +1176,29 @@ pub(crate) fn settle_print(app: &mut VectorcraftApp, result: DialogResult<PrintA
|
||||
pub(crate) const PRINT_BY_PERSON: &str = "Only the person at the keyboard can print a script's print jobs";
|
||||
/// The status after Cancel.
|
||||
pub(crate) const PRINTS_DROPPED: &str = "The script's print jobs were not sent";
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use vectorcraft_engine::script::DialogKind;
|
||||
use vectorcraft_engine::script::dom::preferences::WARNING_OFF_QUESTION;
|
||||
|
||||
#[test]
|
||||
fn automation_answers_yes_by_the_confirm_origin_not_its_text() {
|
||||
let d = ScriptDialog {
|
||||
kind: DialogKind::Confirm,
|
||||
message: WARNING_OFF_QUESTION.into(),
|
||||
title: None,
|
||||
error_icon: false,
|
||||
no_as_default: true,
|
||||
preset: String::new(),
|
||||
};
|
||||
let ctx = egui::Context::default();
|
||||
// A script's own confirm with the same text takes Yes.
|
||||
let mut script = ScriptNotice::new(&d, false);
|
||||
assert!(script.set_json_field(&ctx, "answer", json!("yes")).is_ok());
|
||||
// The app's question before the warning turns off does not.
|
||||
let mut app = ScriptNotice::new(&d, true);
|
||||
assert_eq!(app.set_json_field(&ctx, "answer", json!("yes")), Err(WARNING_BY_PERSON.to_string()));
|
||||
}
|
||||
}
|
||||
@@ -1117,6 +1117,232 @@ pub(super) fn field_names(out: &egui::FullOutput) -> Vec<String> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A print service with a background printer discovery, which counts the lists made on the UI thread.
|
||||
struct SlowDiscovery {
|
||||
/// How many times the dialog listed the printers on the UI thread.
|
||||
listed_here: Rc<Cell<usize>>,
|
||||
jobs: Jobs,
|
||||
printers: Vec<Printer>,
|
||||
}
|
||||
|
||||
impl PrintService for SlowDiscovery {
|
||||
fn printers(&mut self) -> Vec<Printer> {
|
||||
self.listed_here.set(self.listed_here.get() + 1);
|
||||
MockPrint(Jobs::default()).printers()
|
||||
}
|
||||
|
||||
fn print(&mut self, job: &PrintJob) -> Result<String, String> {
|
||||
MockPrint(self.jobs.clone()).print(job)
|
||||
}
|
||||
|
||||
fn shared_printers(&self) -> Option<crate::print::SharedPrintersFn> {
|
||||
let printers = self.printers.clone();
|
||||
Some(std::sync::Arc::new(move || printers.clone()))
|
||||
}
|
||||
}
|
||||
|
||||
/// The message the Print dialog shows while the printer discovery runs.
|
||||
const PENDING_MESSAGE: &str = "Finding printers. PDF File and Done are available.";
|
||||
|
||||
/// Checks the dialog's next frame: whether it shows the discovery message, and whether Print is enabled. Done always
|
||||
/// is.
|
||||
fn discovery_controls(app: &mut VectorcraftApp, pending: bool, enabled: bool) {
|
||||
use egui::accesskit::Role;
|
||||
let ctx = ctx(app);
|
||||
let out = crate::testing::app_frame(app, &ctx, Default::default());
|
||||
let nodes = out.platform_output.accesskit_update.expect("an accessibility tree").nodes;
|
||||
let button = |name| nodes.iter().map(|(_, node)| node).find(|node| node.role() == Role::Button && node.label() == Some(name)).unwrap();
|
||||
assert_eq!(!button("Print").is_disabled(), enabled, "Print availability follows discovery and destination");
|
||||
assert!(!button("Done").is_disabled(), "Done stays available");
|
||||
assert_eq!(nodes.iter().any(|(_, node)| node.label() == Some(PENDING_MESSAGE) || node.value() == Some(PENDING_MESSAGE)), pending);
|
||||
}
|
||||
|
||||
/// An app with a drawing whose print service finds `printers` on a background job that waits until the test runs it,
|
||||
/// as a slow print server would; with the count of lists made on the UI thread, the jobs printed, and the jobs.
|
||||
fn discovery_app(printers: Vec<Printer>) -> (VectorcraftApp, Rc<Cell<usize>>, Jobs, std::sync::Arc<craft::host::ManualJobs>) {
|
||||
let listed_here = Rc::new(Cell::new(0));
|
||||
let printed = Jobs::default();
|
||||
let service = SlowDiscovery { listed_here: listed_here.clone(), jobs: printed.clone(), printers };
|
||||
let services = Services { print: Some(Box::new(service)), ..Default::default() };
|
||||
let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), services));
|
||||
let jobs = std::sync::Arc::new(craft::host::ManualJobs::new());
|
||||
app.host = std::sync::Arc::new(craft::host::Host::builder(app.host.app().clone()).i18n(crate::i18n::shared()).jobs(jobs.clone()).build());
|
||||
app.run("file.new", json!({"width": 120, "height": 90})).unwrap();
|
||||
(app, listed_here, printed, jobs)
|
||||
}
|
||||
|
||||
/// The dialog opens and works while the printer discovery waits on a background job, and shows the system's printers
|
||||
/// once the job has run.
|
||||
#[test]
|
||||
fn printer_discovery_runs_off_the_ui_thread() {
|
||||
use egui::accesskit::Role;
|
||||
let (mut app, listed_here, printed, jobs) = discovery_app(MockPrint(Jobs::default()).printers());
|
||||
let pending_message = PENDING_MESSAGE;
|
||||
let controls = discovery_controls;
|
||||
app.run("file.print", json!({})).unwrap();
|
||||
app.run("file.new", json!({"width": 180, "height": 100})).unwrap();
|
||||
let ctx = ctx(&app);
|
||||
let out = crate::testing::app_frame(&mut app, &ctx, Default::default());
|
||||
let nodes = out.platform_output.accesskit_update.unwrap().nodes;
|
||||
assert!(
|
||||
nodes.iter().any(|(_, node)| node.role() == Role::Button && node.label() == Some("Print") && node.is_disabled()),
|
||||
"physical Print is disabled in the first frame"
|
||||
);
|
||||
assert!(
|
||||
nodes.iter().any(|(_, node)| {
|
||||
node.role() == Role::Status
|
||||
&& node.live() == Some(egui::accesskit::Live::Polite)
|
||||
&& node.label().is_some_and(|text| text.contains(pending_message))
|
||||
}),
|
||||
"printer discovery is announced before Print is pressed"
|
||||
);
|
||||
assert_eq!(listed_here.get(), 0, "the printers are not listed on the UI thread");
|
||||
assert_eq!(jobs.waiting(), 1, "discovery starts even after switching drawings before the first pump");
|
||||
app.run("document.activate", json!({"index": 0})).unwrap();
|
||||
pump(&mut app);
|
||||
controls(&mut app, true, false);
|
||||
assert_eq!(jobs.waiting(), 1, "the discovery waits on a background job");
|
||||
assert_ne!(fields(&app)["printer"], "Proofer", "the list has not arrived");
|
||||
set(&mut app, "printer", json!("PDF File"));
|
||||
pump(&mut app);
|
||||
controls(&mut app, true, true);
|
||||
let out = crate::testing::app_frame(&mut app, &ctx, Default::default());
|
||||
let nodes = out.platform_output.accesskit_update.unwrap().nodes;
|
||||
assert!(nodes.iter().any(|(_, node)| node.label() == Some("Print preview image")), "PDF preview stays available during discovery");
|
||||
set(&mut app, "sheet", json!(0));
|
||||
pump(&mut app);
|
||||
assert_eq!(fields(&app)["sheet"], 0, "PDF preview accepts page selection during discovery");
|
||||
set(&mut app, "printer", json!(""));
|
||||
pump(&mut app);
|
||||
set(&mut app, "section", json!("Graphics"));
|
||||
pump(&mut app);
|
||||
assert_eq!(jobs.waiting(), 1, "one discovery at a time");
|
||||
confirm(&mut app);
|
||||
assert!(is_open(&app), "physical printing waits for discovery");
|
||||
assert!(printed.borrow().is_empty());
|
||||
let (id, _) = top(&app).unwrap();
|
||||
app.dialogs().unwrap().with(|host| {
|
||||
host.get_mut::<craft::print::ui::HostedPrint>().unwrap().set_settings_valid(true);
|
||||
let _ = host.confirm_by_id(&ctx, id);
|
||||
assert_eq!(host.held_state(id), Some(craft::ui::dialog::HeldOk::Waiting));
|
||||
});
|
||||
assert_eq!(jobs.run_all(), 1);
|
||||
// The frame's pump takes the list and announces it.
|
||||
let out = crate::testing::app_frame(&mut app, &ctx, Default::default());
|
||||
assert_eq!(app.dialogs().unwrap().with(|host| host.held_state(id)), None, "the pump discards the held physical answer");
|
||||
assert!(printed.borrow().is_empty(), "the captured placeholder must not submit to the default printer");
|
||||
let nodes = out.platform_output.accesskit_update.unwrap().nodes;
|
||||
assert!(
|
||||
nodes.iter().any(|(_, node)| {
|
||||
node.role() == Role::Status
|
||||
&& node.live() == Some(egui::accesskit::Live::Polite)
|
||||
&& node.label().is_some_and(|text| text.contains("Printers are ready. Selected printer: Proofer."))
|
||||
}),
|
||||
"the applied printer list and selected queue are announced"
|
||||
);
|
||||
pump(&mut app);
|
||||
assert!(is_open(&app), "the held Print answer waits for the dialog to apply the list");
|
||||
assert!(printed.borrow().is_empty(), "the captured placeholder must not submit to the default printer");
|
||||
assert_eq!(fields(&app)["printer"], "Proofer", "the system's default printer, once the list arrives");
|
||||
assert_eq!(listed_here.get(), 0);
|
||||
controls(&mut app, false, true);
|
||||
confirm(&mut app);
|
||||
assert!(!is_open(&app));
|
||||
assert_eq!(printed.borrow().len(), 1);
|
||||
assert_eq!(printed.borrow()[0].0.as_deref(), Some("Proofer"));
|
||||
|
||||
let picker = crate::tests_picks::scripted(&mut app);
|
||||
let written: Written = Rc::default();
|
||||
let w = written.clone();
|
||||
app.services.write = Some(Box::new(move |path: &str, bytes: &[u8]| {
|
||||
w.borrow_mut().push((path.to_string(), bytes.to_vec()));
|
||||
Ok(())
|
||||
}));
|
||||
app.run("file.print", json!({})).unwrap();
|
||||
call(&mut app, "ui.dialog.set", json!({"dialog": "top", "field": "printer", "value": "PDF File", "action": "confirm"}));
|
||||
picker.answer_saved("/tmp/discovery-combined.pdf", None);
|
||||
crate::tests_picks::poll(&mut app, &ctx);
|
||||
assert_eq!(written.borrow().len(), 1, "PDF selection and confirmation work in one call before a frame");
|
||||
assert_eq!(printed.borrow().len(), 1, "PDF confirmation does not submit a physical job");
|
||||
assert_eq!(jobs.waiting(), 1, "PDF confirmation does not wait for discovery");
|
||||
assert_eq!(jobs.run_all(), 1);
|
||||
assert_eq!(listed_here.get(), 0);
|
||||
}
|
||||
|
||||
/// While the printer discovery runs, Done keeps the settings and PDF File saves, and a held Print to a printer waits.
|
||||
#[test]
|
||||
fn done_and_pdf_file_work_while_printers_are_found() {
|
||||
let (mut app, listed_here, printed, jobs) = discovery_app(MockPrint(Jobs::default()).printers());
|
||||
let controls = discovery_controls;
|
||||
let ctx = ctx(&app);
|
||||
app.run("file.print", json!({})).unwrap();
|
||||
pump(&mut app);
|
||||
assert_eq!(jobs.waiting(), 1);
|
||||
let (id, _) = top(&app).unwrap();
|
||||
let _ = app.dialogs().unwrap().with(|host| host.confirm_by_id(&ctx, id));
|
||||
set(&mut app, "printer", json!("PDF File"));
|
||||
super::print::pump(&mut app, &ctx);
|
||||
pump(&mut app);
|
||||
controls(&mut app, true, true);
|
||||
assert_eq!(printed.borrow().len(), 0, "the held physical destination is checked even after selecting PDF File");
|
||||
set(&mut app, "printer", json!(""));
|
||||
set(&mut app, "copies", json!(2));
|
||||
set(&mut app, "choice", json!("done"));
|
||||
confirm(&mut app);
|
||||
assert!(!is_open(&app), "Done can save settings while discovery is pending");
|
||||
assert_eq!(app.session.active().unwrap().doc.print_setup.as_ref().unwrap()["copies"], 2);
|
||||
assert_eq!(printed.borrow().len(), 0, "Done does not submit a print job");
|
||||
assert_eq!(jobs.waiting(), 1, "Done did not wait for discovery");
|
||||
assert_eq!(jobs.run_all(), 1);
|
||||
|
||||
let picker = crate::tests_picks::scripted(&mut app);
|
||||
let written: Written = Rc::default();
|
||||
let w = written.clone();
|
||||
app.services.write = Some(Box::new(move |path: &str, bytes: &[u8]| {
|
||||
w.borrow_mut().push((path.to_string(), bytes.to_vec()));
|
||||
Ok(())
|
||||
}));
|
||||
app.run("file.print", json!({})).unwrap();
|
||||
pump(&mut app);
|
||||
set(&mut app, "printer", json!("PDF File"));
|
||||
pump(&mut app);
|
||||
controls(&mut app, true, true);
|
||||
confirm(&mut app);
|
||||
picker.answer_saved("/tmp/discovery.pdf", None);
|
||||
crate::tests_picks::poll(&mut app, &ctx);
|
||||
assert_eq!(written.borrow().len(), 1, "PDF File saves while discovery is pending");
|
||||
assert_eq!(pages(&written.borrow()[0].1), 2, "PDF File keeps the copies saved by Done");
|
||||
assert_eq!(printed.borrow().len(), 0);
|
||||
assert_eq!(jobs.waiting(), 1, "PDF File does not wait for discovery");
|
||||
assert_eq!(jobs.run_all(), 1);
|
||||
assert_eq!(listed_here.get(), 0);
|
||||
}
|
||||
|
||||
/// A discovery that finds no printers leaves Default Printer chosen, and Print goes to it once the list is applied.
|
||||
#[test]
|
||||
fn an_empty_discovery_keeps_the_default_printer() {
|
||||
let (mut app, listed_here, printed, jobs) = discovery_app(vec![]);
|
||||
let controls = discovery_controls;
|
||||
app.run("file.print", json!({})).unwrap();
|
||||
pump(&mut app);
|
||||
controls(&mut app, true, false);
|
||||
confirm(&mut app);
|
||||
assert!(is_open(&app));
|
||||
assert_eq!(fields(&app)["printer"], "");
|
||||
assert_eq!(jobs.run_all(), 1);
|
||||
pump(&mut app);
|
||||
pump(&mut app);
|
||||
controls(&mut app, false, true);
|
||||
assert_eq!(fields(&app)["printer"], "", "an empty result keeps Default Printer selected");
|
||||
let (id, _) = top(&app).unwrap();
|
||||
assert_eq!(app.dialogs().unwrap().with(|host| host.held_state(id)), None, "a blocked Print leaves no stale refusal");
|
||||
confirm(&mut app);
|
||||
assert!(!is_open(&app));
|
||||
assert_eq!(printed.borrow().len(), 1);
|
||||
assert_eq!(printed.borrow()[0].0, None);
|
||||
assert_eq!(listed_here.get(), 0);
|
||||
}
|
||||
|
||||
/// Every number and length field of the dialog's sections has a name that tells it from the others in its row.
|
||||
#[test]
|
||||
fn every_number_and_length_field_is_named() {
|
||||
|
||||
@@ -1992,7 +1992,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"file.print",
|
||||
"Print…",
|
||||
"Cmd+P",
|
||||
"{} open the Print dialog (dialog `print`: the print.setup settings, preset (setting it loads that print preset; Save Preset… saves them as one), printer, toFile; Print keeps the settings with the document and prints, Done (discard: true) only keeps them); with params {preset? (a print preset's name: its settings instead of the document's), settings? (over the document's or the preset's), printer? (print.printers name; \"\" the default), toFile?, path?, format?: pdf|postscript, level?, flattenerPreset?, maxPages? (as engine file.print)} print without it: the print-ready PDF (engine file.print) goes to the printer → {pages, printer, printed: true, warnings}; with toFile, a path or no printing here (no print service) it is saved as a PDF at path (else a picked file, the web downloads it) → {path, pages, printed: false, warnings}; a PostScript file (format postscript, or a .ps path) is always saved that way; a job of more than maxPages pages is neither printed nor saved → {pages, format}",
|
||||
"{} open the Print dialog (dialog `print`: the print.setup settings, preset (setting it loads that print preset; Save Preset… saves them as one), printer, toFile; on desktop, installed printers appear once the background lookup has returned and the dialog has applied the list; ui.dialog.set accepts a named printer once it appears in the list; PDF File is available at once; Print keeps the settings with the document and prints, Done (discard: true) only keeps them); with params {preset? (a print preset's name: its settings instead of the document's), settings? (over the document's or the preset's), printer? (print.printers name; \"\" the default), toFile?, path?, format?: pdf|postscript, level?, flattenerPreset?, maxPages? (as engine file.print)} print without it: the print-ready PDF (engine file.print) goes to the printer → {pages, printer, printed: true, warnings}; with toFile, a path or no printing here (no print service) it is saved as a PDF at path (else a picked file, the web downloads it) → {path, pages, printed: false, warnings}; a PostScript file (format postscript, or a .ps path) is always saved that way; a job of more than maxPages pages is neither printed nor saved → {pages, format}",
|
||||
),
|
||||
(
|
||||
"print.printers",
|
||||
|
||||
@@ -33,6 +33,9 @@ pub struct PrintJob<'a> {
|
||||
/// Submission callable from the desktop background worker.
|
||||
pub type SharedPrintFn = std::sync::Arc<dyn Fn(&PrintJob<'_>) -> Result<String, String> + Send + Sync>;
|
||||
|
||||
/// Printer discovery callable from a background job.
|
||||
pub type SharedPrintersFn = std::sync::Arc<dyn Fn() -> Vec<Printer> + Send + Sync>;
|
||||
|
||||
/// The platform's printing ([`crate::Services::print`]).
|
||||
pub trait PrintService {
|
||||
/// The printers the system knows (none: only the default one, or the browser's dialog).
|
||||
@@ -44,6 +47,11 @@ pub trait PrintService {
|
||||
fn shared_print(&self) -> Option<SharedPrintFn> {
|
||||
None
|
||||
}
|
||||
/// The printer discovery the Print dialog runs on a background job. Without one, the dialog lists
|
||||
/// [`PrintService::printers`] on the UI thread.
|
||||
fn shared_printers(&self) -> Option<SharedPrintersFn> {
|
||||
None
|
||||
}
|
||||
/// Whether the system turns a landscape page to fit the paper. macOS's print queues put
|
||||
/// each page on the paper as it is, so their jobs are written upright (`file.print`'s
|
||||
/// `forPrinter`); Windows and the browser's print dialog turn them themselves.
|
||||
|
||||
@@ -63,13 +63,23 @@ pub fn poll(app: &mut VectorcraftApp) {
|
||||
match result {
|
||||
// The commands it ran are journaled now: a recording they no longer fit in names its limit.
|
||||
Ok(report) => {
|
||||
if !crate::panels::actions::after_journaled_edit(app) {
|
||||
let limited = crate::panels::actions::after_journaled_edit(app);
|
||||
if !limited {
|
||||
app.status(format!("Ran {name}"));
|
||||
}
|
||||
// What the script's Copy or Cut left on the clipboard is offered to other apps, as
|
||||
// Edit › Copy does.
|
||||
if report["copied"] == true {
|
||||
let limit = limited.then(|| app.ui.status.clone());
|
||||
app.publish_clipboard(false);
|
||||
// The limit's message is set again, so the notes of the Copy's formats do not
|
||||
// replace it. A write failure reported at once stays on the status bar.
|
||||
if let Some(limit) = limit
|
||||
&& app.ui.status == limit
|
||||
{
|
||||
app.status(limit);
|
||||
app.ui.status_notes = None;
|
||||
}
|
||||
}
|
||||
// The jobs it prepared for a printer wait for the person's answer.
|
||||
script_run::ask_print(app);
|
||||
|
||||
@@ -339,13 +339,23 @@ fn only_the_person_turns_off_the_external_script_warning() {
|
||||
|
||||
script_run::forget::<ScriptNotice>(&app);
|
||||
app.ui.answering_control = true;
|
||||
let yes = script_run::ScriptAnswer { kind: "confirm".into(), answer: "yes", value: String::new() };
|
||||
let yes = script_run::ScriptAnswer { kind: "confirm".into(), answer: "yes", value: String::new(), automated: false };
|
||||
script_run::settle_notice(&mut app, craft::ui::dialog::DialogResult::Ok(yes));
|
||||
app.ui.answering_control = false;
|
||||
assert_eq!(app.ui.status, script_run::WARNING_BY_PERSON);
|
||||
assert!(is_open::<ScriptNotice>(&app), "the question opens again");
|
||||
assert!(app.session.script_dialog().is_some(), "the run still waits");
|
||||
|
||||
// Yes that automation gave is refused in a later frame that automation does not drive.
|
||||
script_run::forget::<ScriptNotice>(&app);
|
||||
app.ui.status = String::new();
|
||||
let yes = script_run::ScriptAnswer { kind: "confirm".into(), answer: "yes", value: String::new(), automated: true };
|
||||
script_run::settle_notice(&mut app, craft::ui::dialog::DialogResult::Ok(yes));
|
||||
assert_eq!(app.ui.status, script_run::WARNING_BY_PERSON);
|
||||
assert!(is_open::<ScriptNotice>(&app), "the question opens again");
|
||||
assert!(app.session.script_dialog().is_some(), "the run still waits");
|
||||
assert!(app.session.prefs.show_external_script_warning, "the warning stays on");
|
||||
|
||||
set(&app, NOTICE_KIND, "answer", json!("no")).unwrap();
|
||||
assert!(confirm(&mut app, NOTICE_KIND), "No is taken from automation");
|
||||
assert!(!until_dialog(&mut app));
|
||||
|
||||
@@ -628,6 +628,33 @@ fn copy_notes_are_counted_and_kept_in_order() {
|
||||
assert_eq!((app.ui.status.as_str(), &app.ui.status_notes), ("Ready", &None));
|
||||
}
|
||||
|
||||
/// A script whose Copy leaves a note and whose commands take a recording past its limit keeps the
|
||||
/// limit on the status bar once the Copy's formats are written.
|
||||
#[test]
|
||||
fn a_copy_note_does_not_replace_a_scripts_recording_limit() {
|
||||
let (mut app, board) = app_with_worker();
|
||||
vectorcraft_testkit::fixtures::place_cut_png(&mut app.session, &cut_short_png(), json!({}));
|
||||
run(&mut app, crate::panels::actions::START_RECORDING, json!({}));
|
||||
for _ in 0..vectorcraft_engine::script::actions::MAX_ACTION_STEPS - 1 {
|
||||
app.session.journal.push(("object.group".to_string(), json!({})));
|
||||
}
|
||||
app.session.script_frames = true;
|
||||
let source = "vc.run('edit.copy', {}); vc.run('object.move', {dx: 1, dy: 0}); vc.run('object.move', {dx: 1, dy: 0});";
|
||||
run(&mut app, "script.run", json!({"source": source, "name": "t.js"}));
|
||||
for _ in 0..10_000 {
|
||||
if !app.session.script_running() {
|
||||
break;
|
||||
}
|
||||
crate::script_runs::poll(&mut app);
|
||||
}
|
||||
assert!(!app.session.script_running(), "the script ends");
|
||||
let limit = "the action already has 10,000 steps";
|
||||
assert_eq!(app.ui.status, limit, "the status bar names the limit as the run ends");
|
||||
background::wait_all(&mut app);
|
||||
assert_eq!(written(&board), [TEXT, SVG, PNG]);
|
||||
assert_eq!((app.ui.status.as_str(), &app.ui.status_notes), (limit, &None), "the Copy's note does not replace the limit");
|
||||
}
|
||||
|
||||
/// A message shown while a Copy's formats are made on the worker stays: the formats are written
|
||||
/// once they are ready, and their note does not replace the newer message.
|
||||
#[test]
|
||||
|
||||
+42
-11
@@ -3072,7 +3072,7 @@ through `$`:
|
||||
`add` throws a `RangeError`), and `addDocument(startupPreset, presetSettings?, showOptionsDialog?)`, which runs `file.new`
|
||||
with the New Document profile `startupPreset` names (`Print`, `Web`, `Mobile`, `Video`, another profile of
|
||||
`file.newPresets`, or `Basic CMYK` and `Basic RGB` for no profile), starting from the first preset
|
||||
`file.newPresets` lists for that profile, and the settings of a `new DocumentPreset()`
|
||||
`file.newPresets` lists for that profile (a saved preset of the same name is not used), and the settings of a `new DocumentPreset()`
|
||||
(https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/) in place of the preset's. A `DocumentPreset`
|
||||
starts with the defaults that page gives. Assigning one of its settings checks the value's kind: a value of the
|
||||
setting's enumeration, a finite number, a `title` string, `true` or `false` for `documentBleedLink`, or an array
|
||||
@@ -3129,10 +3129,10 @@ through `$`:
|
||||
or placed document already has is not applied, and its document stays in the back), `editable` (false for an
|
||||
object that is hidden or locked, in a hidden or locked layer or group, or on a locked artboard), `zOrderPosition`,
|
||||
`duplicate(relativeObject?, insertionLocation?)`,
|
||||
`move(relativeObject, insertionLocation?)`, `remove()` and `zOrder(method)`
|
||||
(https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/). `move` runs `node.move` unless the object is already in
|
||||
the place it names. `duplicate` runs `edit.duplicate`, and with a relative object it then runs `node.move` on the
|
||||
copy the same way; without one, the copy stays where `edit.duplicate` puts it. The relative object is a page item or a layer of the same
|
||||
`move(relativeObject, insertionLocation?)`, `remove()`, `zOrder(method)`, `translate`, `rotate`, `resize` and
|
||||
`transform` (https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/). `move` runs `node.move` unless the object is
|
||||
already in the place it names. `duplicate` runs `edit.duplicate`, and with a relative object it then runs `node.move`
|
||||
on the copy the same way; without one, the copy stays where `edit.duplicate` puts it. The relative object is a page item or a layer of the same
|
||||
document; `ElementPlacement.INSIDE` and `PLACEATBEGINNING` (the default) put the object on top of a layer's or a
|
||||
group's contents, `PLACEATEND` under them, `PLACEBEFORE` directly above the relative object and `PLACEAFTER`
|
||||
directly below it. A move that leaves the object where it is runs no command. The clipping path of a clip group or clipping layer stays at its bottom: `PLACEATEND` puts the
|
||||
@@ -3169,8 +3169,35 @@ through `$`:
|
||||
`Reordering a path inside a compound path is not available yet` and leaves the document unchanged. When a placed image is embedded, an
|
||||
object a script holds for it is stale, and the next read gives a new `RasterItem` object. The
|
||||
enumerations `ElementPlacement`, `ZOrderMethod`, `BlendModes`, `RulerUnits`, `DocumentColorSpace`, `CoordinateSystem`,
|
||||
`DocumentArtboardLayout`, `DocumentPresetType`, `DocumentPreviewMode`, `DocumentRasterResolution` and
|
||||
`Transformation`, `DocumentArtboardLayout`, `DocumentPresetType`, `DocumentPreviewMode`, `DocumentRasterResolution` and
|
||||
`DocumentTransparencyGrid` hold strings such as `"ZOrderMethod.BRINGTOFRONT"`.
|
||||
`translate(deltaX?, deltaY?, transformObjects?, transformFillPatterns?, transformFillGradients?,
|
||||
transformStrokePatterns?)` moves the object by the offsets in points, `rotate(angle, changePositions?,
|
||||
changeFillPatterns?, changeFillGradients?, changeStrokePattern?, rotateAbout?)` turns it by `angle` degrees,
|
||||
`resize(scaleX, scaleY, changePositions?, changeFillPatterns?, changeFillGradients?, changeStrokePattern?,
|
||||
changeLineWidths?, scaleAbout?)` scales it by the percentages, and `transform(transformationMatrix, changePositions?,
|
||||
changeFillPatterns?, changeFillGradients?, changeStrokePattern?, changeLineWidths?, transformAbout?)` applies a
|
||||
`Matrix` record (https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/). Each one runs `object.transform` on the
|
||||
object. VectorCraft's own rules for them: offsets, angles and matrices have Y up whatever `app.coordinateSystem` is,
|
||||
so `translate(0, 10)` moves the object up and a positive angle turns it counterclockwise. `rotate`, `resize` and
|
||||
`transform` act about the center of the geometric bounds unless a `Transformation` value names another point of
|
||||
them; `Transformation.DOCUMENTORIGIN` is the bottom-left corner of the first artboard. Positions and gradients
|
||||
default to `true` and patterns to the Transform Pattern Tiles preference. Fill and stroke patterns with different
|
||||
values, and gradients different from positions, counting the defaults of arguments left out, throw an error that
|
||||
says they are not available yet.
|
||||
`changeLineWidths` is 100 (the default; stroke weights stay) or the transformation's own scale in percent, the
|
||||
square root of the area it scales by (stroke weights and effects scale with it). `resize` on a path also takes any
|
||||
other percent from 0 to 100000, which sets the stroke weight to that percent of what it was (through `stroke.set`,
|
||||
at most 1000 points). On a member of a compound path or compound shape, the compound's stroke weight follows the
|
||||
percent through `stroke.set`; when the percent is the resize's own scale, the member's own strokes and effects also
|
||||
scale with it. `transform` with `changeLineWidths` at the matrix's own scale sets the compound's stroke weight the
|
||||
same way, which changes the stroke every member of the compound shows. Another value throws the same
|
||||
error. A locked object, one inside a locked layer or group, a
|
||||
group that holds one, a hidden object or one inside a hidden layer or group, and an object on a locked artboard
|
||||
throw `cannot transform locked objects`, `cannot transform hidden objects` or
|
||||
`cannot transform objects on a locked artboard`. A scale of 0, a
|
||||
matrix whose determinant is 0 and a transformation that would take the object past the canvas also throw an error.
|
||||
In each of these cases the document does not change. A call that changes nothing runs no command.
|
||||
`pageItems` lists the art topmost first, as the example on
|
||||
[CMYKColor](https://ai-scripting.docsforadobe.dev/jsobjref/CMYKColor/) reads the frontmost path as `pathItems[0]`,
|
||||
and a document's `selection` lists the selected objects in the same order, whatever order they were selected or
|
||||
@@ -3221,7 +3248,7 @@ through `$`:
|
||||
`..`, a network path, a NUL character or more than 4,096 bytes throws an error. `app.redraw()` returns `undefined`
|
||||
and does not change the documents or add an undo step. In the app, the documents are drawn as they were before the
|
||||
run until the run ends, with or without the call. Some members the Application,
|
||||
Document and PageItem pages list, such as `Document.layers`, `PageItem.isIsolated`, `PageItem.rotate` and
|
||||
Document and PageItem pages list, such as `Document.layers`, `PageItem.isIsolated`, `PageItem.bringInPerspective` and
|
||||
`app.beep`, throw an error that says they are not available yet when they are read or assigned.
|
||||
`hasOwnProperty` and `propertyIsEnumerable` are false for those members and true for every other member of an
|
||||
object's class, so `item.hasOwnProperty("opacity")` is true on a page item, and `for (k in item)` lists the
|
||||
@@ -3515,11 +3542,10 @@ through `$`:
|
||||
members `pathPoints`, `closed`, `evenodd`, `area` (negative for a path that runs counterclockwise), `length`,
|
||||
`guides`, `clipping`, `selectedPathPoints`, `setEntirePath(points)`, `filled`, `fillColor`, `fillOverprint`,
|
||||
`stroked`, `strokeColor`, `strokeOverprint`, `strokeWidth`, `strokeCap`, `strokeJoin`, `strokeMiterLimit` (1 to
|
||||
500), `strokeDashes`, `strokeDashOffset`, `translate(deltaX?, deltaY?, ...)`, `rotate(angle, ..., rotateAbout?)`
|
||||
(counterclockwise for a positive angle) and `resize(scaleX, scaleY, ..., changeLineWidths?, scaleAbout?)`. The
|
||||
500), `strokeDashes` and `strokeDashOffset`, and takes the page item transforms above. The
|
||||
geometry changes through `path.setAnchors`, the fill and stroke through `paint.setFill` and `paint.setStroke`, the
|
||||
stroke options through `stroke.set`, the fill rule through `path.setFillRule`, overprint through
|
||||
`object.setOverprint` and the transforms through `object.move`, `object.rotate` and `object.scale`. Changes to the
|
||||
`object.setOverprint`. Changes to the
|
||||
points of a path (`closed`, `setEntirePath`, `pathPoints` and each `PathPoint`) are written together with one
|
||||
`path.setAnchors` before the script uses any other member or command, edits the points of another path, or reads
|
||||
the points of another path in the same Objects on Path group, and when the script ends;
|
||||
@@ -10961,7 +10987,9 @@ and goes back to Document Setup, whose OK runs `document.setup`; its Cancel goes
|
||||
|
||||
## New Document
|
||||
|
||||
`file.new` takes everything New Document sets: `preset` (a name from `file.newPresets`), `name`, `width`/`height`
|
||||
`file.new` takes everything New Document sets: `preset` (a name from `file.newPresets`, a saved preset before a
|
||||
built-in one of the same name; with `presetCategory`, a category of `file.newPresets`, the preset of that name in
|
||||
that category), `name`, `width`/`height`
|
||||
(points, or lengths such as `"210 mm"`), `units`, `orientation`, `artboards` with `artboardLayout {layout, columns,
|
||||
rows, spacing, rightToLeft}` (`artboards`, `columns` and `rows` are whole numbers from 1 to 1000, and any other number is an error; `rows` gives a `gridByColumn` layout that many rows, at most one for each artboard, in place of `columns`, and is
|
||||
an error with another layout; a preset keeps the rows, and `file.newPresets` lists them as set even when there are
|
||||
@@ -13384,6 +13412,9 @@ prints at most that many pages, copies counted; with more, `file.print` composes
|
||||
its raster effects are rendered. In the app, `file.print` with no params opens the Print
|
||||
dialog, and with params it prints through the system (`printer`: a name from `print.printers`, default the system's
|
||||
default printer) or, with `toFile`, a `path` or no printing available, saves the PDF.
|
||||
In the desktop Print dialog, installed printers appear once the background lookup has returned and the dialog has
|
||||
applied the list. `ui.dialog.set` accepts a named `printer` once it appears in that list. PDF File is available at once.
|
||||
The dialog shows and announces printer discovery. Physical Print is disabled until the list is applied; PDF File and Done remain available.
|
||||
|
||||
```json
|
||||
{"name":"run_command","arguments":{"command":"print.setup","params":{"settings":{"media":"a4","scaling":"fit","marks":{"trim":true}}}}}
|
||||
|
||||
@@ -1114,10 +1114,11 @@ 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: a page item's `translate`, `rotate`, `resize` and `transform` move, turn, scale and transform the object by offsets, an angle, percentages or a `Matrix` record, about its center or a `Transformation` point, with positions, patterns, gradients and line widths following their arguments (https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/). Each call that moves or reshapes the object runs `object.transform` inside the run's transaction, a call that changes only a path's stroke weight runs `stroke.set`, and a call that changes nothing runs no command. `resize` and `transform` on a member of a compound path with `changeLineWidths` at their own scale set the compound's stroke weight; locked art, art on a locked artboard and bad arguments throw an error with nothing changed (`docs/mcp.md`). `crates/engine/src/tests/script_dom_transform.rs`.
|
||||
- Scripts: `app.preferences` reads, stores and removes values by key with the type they were set as, keeps them across runs and restarts, and turns the warning before a picked script on with the key `ShowExternalJSXWarning`, and off only after the person answers Yes to a confirm (https://ai-scripting.docsforadobe.dev/jsobjref/Preferences/; the confirm is VectorCraft's own rule); `app` makes, joins, inverts and compares `Matrix` records (https://ai-scripting.docsforadobe.dev/jsobjref/Matrix/), rounding each joined value once from its exact sum of products and deciding whether an inverted value overflows from its exact quotient, and runs Copy, Cut and Paste on the active document inside the run's transaction (https://ai-scripting.docsforadobe.dev/jsobjref/Application/). `crates/engine/src/tests/script_dom_prefs.rs`.
|
||||
- Scripts: `Document.pathItems` lists the paths and makes rectangles, rounded rectangles, ellipses, polygons, stars and empty paths with the defaults the help page https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/ gives; each path's points, closed state, fill rule, area, length, guide state, selected points, fill and stroke colors, stroke options and transforms read and change as https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/ and https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/ describe them, and `RGBColor`, `CMYKColor`, `GrayColor`, `LabColor` and `NoColor` make colors (`docs/mcp.md`). `pathItems["name"]` reads a path by name as `pageItems` does, and `removeAll()` deletes nothing and throws when any path is on a locked artboard. A path takes the page item transforms, and `resize` also sets its stroke weight to a `changeLineWidths` percent from 0 to 100000 (at most 1000 points; a member of a compound sets the compound's stroke); gradients move with positions, so a `changeFillGradients` different from `changePositions` throws an error, as do `changeFillPatterns` and `changeStrokePattern` given as different values (`docs/mcp.md` lists these limits). Gradient stops are not there yet. A `PathPoint` of a path in an Objects on Path group goes stale when an edit of another path in the group moves it. `crates/engine/src/tests/script_dom_paths.rs`.
|
||||
- Scripts: `Document.placedItems` and `Document.rasterItems` list a document's linked and embedded images; `placedItems.add()` with a `File` assigned to `file` places an image linked, and `PlacedItem.relink(file)` and `embed()` relink and embed it, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PlacedItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PlacedItem/, https://ai-scripting.docsforadobe.dev/jsobjref/RasterItems/ and https://ai-scripting.docsforadobe.dev/jsobjref/RasterItem/ describe them. A raster item's bits per channel, channels, color space and transparency come from its encoded pixels' header. Only files the script may read, of at most 256 MiB and holding an image, are placed or relinked. Rasterizing and capturing are not there yet. `crates/engine/src/tests/script_dom_images.rs`.
|
||||
- Scripts: `PlacedItem.trace()` and `RasterItem.trace()` make an Image Trace object and return it as a `PluginItem` whose `tracing` gives its path, anchor and color counts, the source image's resolution, `expandTracing()`, `releaseTracing()` and its `TracingOptions`; assigning an option or loading a preset traces it again, except that the view options (`viewRaster` and `viewVector`) only change the view, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PluginItem/, https://ai-scripting.docsforadobe.dev/jsobjref/TracingObject/ and https://ai-scripting.docsforadobe.dev/jsobjref/TracingOptions/ describe them. Option values are checked for type and range before any trace, a script cannot save a preset, and the options without a VectorCraft setting throw. The source image of a traced item is left out of `pageItems`, `placedItems` and `rasterItems`; a script reaches it through `PluginItem.tracing.sourceArt`. Renaming an ordinary group that holds an image first to `Image Trace`, or moving or duplicating an image to the bottom of an ordinary group with that name, throws an error. `crates/engine/src/tests/script_dom_tracing.rs`.
|
||||
- Scripts: `Document.pathItems` lists the paths and makes rectangles, rounded rectangles, ellipses, polygons, stars and empty paths with the defaults the help page https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/ gives; each path's points, closed state, fill rule, area, length, guide state, selected points, fill and stroke colors, stroke options and transforms read and change as https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/ and https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/ describe them, and `RGBColor`, `CMYKColor`, `GrayColor`, `LabColor` and `NoColor` make colors (`docs/mcp.md`). `pathItems["name"]` reads a path by name as `pageItems` does, and `removeAll()` deletes nothing and throws when any path is on a locked artboard. The transforms move gradients with the art: `changeFillGradients` false throws an error, as do `changeFillPatterns` and `changeStrokePattern` given as different values, and `transform` is not there yet (`docs/mcp.md` lists these limits). Gradient stops are not there yet. A `PathPoint` of a path in an Objects on Path group goes stale when an edit of another path in the group moves it. `crates/engine/src/tests/script_dom_paths.rs`.
|
||||
- Scripts: a document's `default*` members (https://ai-scripting.docsforadobe.dev/jsobjref/Document/) read and set the fill, stroke and stroke options of the next object drawn through `appearance.setNewArt`, leaving the selection and its art as they were, and `scaleFactor` reads 1 (`docs/mcp.md`). `crates/engine/src/tests/script_dom_defaults.rs`.
|
||||
- Scripts: `app.undo()` and `app.redo()` undo and redo the edits the run made, and each document open before and after the run that it changed gets one undo step. `crates/engine/src/tests/script_dom.rs`.
|
||||
- Scripts: `document.textFrames` makes point type, area type and type on a path, and each text frame gives its kind, its contents, its text as text ranges with their characters, words and paragraphs (which can add text), their character attributes (size, leading, tracking, baseline shift, scales, rotation, underline, strikethrough, font) and paragraph attributes (alignment, indents, space before and after), outlines and point and area conversion; `app.textFonts` lists the fonts, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItems/, https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/, https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/ and https://ai-scripting.docsforadobe.dev/jsobjref/TextFonts/ describe them (`docs/mcp.md`). Offsets count UTF-16 units, VectorCraft's own rule. Lines, tab stops and colors are not there yet. `crates/engine/src/tests/script_text.rs`.
|
||||
|
||||
Reference in new issue
Block a user