Merge main into feat/scripts-api-layer-path-items

This commit is contained in:
dotCooCoo committed 2026-12-02 18:24:31 -08:00
commit 4010eb5be2
36 files changed
+1998 -197

No files matched your search

+223 -11
View File
@@ -25,6 +25,9 @@ impl PrintService for SystemPrint {
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, &note))))
}
fn applies_paper(&self) -> bool {
!cfg!(windows)
}
fn turns_landscape(&self) -> bool {
// macOS's `lp` doesn't turn a landscape page to the paper: it cuts it off on upright
// paper. craft-print turns each sheet to its own orientation on Windows.
@@ -173,17 +176,135 @@ mod system {
if printer.contains(['/', '\\']) || printer.starts_with('.') {
return Vec::new();
}
const PPD_CAP: u64 = 16 << 20;
let mut bytes = Vec::new();
let read = std::fs::File::open(format!("/etc/cups/ppd/{printer}.ppd")).and_then(|f| f.take(PPD_CAP).read_to_end(&mut bytes));
if read.is_err() {
return Vec::new();
let named = cups_server();
// A local PPD describes a local queue. With a remote scheduler the job goes to that server's queue,
// so its sizes come from the server.
if scheduler_is_local(named.as_deref()) {
const PPD_CAP: u64 = 16 << 20;
let mut bytes = Vec::new();
let read = std::fs::File::open(format!("/etc/cups/ppd/{printer}.ppd")).and_then(|f| f.take(PPD_CAP).read_to_end(&mut bytes));
let papers = if read.is_ok() { vectorcraft_ui_egui::print::ppd_papers(&craft::print::ppd_text(&bytes)) } else { Vec::new() };
if !papers.is_empty() {
return papers;
}
}
vectorcraft_ui_egui::print::ppd_papers(&craft::print::ppd_text(&bytes))
// A driverless or remote queue has no PPD here: `lpoptions` asks the queue's server for its sizes.
let mut command = Command::new("lpoptions");
command.args(["-p", printer, "-l"]);
let papers = paper_output(&mut command)
.map(|out| vectorcraft_ui_egui::print::lpoptions_papers(&String::from_utf8_lossy(&out)))
.unwrap_or_default();
if !papers.is_empty() {
return papers;
}
// A queue whose server has no PPD either: its IPP `media-supported` attribute, from the scheduler CUPS uses.
let port = vectorcraft_ui_egui::print::ipp_port(std::env::var("IPP_PORT").ok().as_deref());
let server = ipp_server(named, |s| std::path::Path::new(s).exists());
let Some(uri) = vectorcraft_ui_egui::print::ipp_queue_uri(server.as_deref(), port, printer) else { return papers };
use std::io::Write as _;
use std::sync::atomic::{AtomicU64, Ordering};
static NEXT: AtomicU64 = AtomicU64::new(0);
let test_path =
std::env::temp_dir().join(format!("vectorcraft-printer-papers-{}-{}.test", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
let Ok(mut test) = std::fs::File::options().write(true).create_new(true).open(&test_path) else { return papers };
let written = test.write_all(
b"{\n\
VERSION 1.1\n\
OPERATION Get-Printer-Attributes\n\
GROUP operation-attributes-tag\n\
ATTR charset attributes-charset utf-8\n\
ATTR language attributes-natural-language en\n\
ATTR uri printer-uri $uri\n\
ATTR keyword requested-attributes media-supported\n\
STATUS successful-ok\n\
}\n",
);
drop(test);
if written.is_err() {
let _ = std::fs::remove_file(&test_path);
return papers;
}
let mut command = Command::new("ipptool");
command.args(["-T", "10", "-tv", &uri]).arg(&test_path);
let output = paper_output(&mut command);
let _ = std::fs::remove_file(&test_path);
output.map(|out| vectorcraft_ui_egui::print::ipp_papers(&String::from_utf8_lossy(&out))).unwrap_or_default()
}
}
/// CUPS's own domain sockets, where the local scheduler listens next to `localhost:631`.
#[cfg(not(windows))]
const CUPS_SOCKETS: [&str; 3] = ["/private/var/run/cupsd", "/run/cups/cups.sock", "/var/run/cups/cups.sock"];
/// The server for the IPP lookup, given the one `cups_server` names and whether a path exists. With no server
/// named, CUPS uses its domain socket when it exists (`None`: [`ipp_queue_uri`] asks `localhost` on the IPP default
/// port), and `localhost` on `IPP_PORT` otherwise. A named domain socket that is one of CUPS's own is the same local
/// scheduler; any other socket path stays as named, so the lookup is skipped rather than asking a scheduler the job
/// does not go to.
///
/// [`ipp_queue_uri`]: vectorcraft_ui_egui::print::ipp_queue_uri
#[cfg(not(windows))]
pub(super) fn ipp_server(named: Option<String>, exists: impl Fn(&str) -> bool) -> Option<String> {
match named {
Some(server) if CUPS_SOCKETS.contains(&server.trim()) => None,
Some(server) => Some(server),
None => (!CUPS_SOCKETS.iter().any(|s| exists(s))).then(|| "localhost".to_string()),
}
}
/// The scheduler CUPS clients use: `CUPS_SERVER`, else the `ServerName` of `~/.cups/client.conf` or
/// `/etc/cups/client.conf`; `None` for the local default. macOS does not read `ServerName`
/// (https://openprinting.github.io/cups/doc/man-client.conf.html), so there only `CUPS_SERVER` counts.
#[cfg(not(windows))]
fn cups_server() -> Option<String> {
if let Some(server) = std::env::var("CUPS_SERVER").ok().filter(|s| !s.trim().is_empty()) {
return Some(server.trim().to_string());
}
if cfg!(target_os = "macos") {
return None;
}
let home = std::env::var_os("HOME").map(|h| std::path::Path::new(&h).join(".cups/client.conf"));
home.into_iter().chain([std::path::PathBuf::from("/etc/cups/client.conf")]).find_map(|path| {
use std::io::Read as _;
let mut text = String::new();
std::fs::File::open(path).and_then(|f| f.take(1 << 16).read_to_string(&mut text)).ok()?;
client_conf_server_name(&text)
})
}
/// Whether a scheduler named by `cups_server` runs on this machine: none named, a domain socket path,
/// or `localhost`, `127.0.0.1` or `::1` with no port or port 631, each with an optional `/version=` suffix. A loopback
/// name on another port is a second scheduler, whose queues the local PPD folder does not describe.
#[cfg(not(windows))]
pub(super) fn scheduler_is_local(server: Option<&str>) -> bool {
let Some(server) = server.map(str::trim) else { return true };
if server.starts_with('/') {
return true;
}
// A network name may end in `/version=1.1`.
let server = server.split_once('/').map_or(server, |(server, _)| server);
let (host, port) = if let Some(rest) = server.strip_prefix('[') {
rest.split_once(']').map_or((rest, None), |(host, after)| (host, after.strip_prefix(':')))
} else if server.matches(':').count() == 1 {
server.split_once(':').map_or((server, None), |(host, port)| (host, Some(port)))
} else {
(server, None)
};
let loopback = host.eq_ignore_ascii_case("localhost") || host == "127.0.0.1" || host == "::1";
loopback && port.is_none_or(|port| port.trim() == "631")
}
/// The last `ServerName` in a `client.conf`. CUPS (`cupsFileGetConf`) looks only at the first `#` on a
/// line: unescaped, it starts a comment that runs to the end of the line; as `\#`, the backslash is
/// dropped and the rest of the line is kept as written.
#[cfg(not(windows))]
pub(super) fn client_conf_server_name(text: &str) -> Option<String> {
text.lines().rev().find_map(|line| {
let kept = match line.find('#') {
Some(at) if line[..at].ends_with('\\') => format!("{}{}", &line[..at - 1], &line[at..]),
Some(at) => line[..at].to_string(),
None => line.to_string(),
};
let (key, value) = kept.trim().split_once(char::is_whitespace)?;
(key.eq_ignore_ascii_case("ServerName") && !value.trim().is_empty()).then(|| value.trim().to_string())
})
}
/// Drain output while polling the child, and stop discovery after ten seconds.
#[cfg(windows)]
fn paper_output(command: &mut Command) -> Option<Vec<u8>> {
use std::io::Read as _;
use std::process::Stdio;
@@ -226,10 +347,14 @@ mod system {
if job.direct_pdf {
return super::direct_pdf::print(job);
}
// Copies, layout, marks and colour management are already in the PDF. Preserve its
// physical sheet size and the queue's duplex default without printing copies twice.
let settings = craft::print::Job { printer: job.printer.map(str::to_string), title: job.title.into(), ..Default::default() };
craft::print::submit(job.pdf, &settings).map_err(|e| e.to_string())
craft::print::submit(job.pdf, &settings(job)).map_err(|e| e.to_string())
}
/// The spooler's settings for `job`. Copies, layout, marks and colour management are already in the PDF. Preserve
/// its physical sheet size and the queue's duplex default without printing copies twice. The driver's paper
/// keyword goes to CUPS as `media`, so the queue feeds the paper the job was laid out for.
pub(crate) fn settings(job: &PrintJob) -> craft::print::Job {
let options = job.paper.map(|paper| ("media".to_string(), paper.to_string())).into_iter().collect();
craft::print::Job { printer: job.printer.map(str::to_string), title: job.title.into(), options, ..Default::default() }
}
#[cfg(windows)]
pub(crate) fn setup_command(printer: Option<&str>, default_printer: Option<&str>) -> Command {
@@ -476,3 +601,90 @@ mod turn_tests {
);
}
}
#[cfg(all(test, not(windows)))]
mod client_conf_tests {
use super::system::{client_conf_server_name, ipp_server, scheduler_is_local};
#[test]
fn the_ipp_lookup_asks_a_socket_scheduler_only_when_it_is_cups_own() {
let none = |_: &str| false;
let socket = |s: &str| s == "/run/cups/cups.sock";
assert_eq!(ipp_server(Some("/run/cups/cups.sock".into()), none), None, "CUPS's socket is asked as localhost:631");
assert_eq!(ipp_server(Some(" /var/run/cups/cups.sock ".into()), none), None);
assert_eq!(ipp_server(Some("/tmp/other.sock".into()), socket).as_deref(), Some("/tmp/other.sock"), "another socket is not asked");
assert_eq!(ipp_server(Some("localhost:8631".into()), socket).as_deref(), Some("localhost:8631"));
assert_eq!(ipp_server(None, socket), None);
assert_eq!(ipp_server(None, none).as_deref(), Some("localhost"));
}
#[test]
fn only_a_scheduler_on_this_machine_counts_as_local() {
for local in [
None,
Some("/run/cups/cups.sock"),
Some("localhost"),
Some("LocalHost:631"),
Some("localhost:631"),
Some("127.0.0.1:631"),
Some("::1"),
Some("[::1]:631"),
Some("[::1]"),
Some("localhost/version=1.1"),
Some("localhost:631/version=1.1"),
] {
assert!(scheduler_is_local(local), "{local:?}");
}
for remote in [
"print.example.com",
"print.example.com:631",
"192.0.2.7",
"[2001:db8::1]:631",
"2001:db8::1",
"localhost.example.com",
"print.example.com:631/version=1.1",
"localhost:8631",
"127.0.0.1:8631",
"[::1]:8631",
"localhost:8631/version=1.1",
] {
assert!(!scheduler_is_local(Some(remote)), "{remote}");
}
}
#[test]
fn server_name_drops_a_trailing_comment_and_keeps_an_escaped_hash() {
assert_eq!(client_conf_server_name("ServerName print.example.com\n").as_deref(), Some("print.example.com"));
assert_eq!(client_conf_server_name("ServerName print.example.com # office\n").as_deref(), Some("print.example.com"));
assert_eq!(client_conf_server_name("ServerName print.example.com#office\n").as_deref(), Some("print.example.com"));
assert_eq!(client_conf_server_name("ServerName /run/cups\\#1.sock\n").as_deref(), Some("/run/cups#1.sock"));
// After an escaped first `#`, a later `#` stays as written.
assert_eq!(client_conf_server_name("ServerName a\\#b#c\n").as_deref(), Some("a#b#c"));
// A later line that is only a comment, or a directive whose value is all comment, leaves the earlier one.
assert_eq!(client_conf_server_name("ServerName a.example\n# ServerName b.example\nServerName # none\n").as_deref(), Some("a.example"));
assert_eq!(client_conf_server_name("ServerName a.example\nServerName b.example\n").as_deref(), Some("b.example"));
}
}
#[cfg(test)]
mod job_settings_tests {
use super::system::settings;
use vectorcraft_ui_egui::print::PrintJob;
fn job(paper: Option<&str>) -> PrintJob<'_> {
PrintJob { printer: Some("Card"), title: "Badge", pdf: b"%PDF", paper, direct_pdf: false }
}
#[test]
fn the_chosen_paper_goes_to_cups_as_media() {
let args = craft::print::lp_args(&settings(&job(Some("CR80"))));
assert!(args.windows(2).any(|w| w == ["-o", "media=CR80"]), "{args:?}");
assert!(args.windows(2).any(|w| w == ["-d", "Card"]), "{args:?}");
}
#[test]
fn without_a_paper_the_queue_keeps_its_own() {
let args = craft::print::lp_args(&settings(&job(None)));
assert!(!args.iter().any(|a| a.starts_with("media=")), "{args:?}");
}
}
+17 -1
View File
@@ -234,7 +234,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Clear",
["Edit"],
Some("Delete"),
"{ids?, guides?: bool (with ids: also delete the selected ruler guides), keepJoined?: bool (without ids: the direct-selected anchors of a path with no selected segment are removed as path.removeAnchors removes them, without opening the path, and the next anchor along is selected (the one before at an open path's end); default: prefs deleteKeepsPathsJoined), keepEmpty?: bool (keep a compound path left with no members)} delete the objects `ids`, else the selection (fully selected objects and direct-selected anchors together, else ruler guides; a compound-path member selected on its own is deleted alone, and a compound left with no members goes too unless keepEmpty); without ids, refused while an object of a symbol instance's art is selected",
"{ids?, guides?: bool (with ids: also delete the selected ruler guides), keepJoined?: bool (without ids: the direct-selected anchors of a path with no selected segment are removed as path.removeAnchors removes them, without opening the path, and the next anchor along is selected (the one before at an open path's end); default: prefs deleteKeepsPathsJoined), keepEmpty?: bool (keep a compound path left with no members)} delete the objects `ids`, else the selection (fully selected objects and direct-selected anchors together, else ruler guides; a compound-path member selected on its own is deleted alone, and a compound left with no members goes too unless keepEmpty); a clipping group or layer left without art releases its mask in the same undo step; without ids, refused while an object of a symbol instance's art is selected",
has_selection_or_guides,
clear
),
@@ -1312,6 +1312,20 @@ fn cut_direct_selection(s: &mut Session, roots: &[NodeId]) -> Result<Value> {
ok()
}
pub(super) fn clipped_ancestors(d: &Document, ids: impl IntoIterator<Item = NodeId>) -> BTreeSet<NodeId> {
ids.into_iter().flat_map(|id| d.ancestry(id).unwrap_or_default()).filter(|id| d.node(*id).is_some_and(Node::clips)).collect()
}
pub(super) fn release_empty_clips(d: &mut Document, ids: BTreeSet<NodeId>) {
for id in ids {
if let Some(n) = d.node_mut(id)
&& n.children().is_some_and(|c| c.iter().all(|n| n.is_ruler_guide()))
{
n.set_clips(false);
}
}
}
fn clear(s: &mut Session, p: &Value) -> Result<Value> {
let guides = switch_or(p, "guides", false, "edit.clear")?;
let keep_empty = switch_or(p, "keepEmpty", false, "edit.clear")?;
@@ -1348,6 +1362,7 @@ fn clear(s: &mut Session, p: &Value) -> Result<Value> {
return ok();
}
s.edit("Clear", |d, sel| {
let clipped = clipped_ancestors(d, ids.iter().copied());
let parents: Vec<_> = if keep_empty {
Vec::new()
} else {
@@ -1363,6 +1378,7 @@ fn clear(s: &mut Session, p: &Value) -> Result<Value> {
let gone = sel.guides.clone();
d.retain_guides(sel, |g| !g.id.is_some_and(|id| gone.contains(&id)));
}
release_empty_clips(d, clipped);
if is_explicit {
sel.remove_all(ids.iter().copied());
sel.prune(d);
+6 -1
View File
@@ -129,7 +129,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Reorder",
[],
None,
"{id, parent?: id (null = top level), index} put a row at `index` (0 = bottom) of `parent` (layers only at the top level or in layers; a path also goes into a shown, unlocked compound path whose layer and groups are shown and unlocked and that is not on a locked artboard, and gives up its own paint (the compound path becomes pixel-aligned when the path or the compound path it leaves was), and an empty compound path takes the paint the first path that goes in was drawn with; a path that leaves a compound path for a layer or a group takes its paint and pixel alignment; an Intertwine group takes and gives up members as layer.move does), deselecting every selected object left hidden or locked (the key object too); a Live Paint group or its paths take a row as layer.move does",
"{id, parent?: id (null = top level), index} put a row at `index` (0 = bottom) of `parent` (layers only at the top level or in layers; a path other than a clip group's or clipping layer's clipping path also goes into a shown, unlocked compound path whose layer and groups are shown and unlocked and that is not on a locked artboard, and gives up its own paint (the compound path becomes pixel-aligned when the path or the compound path it leaves was), and an empty compound path takes the paint the first path that goes in was drawn with; a path that leaves a compound path for a layer or a group takes its paint and pixel alignment; an Intertwine group takes and gives up members as layer.move does), deselecting every selected object left hidden or locked (the key object too); a Live Paint group or its paths take a row as layer.move does",
has_doc,
move_node
),
@@ -1006,6 +1006,11 @@ fn move_node(s: &mut Session, p: &Value) -> Result<Value> {
if !matches!(n.kind, NodeKind::Path { guide: false, .. }) {
return Err(bad(C, "a compound path holds only paths"));
}
// A clip group's or clipping layer's clipping path stays where it is: without it, the
// next object up would become the clipping path.
if d.position(id).is_some_and(|(from, i, _)| i == 0 && from.and_then(|f| d.node(f)).is_some_and(Node::clips)) {
return Err(bad(C, "a clipping path does not go into a compound path; release the clipping mask first"));
}
if !d.is_editable(c.id) {
return Err(bad(C, "the compound path is hidden or locked"));
}
+4 -3
View File
@@ -110,17 +110,18 @@ pub(super) fn group(s: &mut Session, _: &Value) -> Result<Value> {
/// selection stays as it is.
pub(super) fn new_group(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "object.newGroup";
// Only an omitted key takes its default; `null` is refused like any other bad value.
let compound = match p.get("compound") {
None | Some(Value::Null) => false,
None => false,
Some(v) => v.as_bool().ok_or_else(|| bad(C, "compound must be true or false"))?,
};
let st = s.doc()?;
let parent = match p.get("parent") {
None | Some(Value::Null) => st.current_layer().or_else(|| st.doc.default_layer()).ok_or_else(|| bad(C, "the document has no layer"))?,
None => st.current_layer().or_else(|| st.doc.default_layer()).ok_or_else(|| bad(C, "the document has no layer"))?,
Some(v) => NodeId(v.as_u64().ok_or_else(|| bad(C, "parent must be a layer or group id"))?),
};
let index = match p.get("index") {
None | Some(Value::Null) => usize::MAX,
None => usize::MAX,
Some(v) => v.as_u64().and_then(|i| usize::try_from(i).ok()).ok_or_else(|| bad(C, "index must be a whole number"))?,
};
let d = &st.doc;
+1 -1
View File
@@ -142,7 +142,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Group",
[],
None,
"{parent?: layer or group id (default: the current layer), index?: n (0 = bottom, or directly above the clipping path in a clipping layer or group; default: on top), compound?: bool (default false; true: an empty compound path instead of a group)} → {id}: an empty group or compound path in a shown, unlocked layer or group; the selection stays as it is",
"{parent?: layer or group id (default: the current layer), index?: n (0 = bottom, or directly above the clipping path in a clipping layer or group; default: on top), compound?: bool (default false; true: an empty compound path instead of a group)} → {id}: an empty group or compound path in a shown, unlocked layer or group; an omitted key takes its default; null is refused for parent, index and compound; the selection stays as it is",
has_doc,
new_group
),
+2
View File
@@ -1950,6 +1950,7 @@ pub(crate) fn delete_anchors_joined(s: &mut Session, p: &Value, keep_joined: boo
.copied()
.filter(|id| !d.ancestry(*id).unwrap_or_default().iter().rev().skip(1).any(|ancestor| targets.contains(ancestor)))
.collect();
let clipped = super::edit::clipped_ancestors(d, whole_ids.iter().chain(sel.keys()).chain(segments.keys()).copied());
// The compound paths that hold a deleted object; one left with no members goes too, unless `keepEmpty`.
let compounds: BTreeSet<NodeId> = if keep_empty {
BTreeSet::new()
@@ -2031,6 +2032,7 @@ pub(crate) fn delete_anchors_joined(s: &mut Session, p: &Value, keep_joined: boo
d.remove(p)?;
}
}
super::edit::release_empty_clips(d, clipped);
selection.set(survivors);
for (id, next) in following {
if !next.is_empty() {
+11 -1
View File
@@ -253,7 +253,17 @@ fn do_script(h: &Host, a: &[Data]) -> std::result::Result<Data, HostError> {
h.charge_call(16 + s.id.len() as u64 + s.bytes)?;
// Saved steps run as they run in the Actions panel: keys their commands no longer read are
// passed over.
let start = Start { active: &h.active_artboards, picks: h.artboard_picks.as_ref(), batch: s.artboard };
// A document whose active artboard the script chose uses that choice, not the one the run
// started with.
let chosen = h.session.borrow().active().and_then(|st| {
h.dom.chosen_artboards.borrow().iter().find(|(uid, reverts)| *uid == st.uid && *reverts == st.reverts)?;
Some((st.uid, super::dom::active_artboard(st)))
});
let active = match &chosen {
Some(chosen) => std::slice::from_ref(chosen),
None => h.active_artboards.as_slice(),
};
let start = Start { active, picks: h.artboard_picks.as_ref(), batch: s.artboard };
let params = on_active_artboard(&h.session.borrow(), &start, &s.id, &s.params);
let outer = h.session.borrow_mut().set_replaying(true);
let r = command(h, &s.id, &params);
+32 -10
View File
@@ -18,7 +18,8 @@
//!
//! Collections are counted from 0, and `pageItems` lists art topmost first, as
//! <https://ai-scripting.docsforadobe.dev/jsobjref/CMYKColor/> reads the frontmost path as
//! `pathItems[0]`. A collection read with a name, `pageItems["name"]`, gives the object `getByName`
//! `pathItems[0]`; the `layers` module gives the order of a layer's, a group's and a compound
//! path's lists. A collection read with a name, `pageItems["name"]`, gives the object `getByName`
//! gives, and a script may name the application's members without `app.`, as
//! <https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/> describes; here
//! that holds for `activeDocument`, `documents` and `selection`. `documents[0]` is the active
@@ -100,6 +101,7 @@ use crate::{DocState, Document, NodeId, NodeKind, Session, WindowView};
mod clipboard;
mod images;
pub(super) mod layers;
mod matrix;
pub mod preferences;
mod print;
@@ -125,7 +127,6 @@ pub(super) fn after_command(h: &Host, before: Option<(u64, Vec<crate::doc::DataS
mod colors;
mod defaults;
pub(super) mod layers;
mod paths;
#[cfg(test)]
@@ -186,6 +187,14 @@ pub(super) enum Coords {
const DOCUMENT_COORDS: &str = "CoordinateSystem.DOCUMENTCOORDINATESYSTEM";
const ARTBOARD_COORDS: &str = "CoordinateSystem.ARTBOARDCOORDINATESYSTEM";
#[cfg(test)]
thread_local! {
/// How many nodes the layer lists of `Layers` objects have looked at on this thread.
pub(crate) static LAYER_SCANS: Cell<u64> = const { Cell::new(0) };
/// How many lists of art the art collections have built on this thread.
pub(crate) static ART_SCANS: Cell<u64> = const { Cell::new(0) };
}
/// What the object model keeps for one run: its coordinate system, the lists of page items and the
/// answers of which objects are on a locked artboard for the last [`ITEM_LISTS`] documents read,
/// each kept while its document is unchanged, the lists of paths, the point changes of a path not
@@ -240,8 +249,13 @@ pub(super) struct State {
layer_lists: RefCell<Vec<layers::LayerList>>,
/// The uids of the documents whose active artboard `setActiveArtboardIndex` changed.
pub(super) active_artboards: RefCell<Vec<u64>>,
/// Each document's uid and revert generation when `setActiveArtboardIndex` last chose it.
pub(super) chosen_artboards: RefCell<Vec<(u64, u64)>>,
/// Each open document's uid and the index of its active artboard when the run started.
pub(super) boards_at_start: Vec<(u64, usize)>,
/// Each document made during the run whose active artboard `setActiveArtboardIndex` chose,
/// with the index it chose the first time.
pub(super) boards_chosen_in_new: RefCell<Vec<(u64, usize)>>,
/// `app.userInteractionLevel` ([`save_open`]).
save_options: save_open::State,
/// The print option objects ([`print`]).
@@ -259,8 +273,7 @@ pub(super) struct State {
}
impl State {
/// The state of a run that starts with the documents `docs` open and whose heap is
/// `heap_bytes`.
/// The state of a run that starts with the documents `docs` open and whose heap is `heap_bytes`.
pub(super) fn new(docs: &[DocState], heap_bytes: usize) -> Self {
Self { boards_at_start: docs.iter().map(|st| (st.uid, active_artboard(st))).collect(), preset_limit: heap_bytes as u64, ..Self::default() }
}
@@ -2307,6 +2320,10 @@ fn items_typename(h: &Host, a: &[Data]) -> Answer {
}
fn items_to_string(h: &Host, a: &[Data]) -> Answer {
if layers::is_scoped(a) {
layers::scoped_typename(h, a)?;
return Ok(text("[PageItems]"));
}
items_doc(h, a)?;
Ok(text("[PageItems]"))
}
@@ -2601,8 +2618,14 @@ fn item_set_locked(h: &Host, a: &[Data]) -> Answer {
set_props(h, a, |n| n.locked == locked, json!({"locked": locked}))
}
/// The percentage a page item's or a layer's `opacity` reports for `opacity`, rounded to four
/// decimals.
fn reported_opacity(opacity: f32) -> f64 {
(f64::from(opacity) * 100.0 * 1e4).round() / 1e4
}
fn item_opacity(h: &Host, a: &[Data]) -> Answer {
read_item(h, a, |_, n| Ok(num((f64::from(n.opacity) * 100.0 * 1e4).round() / 1e4)))
read_item(h, a, |_, n| Ok(num(reported_opacity(n.opacity))))
}
fn item_set_opacity(h: &Host, a: &[Data]) -> Answer {
@@ -2619,7 +2642,7 @@ fn item_set_opacity(h: &Host, a: &[Data]) -> Answer {
let (now, keeps_other) = with_doc(h, item.doc, |_, st| {
let d = &st.doc;
// Only the exact number the getter reports counts as the same opacity.
let now = d.node(item.id).map(|n| f64::from(n.opacity) * 100.0).filter(|now| (now * 1e4).round() / 1e4 == v);
let now = d.node(item.id).filter(|n| reported_opacity(n.opacity) == v).map(|n| f64::from(n.opacity) * 100.0);
let keeps_other =
crate::cmd::graph::series_object_opacity_differs(d, &[item.id]) || crate::cmd::graph::label_object_opacity_differs(d, &[item.id]);
(now, keeps_other)
@@ -3624,19 +3647,18 @@ fn classes(link: &Link) -> Vec<HostClass> {
classes.push(class("PageItem", None, page_item, None));
let own = |c: &&&str| **c == "TextFrame" || images::CLASSES.contains(c) || tracing::CLASSES.contains(c);
classes.extend(ITEM_CLASSES.iter().filter(|c| !own(c)).map(|c| {
let mut members = variables::item_members(l, c);
let mut members = layers::members(c, l);
members.extend(variables::item_members(l, c));
if *c == "PathItem" {
members.extend(paths::path_item_members(l));
} else {
members.extend(layers::members(c, l));
}
class(c, Some("PageItem"), members, None)
}));
classes.extend(layers::classes(l));
classes.extend(paths::classes(l));
classes.extend(colors::classes(l));
classes.extend(text::classes(l));
classes.extend(variables::classes(l));
classes.extend(layers::classes(l));
classes.extend(images::classes(l));
tracing::add_trace(&mut classes, l);
classes.extend(tracing::classes(l));
+1 -1
View File
@@ -39,7 +39,7 @@ const CLASSES: &[(&str, &[&str])] = &[
("PatternColor", &[]),
];
fn color_object(class: &str, values: &[(&str, f64)]) -> Data {
pub(super) fn color_object(class: &str, values: &[(&str, f64)]) -> Data {
let mut items = vec![("typename".to_string(), text(class))];
items.extend(values.iter().map(|(k, v)| ((*k).to_string(), num(*v))));
Data::Object(items)
+46 -9
View File
@@ -27,8 +27,10 @@
//! transparent palette entry. `RasterItem.file` is `null`, `embedded` is true and takes only
//! `true`, and `status` is `RasterLinkState.NODATA`, since a raster item has no linked file.
//! - `matrix` maps the image's pixels (row 0 at the top) to script coordinates, as a record of
//! `mValueA` to `mValueTY`; a distorted image has none. Assigning it runs `object.transform`; a
//! matrix with no area or one that puts a corner of the image outside the canvas is refused.
//! `mValueA` to `mValueTY`; a distorted image has none. Assigning it runs `object.transform`,
//! and assigning the matrix it reads runs nothing; a matrix with no area, one that puts a
//! corner of the image outside the canvas, or one a nearly singular image cannot reach exactly
//! is refused.
//! `boundingBox` is the pixel rectangle at one point a pixel, in the run's coordinate system.
use std::cell::RefCell;
@@ -291,7 +293,8 @@ fn doc_raster(h: &Host, a: &[Data]) -> Answer {
// ---- files ----
/// Whether the script may read `path` now by its own read scope and the read roots
/// ([`crate::file_access::ScriptGate`]), without the open documents' files a command may also read.
/// ([`crate::file_access::ScriptGate`]), without the open documents' files, or the files they link
/// to, that a command may also read.
fn may_read(h: &Host, path: &str) -> bool {
let gate = h.disk.borrow().gate(Vec::new(), crate::file_access::LinkedFiles::default());
crate::file_access::with_script_gate(gate, || crate::file_access::check_read(path)).is_ok()
@@ -496,16 +499,50 @@ fn set_matrix(h: &Host, a: &[Data], cls: &str) -> Answer {
return Err(HostError::Range("the matrix puts the image outside the canvas".into()));
}
let old = im.xf;
// The coordinate frame only changes the signs of the linear part, so any change to it
// counts; the offsets compare in points, which absorbs the rounding of the frame.
let same = old.as_coeffs().iter().zip(target.as_coeffs()).enumerate().all(|(k, (o, t))| if k < 4 { *o == t } else { (o - t).abs() <= 1e-9 });
if same {
// Unchanged means the numbers the `matrix` getter reports, compared exactly, so a small
// change such as `mValueTX` from 0 to 5e-10 still moves the image. A change that the
// conversion to document space rounds away leaves the image's matrix as it is and runs nothing.
// A coefficient the script left as the getter reports keeps the image's own value, so the
// conversion back does not shift an untouched axis.
let olds = old.as_coeffs();
let [a0, b0, c0, d0, e0, f0] = olds;
let reported = match h.dom.coords.get() {
Coords::Document => [a0, -b0, c0, -d0, e0 - f.left0, f.bottom0 - f0],
Coords::Artboard => [a0, b0, c0, d0, e0 - f.left, f0 - f.top],
};
let mut wanted = target.as_coeffs();
for ((w, o), (r, v)) in wanted.iter_mut().zip(olds).zip(reported.iter().zip(m.iter())) {
if r == v {
*w = o;
}
}
if wanted == olds {
return Ok(None);
}
if !area_of(old) {
return Err(HostError::Error("the image has no area to transform".into()));
}
Ok(Some((target * old.inverse()).as_coeffs()))
let target = Affine::new(wanted);
let [ta, tb, tc, td, te, tf] = wanted;
if [ta, tb, tc, td] == [a0, b0, c0, d0] {
// A move alone: the offset difference, without the error an inverse adds.
return Ok(Some([1.0, 0.0, 0.0, 1.0, te - e0, tf - f0]));
}
// A nearly singular image loses precision through the inverse; refuse a change that would
// not land where the script asked rather than move the image somewhere else.
let delta = target * old.inverse();
let landed = delta * old;
if landed.as_coeffs() == olds {
return Ok(None);
}
let close = [(0.0, 0.0), (w, 0.0), (0.0, ht), (w, ht)].iter().all(|&(x, y)| {
let (p, q) = (landed * Point::new(x, y), target * Point::new(x, y));
(p.x - q.x).abs() <= 1e-6 && (p.y - q.y).abs() <= 1e-6
});
if !close || !area_of(landed) {
return Err(HostError::Range("the matrix cannot be applied exactly to this image".into()));
}
Ok(Some(delta.as_coeffs()))
})?;
if let Some(d) = delta {
edit_item(h, item, "object.transform", &json!({"ids": [item.id.0], "matrix": d, "strokes": false}))?;
@@ -653,7 +690,7 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
]);
let mut placed = named(vec![
("file", property(l, placed_file, placed_set_file), typed("File")),
("relink", method(l, placed_relink), returns("undefined", &[("relinkFile", "File")])),
("relink", method(l, placed_relink), returns("undefined", &[("relinkFrom", "File")])),
("embed", method(l, placed_embed), returns("undefined", &[])),
("matrix", property(l, placed_matrix, placed_set_matrix), typed("Matrix")),
("boundingBox", get(l, placed_box), typed("Array")),
+134 -45
View File
@@ -20,7 +20,7 @@
//! - `locked` true means the layer is locked.
//! - `clipped = true` makes the group's topmost object, which must be a path, a compound path or
//! type, its clipping path, as the Layers panel's clipping mask button does; `false` releases it.
//! - A layer's `color` is an object `{red, green, blue}` with values from 0 to 255.
//! - A layer's `color` is an `RGBColor` object with values from 0 to 255.
//! - `CompoundPathItems.add()` makes an empty compound path. The first path a script moves into it
//! gives it its paint, as Make Compound Path takes the paint of a path it joins.
//! - `artboards.add` and `artboards.insert` stop at [`super::MAX_ARTBOARDS`] artboards in a
@@ -41,9 +41,9 @@ use vectorcraft_js::{Data, HostClass, HostError, MemberInfo, host_ref, host_ref_
use super::{
Answer, Described, Doc, Item, MAX_LISTED, MAX_TEXT_BYTES, NOT_FOUND, ON_LOCKED_ARTBOARD, Placement, STALE_DOCUMENT, STALE_ITEM, active_artboard,
arg, boolean, class_text, command, command_value, doc_of, doc_ref, editable, find_doc, float, frame, get, handle_of, id_of, item_of, item_ref,
later, method, named, named_text, num, number, on_doc, on_doc_layer, page_items, placement_of, property, returns, text, typed, typename, whole,
with_doc,
arg, boolean, command, command_value, doc_of, doc_ref, editable, find_doc, float, frame, get, handle_of, id_of, item_of, item_ref, later, method,
named, named_text, num, number, on_doc, on_doc_layer, page_items, placement_of, property, reported_opacity, returns, text, typed, typename,
whole, with_doc,
};
use crate::script::{Host, Link};
use crate::{DocState, Document, NodeId, NodeKind};
@@ -233,7 +233,7 @@ fn layer_set_dim(h: &Host, a: &[Data]) -> Answer {
}
fn layer_opacity(h: &Host, a: &[Data]) -> Answer {
read_layer(h, a, |_, n| Ok(num((f64::from(n.opacity) * 100.0 * 1e4).round() / 1e4)))
read_layer(h, a, |_, n| Ok(num(reported_opacity(n.opacity))))
}
fn layer_set_opacity(h: &Host, a: &[Data]) -> Answer {
@@ -241,14 +241,13 @@ fn layer_set_opacity(h: &Host, a: &[Data]) -> Answer {
if !(0.0..=100.0).contains(&v) {
return Err(HostError::Range("opacity must be from 0 to 100".into()));
}
set_layer(h, a, "object.setProps", |n| (f64::from(n.opacity) * 100.0 - v).abs() < 1e-4, json!({"opacity": v}))
set_layer(h, a, "object.setProps", |n| reported_opacity(n.opacity) == v, json!({"opacity": v}))
}
fn layer_color(h: &Host, a: &[Data]) -> Answer {
read_layer(h, a, |_, n| {
let [r, g, b] = layer_flags(n).3.rgb();
let item = |k: &str, v: u8| (k.to_string(), num(f64::from(v)));
Ok(Data::Object(vec![item("red", r), item("green", g), item("blue", b)]))
Ok(super::colors::color_object("RGBColor", &[("red", f64::from(r)), ("green", f64::from(g)), ("blue", f64::from(b))]))
})
}
@@ -280,10 +279,6 @@ fn layer_to_string(h: &Host, a: &[Data]) -> Answer {
named_text("Layer", layer_name(h, a))
}
fn board_to_string(h: &Host, a: &[Data]) -> Answer {
named_text("Artboard", board_name(h, a))
}
fn layer_typename(h: &Host, a: &[Data]) -> Answer {
this_layer(h, a)?;
Ok(text("Layer"))
@@ -295,6 +290,8 @@ fn layer_z_position(h: &Host, a: &[Data]) -> Answer {
let (doc, id) = this_layer(h, a)?;
let at = with_doc(h, doc, |_, st| {
let list = layer_ids(h, st, st.doc.parent_of(id))?;
// The scan is charged by itself: a list kept from an earlier read was charged once.
h.charge_call(list.len() as u64)?;
Ok::<_, HostError>(list.iter().position(|l| *l == id).map(|i| list.len() - i))
})?;
at.map(|i| num(float(i as u64))).ok_or_else(|| HostError::Error(STALE_LAYER.into()))
@@ -305,35 +302,59 @@ fn layer_has_selected(h: &Host, a: &[Data]) -> Answer {
Ok(Data::Bool(with_doc(h, doc, |_, st| st.selection.objects.iter().any(|o| st.doc.ancestry(*o).is_some_and(|a| a.contains(&id))))))
}
/// Collects visible, unlocked art through non-template sublayers, bottom first, and counts every
/// child visited, including skipped children.
fn collect_editable_art(n: &crate::doc::Node, out: &mut Vec<NodeId>) -> u64 {
let mut count = 0;
for child in n.children().into_iter().flatten() {
count += 1;
if child.is_ruler_guide() || !child.visible || child.locked || child.is_template() {
continue;
}
if child.is_layer() {
count += collect_editable_art(child, out);
} else {
out.push(child.id);
}
}
count
}
/// `hasSelectedArtwork = false` deselects the layer's art with `select.toggle`; `true` adds its
/// visible, unlocked art with `select.add`. The rest of the selection, ruler guides included, stays,
/// and no command runs when there is nothing to deselect or add.
fn layer_set_has_selected(h: &Host, a: &[Data]) -> Answer {
let on = boolean(arg(a, 1), "hasSelectedArtwork")?;
let (doc, id) = this_layer(h, a)?;
let (ids, total) = with_doc(h, doc, |_, st| {
let (ids, over) = with_doc(h, doc, |_, st| {
let inside = |o: &NodeId| st.doc.ancestry(*o).is_some_and(|a| a.contains(&id));
let selected = &st.selection.objects;
h.charge_call(selected.len() as u64)?;
if !on {
return (selected.iter().copied().filter(inside).collect::<Vec<_>>(), 0);
return Ok::<_, HostError>((selected.iter().copied().filter(inside).collect::<Vec<_>>(), false));
}
let locks = st.doc.locked_artboards();
let art = st.doc.node(id).map(|n| n.layer_art(true)).unwrap_or_default();
let mut art = Vec::new();
let count = st.doc.node(id).map_or(0, |n| collect_editable_art(n, &mut art));
// The walk is charged by every node it looks at, hidden and locked ones included, whether
// or not anything is added.
h.charge_call(count)?;
let mut have: std::collections::HashSet<NodeId> = selected.iter().copied().collect();
let mut ids = Vec::new();
for o in art {
if selected.len() + ids.len() > MAX_LISTED {
break;
if have.contains(&o) || !crate::cmd::select::is_selectable(&st.doc, st.isolation, &locks, o) {
continue;
}
if !have.contains(&o) && crate::cmd::select::is_selectable(&st.doc, st.isolation, &locks, o) {
have.insert(o);
ids.push(o);
// Only art that would be added counts toward the limit.
if selected.len() + ids.len() >= MAX_LISTED {
return Ok((ids, true));
}
have.insert(o);
ids.push(o);
}
let total = selected.len() + ids.len();
(ids, total)
});
if total > MAX_LISTED {
Ok((ids, false))
})?;
if over {
return Err(HostError::Range(format!("a selection takes at most {MAX_LISTED} objects")));
}
if ids.is_empty() {
@@ -478,8 +499,7 @@ fn layers_scope(h: &Host, d: &Data) -> Result<(Doc, Option<NodeId>)> {
[run, uid] => Ok((find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?, None)),
[_, _, _, _, _] => {
// A collection read before its document was reverted is stale, as its layer is.
let (doc, id) = super::node_of(h, &handle).ok_or_else(|| HostError::Error(STALE_LAYER.into()))?;
let (doc, id) = held_layer(h, doc, id)?;
let (doc, id) = layer_of(h, &host_ref("Layer", &handle))?;
Ok((doc, Some(id)))
}
_ => Err(type_error("Layers")),
@@ -492,6 +512,8 @@ fn layer_list(d: &Document, parent: Option<NodeId>) -> Vec<NodeId> {
None => Some(&d.layers),
Some(p) => d.children(Some(p)),
};
#[cfg(test)]
super::LAYER_SCANS.with(|c| c.set(c.get() + list.map_or(0, |l| l.len() as u64)));
list.into_iter().flatten().rev().filter(|n| n.is_layer()).map(|n| n.id).collect()
}
@@ -612,7 +634,7 @@ fn layers_remove_all(h: &Host, a: &[Data]) -> Answer {
if parent.is_none() {
return Err(HostError::Error("a document needs at least one layer".into()));
}
let ids = with_doc(h, doc, |_, st| layer_list(&st.doc, parent));
let ids = with_doc(h, doc, |_, st| layer_ids(h, st, parent))?;
if !ids.is_empty() {
on_doc(h, doc.uid, true, |h| command(h, "layer.delete", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})))?;
}
@@ -664,6 +686,8 @@ fn art_list(h: &Host, st: &DocState, kind: Kind, container: Option<NodeId>) -> R
return Ok(ids);
}
}
#[cfg(test)]
super::ART_SCANS.with(|c| c.set(c.get() + 1));
let ids: Vec<NodeId> = match container {
None => {
let all = page_items(h, st)?;
@@ -756,7 +780,7 @@ fn art_index(h: &Host, a: &[Data], kind: Kind) -> Answer {
/// `pageItems.removeAll()` is stopped.
fn art_remove_all(h: &Host, a: &[Data], kind: Kind) -> Answer {
let (doc, c) = art_scope(h, arg(a, 0), kind.class())?;
let (ids, refused, on_locked) = with_doc(h, doc, |_, st| {
let (ids, refused, on_locked, masks) = with_doc(h, doc, |_, st| {
let all = art_list(h, st, kind, c)?;
let d = &st.doc;
let listed: std::collections::HashSet<NodeId> = all.iter().copied().collect();
@@ -766,7 +790,22 @@ fn art_remove_all(h: &Host, a: &[Data], kind: Kind) -> Answer {
let refused: Vec<u64> = ids.iter().filter(|i| !whole(i)).map(|i| i.0).take(20).collect();
let locks = d.locked_artboards();
let on_locked: Vec<u64> = ids.iter().filter(|i| locks.holds_id(**i)).map(|i| i.0).take(20).collect();
Ok::<_, HostError>((ids, refused, on_locked))
// A clipping path whose group or layer keeps other art would leave the next object clipping it.
let going: std::collections::HashSet<NodeId> = ids.iter().copied().collect();
let masks: Vec<u64> = ids
.iter()
.filter(|i| {
d.parent_of(**i).and_then(|p| d.node(p)).is_some_and(|p| {
let kids = p.children().map_or(&[][..], Vec::as_slice);
p.clips()
&& kids.first().is_some_and(|f| f.id == **i)
&& kids.iter().any(|k| !going.contains(&k.id) && !matches!(k.kind, NodeKind::RulerGuide { .. }))
})
})
.map(|i| i.0)
.take(20)
.collect();
Ok::<_, HostError>((ids, refused, on_locked, masks))
})?;
if !refused.is_empty() {
let list = refused.iter().map(u64::to_string).collect::<Vec<_>>().join(", ");
@@ -776,8 +815,14 @@ fn art_remove_all(h: &Host, a: &[Data], kind: Kind) -> Answer {
let list = on_locked.iter().map(u64::to_string).collect::<Vec<_>>().join(", ");
return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {list}")));
}
if !masks.is_empty() {
let list = masks.iter().map(u64::to_string).collect::<Vec<_>>().join(", ");
return Err(HostError::Error(format!(
"cannot delete a clipping path while its group or layer keeps other objects; release the clipping mask first: {list}"
)));
}
if !ids.is_empty() {
on_doc(h, doc.uid, true, |h| command(h, "edit.clear", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})))?;
on_doc(h, doc.uid, true, |h| command(h, "edit.clear", &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "keepEmpty": true})))?;
}
Ok(Data::Undefined)
}
@@ -976,6 +1021,7 @@ fn group_set_clipped(h: &Host, a: &[Data]) -> Answer {
if now == on {
return Ok(Data::Undefined);
}
super::refuse_protected_edit(h, item)?;
if !ok {
return Err(HostError::Error(format!("Cannot change GroupItem {}: it is hidden or locked", item.id.0)));
}
@@ -988,11 +1034,6 @@ pub(super) fn page_item_members(l: &Link) -> Vec<Described> {
named(vec![("layer", get(l, item_layer), typed("Layer"))])
}
/// A collection member's type for `reflect`.
fn listed(data_type: &str) -> MemberInfo {
MemberInfo { collection: true, ..typed(data_type) }
}
/// The members a page item class adds to `PageItem`'s.
pub(super) fn members(class: &str, l: &Link) -> Vec<Described> {
match class {
@@ -1012,6 +1053,11 @@ pub(super) fn members(class: &str, l: &Link) -> Vec<Described> {
}
}
/// What `reflect` tells of a member whose value is a collection of class `data_type`.
fn listed(data_type: &str) -> MemberInfo {
MemberInfo { collection: true, ..typed(data_type) }
}
// ---- Document ----
fn doc_layers(h: &Host, a: &[Data]) -> Answer {
@@ -1187,6 +1233,10 @@ fn board_typename(h: &Host, a: &[Data]) -> Answer {
Ok(text("Artboard"))
}
fn board_to_string(h: &Host, a: &[Data]) -> Answer {
named_text("Artboard", board_name(h, a))
}
/// `rulerOrigin`: where the rulers measure from with this artboard active, from its top-left corner
/// with Y down.
fn board_ruler_origin(h: &Host, a: &[Data]) -> Answer {
@@ -1273,6 +1323,24 @@ fn boards_typename(h: &Host, a: &[Data]) -> Answer {
Ok(text("Artboards"))
}
/// `toString()` of a collection: `[Class]`, after the same checks of the collection as `typename`.
fn layers_to_string(h: &Host, a: &[Data]) -> Answer {
layers_scope(h, arg(a, 0))?;
Ok(text("[Layers]"))
}
fn groups_to_string(h: &Host, a: &[Data]) -> Answer {
art_scope(h, arg(a, 0), Kind::Group.class())?;
Ok(text("[GroupItems]"))
}
fn compounds_to_string(h: &Host, a: &[Data]) -> Answer {
art_scope(h, arg(a, 0), Kind::Compound.class())?;
Ok(text("[CompoundPathItems]"))
}
fn boards_to_string(h: &Host, a: &[Data]) -> Answer {
boards_doc(h, a)?;
Ok(text("[Artboards]"))
}
/// An artboard index argument: a whole number below `len` (`len + 1` with `insert`).
fn board_index_arg(d: &Data, len: usize, what: &str) -> Result<usize> {
let n = number(d, what)?;
@@ -1360,12 +1428,13 @@ fn boards_add(h: &Host, a: &[Data]) -> Answer {
add_board(h, a, None)
}
/// `artboards.insert(artboardRect, index)`: a new artboard at `index`.
/// `artboards.insert(artboardRect, index)`: a new artboard at `index`. → nothing.
fn boards_insert(h: &Host, a: &[Data]) -> Answer {
if matches!(arg(a, 2), Data::Undefined) {
return Err(HostError::Type("insert needs an index".into()));
}
add_board(h, a, Some(arg(a, 2)))
add_board(h, a, Some(arg(a, 2)))?;
Ok(Data::Undefined)
}
fn boards_remove(h: &Host, a: &[Data]) -> Answer {
@@ -1382,16 +1451,36 @@ fn boards_active(h: &Host, a: &[Data]) -> Answer {
}
/// `setActiveArtboardIndex(index)`: the artboard becomes the view's active one. Nothing in the
/// document changes, and no command runs.
/// document changes, and no command runs. The artboard is kept by its id even when it is already
/// active only as the fallback (no artboard chosen yet), so an artboard inserted before it later
/// in the run moves it to the next index instead of taking its place.
fn boards_set_active(h: &Host, a: &[Data]) -> Answer {
let doc = boards_doc(h, a)?;
let (len, now) = with_doc(h, doc, |_, st| (st.doc.artboards.len(), active_artboard(st)));
let i = board_index_arg(arg(a, 1), len, "index")?;
if i != now {
{
let mut s = h.session.borrow_mut();
let st = s.document_mut(doc.uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?;
st.active_artboard = st.doc.artboards.get(i).map(|ab| ab.id);
drop(s);
}
{
let mut chosen = h.dom.chosen_artboards.borrow_mut();
let reverts = with_doc(h, doc, |_, st| st.reverts);
if let Some((_, generation)) = chosen.iter_mut().find(|(uid, _)| *uid == doc.uid) {
*generation = reverts;
} else {
chosen.push((doc.uid, reverts));
}
}
// A document made during the run has no index from the start of the run, so the first choice
// records one; an artboard inserted before it later still puts it in the report.
if !h.dom.boards_at_start.iter().any(|(uid, _)| *uid == doc.uid) {
let mut made = h.dom.boards_chosen_in_new.borrow_mut();
if !made.iter().any(|(uid, _)| *uid == doc.uid) {
made.push((doc.uid, i));
}
}
if i != now {
let mut moved = h.dom.active_artboards.borrow_mut();
if !moved.contains(&doc.uid) {
moved.push(doc.uid);
@@ -1466,7 +1555,7 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
("getByName", method(l, layers_by_name), returns("Layer", &[("name", "string")])),
("add", method(l, layers_add), returns("Layer", &[])),
("removeAll", method(l, layers_remove_all), returns("undefined", &[])),
("toString", class_text("Layers"), returns("string", &[])),
("toString", method(l, layers_to_string), returns("string", &[])),
]),
Some(super::function(l, layers_at)),
),
@@ -1482,7 +1571,7 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
("getByName", method(l, groups_by_name), returns("GroupItem", &[("name", "string")])),
("add", method(l, groups_add), returns("GroupItem", &[])),
("removeAll", method(l, groups_remove_all), returns("undefined", &[])),
("toString", class_text("GroupItems"), returns("string", &[])),
("toString", method(l, groups_to_string), returns("string", &[])),
]);
m.push(later(l, "GroupItems", "createFromFile"));
m
@@ -1500,7 +1589,7 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
("getByName", method(l, compounds_by_name), returns("CompoundPathItem", &[("name", "string")])),
("add", method(l, compounds_add), returns("CompoundPathItem", &[])),
("removeAll", method(l, compounds_remove_all), returns("undefined", &[])),
("toString", class_text("CompoundPathItems"), returns("string", &[])),
("toString", method(l, compounds_to_string), returns("string", &[])),
]),
Some(super::function(l, compounds_at)),
),
@@ -1532,11 +1621,11 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
("index", method(l, boards_index), returns("Artboard", &[("itemKey", "*")])),
("getByName", method(l, boards_by_name), returns("Artboard", &[("name", "string")])),
("add", method(l, boards_add), returns("Artboard", &[("artboardRect", "Array")])),
("insert", method(l, boards_insert), returns("Artboard", &[("artboardRect", "Array"), ("index", "number")])),
("insert", method(l, boards_insert), returns("undefined", &[("artboardRect", "Array"), ("index", "number")])),
("remove", method(l, boards_remove), returns("undefined", &[("index", "number")])),
("getActiveArtboardIndex", method(l, boards_active), returns("number", &[])),
("setActiveArtboardIndex", method(l, boards_set_active), returns("undefined", &[("index", "number")])),
("toString", class_text("Artboards"), returns("string", &[])),
("toString", method(l, boards_to_string), returns("string", &[])),
]),
Some(super::function(l, boards_at)),
),
+171 -15
View File
@@ -1,9 +1,10 @@
//! The matrix functions of `app`, as the help pages
//! <https://ai-scripting.docsforadobe.dev/jsobjref/Matrix/> and
//! <https://ai-scripting.docsforadobe.dev/jsobjref/Application/> describe them. A matrix is a plain
//! record with `mValueA`, `mValueB`, `mValueC`, `mValueD`, `mValueTX` and `mValueTY` and the
//! `typename` `"Matrix"`; each function other than `isEqualMatrix` and `isSingularMatrix` gives a
//! new record, those two give a boolean, and none changes the records passed to it.
//! record with the finite numbers `mValueA`, `mValueB`, `mValueC`, `mValueD`, `mValueTX` and
//! `mValueTY`; a record passed in needs only those six, and each record a function gives also has
//! the `typename` `"Matrix"`. Each function other than `isEqualMatrix` and `isSingularMatrix` gives
//! a new record, those two give a boolean, and none changes the records passed to it.
//!
//! The record maps a point `(x, y)` to `(a·x + c·y + tx, b·x + d·y + ty)`, as a PDF `cm` matrix
//! does (ISO 32000-1, 8.3.4), in script coordinates with Y up.
@@ -19,7 +20,7 @@
//! - An argument that is not a finite number, or a matrix with a value that is not one, throws a
//! `TypeError`; a result with a value too large for a number throws a `RangeError`.
use vectorcraft_js::{Data, HostError};
use vectorcraft_js::{Data, HostError, MemberInfo};
use super::{Answer, Described, Host, Link, arg, method, named, num, returns, text};
@@ -54,6 +55,24 @@ pub(super) fn app_members(link: &Link) -> Vec<Described> {
("isEqualMatrix", method(l, is_equal), returns("boolean", &[("matrix", "Matrix"), ("secondMatrix", "Matrix")])),
("isSingularMatrix", method(l, is_singular), returns("boolean", &[("matrix", "Matrix")])),
])
.into_iter()
.map(|(name, member, info)| (name, member, with_defaults(info)))
.collect()
}
/// `info` with the defaults of its left-out number arguments, which `reflect` reports: 0 for a
/// translation and an angle, 100 for a horizontal scale. A left-out vertical scale is the
/// horizontal one, so it has no fixed default and its description says so.
fn with_defaults(mut info: MemberInfo) -> MemberInfo {
for a in &mut info.arguments {
match a.name.as_str() {
"deltaX" | "deltaY" | "angle" => a.default = Some(num(0.0)),
"scaleX" => a.default = Some(num(100.0)),
"scaleY" => a.description = Some("The vertical scale; when it is left out, the horizontal scale.".into()),
_ => {}
}
}
info
}
/// The record for `m`, or a `RangeError` when a value is not finite.
@@ -125,26 +144,29 @@ fn products_sum(x: f64, y: f64, z: f64, w: f64, t: f64) -> f64 {
// Each product is split into its rounded value and the part that rounding drops, both exact.
// The five parts are added one at a time into a list of values that do not overlap, smallest
// first, whose sum is exact (Shewchuk's expansion).
let product = |a: f64, b: f64| {
let (a, b) = (Wide::of(a), Wide::of(b));
let (hi, e) = (a.m * b.m, a.e.saturating_add(b.e));
[Wide::new(hi, e), Wide::new(a.m.mul_add(b.m, 0.0 - hi), e)]
};
let ([p, p_lost], [q, q_lost]) = (product(x, y), product(z, w));
let exact = [p, p_lost, q, q_lost, Wide::of(t)].into_iter().fold(Parts::EMPTY, grow);
nearest(exact)
}
/// `a·b` as its rounded value and the part that rounding drops, both exact.
fn product(a: f64, b: f64) -> [Wide; 2] {
let (a, b) = (Wide::of(a), Wide::of(b));
let (hi, e) = (a.m * b.m, a.e.saturating_add(b.e));
[Wide::new(hi, e), Wide::new(a.m.mul_add(b.m, 0.0 - hi), e)]
}
/// Values that do not overlap, smallest first, held without allocating. Each value added keeps at
/// most one more, so the five parts of a sum and the two of a comparison fit.
/// most one more, so the five parts of a sum, the two of a comparison and the sixteen of an
/// inverse's rounding test fit.
#[derive(Clone, Copy)]
struct Parts {
v: [Wide; 8],
v: [Wide; 16],
n: usize,
}
impl Parts {
const EMPTY: Self = Self { v: [Wide { m: 0.0, e: 0 }; 8], n: 0 };
const EMPTY: Self = Self { v: [Wide { m: 0.0, e: 0 }; 16], n: 0 };
fn as_slice(&self) -> &[Wide] {
&self.v[..self.n]
@@ -416,9 +438,143 @@ fn invert(_: &Host, a: &[Data]) -> Answer {
// Each value is divided by the determinant before it is brought back into the range of a
// number, and the translations are taken whole, so a finite inverse is not lost to an
// intermediate value. Adding 0 turns -0 into 0.
let over = |w: Wide| w.div(det).value() + 0.0;
let plain = |v: f64| over(Wide::of(v));
record([plain(d), plain(0.0 - b), plain(0.0 - c), plain(a), over(products_difference(c, f, d, e)), over(products_difference(b, e, a, f))])
let exact_det = || difference_parts(a, d, b, c);
let zero = Wide::of(0.0);
let plain = |v: f64| quotient(Wide::of(v), || [Wide::of(v), zero, zero, zero], det, exact_det);
record([
plain(d),
plain(0.0 - b),
plain(0.0 - c),
plain(a),
quotient(products_difference(c, f, d, e), || difference_parts(c, f, d, e), det, exact_det),
quotient(products_difference(b, e, a, f), || difference_parts(b, e, a, f), det, exact_det),
])
}
/// `a·d − b·c` as four exact parts.
fn difference_parts(a: f64, d: f64, b: f64, c: f64) -> [Wide; 4] {
let neg = |w: Wide| Wide { m: 0.0 - w.m, e: w.e };
let ([p, p_lost], [q, q_lost]) = (product(a, d), product(b, c));
[p, p_lost, neg(q), neg(q_lost)]
}
/// The quotient of `num` by `det`, from their rounded values `num` and `det` and their exact parts.
/// The result is the rounded quotient, which is within a few steps of the exact one, except where
/// that would decide overflow wrongly. When the rounded quotient overflows or lies within eight
/// steps of the largest number, the exact quotient is compared with 2^1024 − 2^970, the halfway
/// point between the largest number and 2^1024: at it or past it the result is infinite. Below it
/// a finite rounded quotient is kept, and an infinite one is replaced by the number the exact
/// quotient rounds to, found from the halfway points 2^1024 − j·2^970 (odd `j`) below, ties to the
/// even one. When the rounded quotient is below 2^-1023, where every number is a multiple of the
/// smallest number, the result is the multiple whose halfway points to its neighbors hold the exact
/// quotient, ties to the even one, so a quotient just past half the smallest number is not rounded
/// to 0. The exact parts are worked out only then. Adding 0 turns -0 into 0.
fn quotient(num: Wide, exact_num: impl Fn() -> [Wide; 4], det: Wide, exact_det: impl Fn() -> [Wide; 4]) -> f64 {
if num.m == 0.0 {
return 0.0;
}
let v = num.div(det).value() + 0.0;
// 2^1024 − 9·2^971, eight steps below the largest number.
let near_top = f64::MAX - 8.0 * pow2(971);
let tiny = f64::MIN_POSITIVE / 2.0;
if v.is_finite() && v.abs() < near_top && v.abs() >= tiny {
return v;
}
let (exact_num, exact_det) = (exact_num(), exact_det());
let sign = |parts: &[Wide]| match parts.iter().copied().fold(Parts::EMPTY, grow).as_slice().last() {
Some(w) if w.m < 0.0 => -1.0,
_ => 1.0,
};
let (sn, sd) = (sign(&exact_num), sign(&exact_det));
if v.abs() < tiny {
return small_quotient(v, &exact_num, &exact_det, sn, sd);
}
// The sign of |num| − (2^1024 − j·2^970)·|det|. Scaling by a power of 2 is exact, and each
// `j·m` is split into its rounded value and the part that rounding drops.
let past = |j: f64| {
let scaled = |w: Wide, s: f64, e: i32| Wide { m: w.m * s, e: w.e.saturating_add(e) };
let times_j = |w: Wide| {
let hi = j * w.m * sd;
let lo = (j * sd).mul_add(w.m, 0.0 - hi);
[Wide::new(hi, w.e.saturating_add(970)), Wide::new(lo, w.e.saturating_add(970))]
};
let sum = exact_num
.iter()
.map(|&w| scaled(w, sn, 0))
.chain(exact_det.iter().map(|&w| scaled(w, 0.0 - sd, 1024)))
.chain(exact_det.iter().flat_map(|&w| times_j(w)))
.fold(Parts::EMPTY, grow);
match sum.as_slice().last() {
Some(w) if w.m > 0.0 => 1,
Some(w) if w.m < 0.0 => -1,
_ => 0,
}
};
if past(1.0) >= 0 {
return f64::INFINITY;
}
if v.is_finite() {
return v;
}
let even = |x: f64| x.to_bits() & 1 == 0;
let mut top = f64::MAX;
for k in 1..16u8 {
let below = top.next_down();
match past(f64::from(2 * k + 1)) {
1 => return top * sn * sd,
0 => return if even(top) { top } else { below } * sn * sd,
_ => top = below,
}
}
top * sn * sd
}
/// The exact quotient of `exact_num` by `exact_det`, whose signs are `sn` and `sd`, rounded to a
/// multiple of the smallest number, ties to the even multiple, starting from the rounded quotient
/// `v`, which is below 2^-1023 and within a few steps of it.
fn small_quotient(v: f64, exact_num: &[Wide; 4], exact_det: &[Wide; 4], sn: f64, sd: f64) -> f64 {
let step = f64::from_bits(1);
// The sign of |num| − j·2^-1075·|det|, with each `j·m` split into its rounded value and the
// part that rounding drops. `j` is odd and below 2^53, so it is exact.
let past = |j: f64| {
let times_j = |w: Wide| {
let hi = j * w.m * sd;
let lo = (j * sd).mul_add(w.m, 0.0 - hi);
[Wide::new(0.0 - hi, w.e.saturating_sub(1075)), Wide::new(0.0 - lo, w.e.saturating_sub(1075))]
};
let sum = exact_num.iter().map(|&w| Wide { m: w.m * sn, e: w.e }).chain(exact_det.iter().flat_map(|&w| times_j(w))).fold(Parts::EMPTY, grow);
match sum.as_slice().last() {
Some(w) if w.m > 0.0 => 1,
Some(w) if w.m < 0.0 => -1,
_ => 0,
}
};
// `k` steps; dividing by the smallest number is exact.
let mut k = v.abs() / step;
let even = |k: f64| k % 2.0 == 0.0;
for _ in 0..8 {
match past(2.0 * k + 1.0) {
1 => k += 1.0,
0 => {
k = if even(k) { k } else { k + 1.0 };
break;
}
_ => {
if k == 0.0 {
break;
}
match past(2.0 * k - 1.0) {
-1 => k -= 1.0,
0 => {
k = if even(k) { k } else { k - 1.0 };
break;
}
_ => break,
}
}
}
}
k * step * sn * sd + 0.0
}
fn is_equal(_: &Host, a: &[Data]) -> Answer {
+1 -1
View File
@@ -1985,6 +1985,7 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
None,
named(vec![
("typename", get(l, items_typename), typed("string")),
("toString", super::class_text("PathItems"), returns("string", &[])),
("length", get(l, items_length), typed("number")),
("parent", get(l, items_parent), typed("*")),
("index", method(l, items_index), returns("PathItem", &[("itemKey", "*")])),
@@ -2004,7 +2005,6 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
method(l, items_star),
returns("PathItem", &with(&center, &[("innerRadius", "number"), ("points", "number"), ("reversed", "boolean")])),
),
("toString", class_text("PathItems"), returns("string", &[])),
]),
Some(super::function(l, items_at)),
),
+2 -1
View File
@@ -2757,7 +2757,8 @@ impl Session {
"hostCalls": host.calls.get(),
});
host.more_written(&mut report);
if let Some(boards) = dom::layers::active_artboards(&host.dom.active_artboards.borrow(), &host.dom.boards_at_start, self.documents()) {
let start: Vec<(u64, usize)> = host.dom.boards_at_start.iter().chain(host.dom.boards_chosen_in_new.borrow().iter()).copied().collect();
if let Some(boards) = dom::layers::active_artboards(&host.dom.active_artboards.borrow(), &start, self.documents()) {
report["activeArtboards"] = boards;
}
// The run ran a Copy or Cut, and the clipboard still holds what one put there.
+76
View File
@@ -262,6 +262,82 @@ fn steps_act_on_the_artboard_active_as_they_run() {
assert_eq!(left(&s), was[0].x0, "a step that names artboard 0 keeps it");
}
/// After the script makes another artboard active with `setActiveArtboardIndex`, a step that acts
/// on the active artboard acts on that one.
#[test]
fn steps_act_on_the_artboard_the_script_made_active() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 100, "height": 100, "units": "Points", "artboards": 3})).unwrap();
let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 30})).unwrap()["id"].as_u64().unwrap();
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
s.execute("select.set", &json!({"ids": [id]})).unwrap();
let was: Vec<_> = s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect();
make_active(&mut s, 0);
let actions = set(&[("Fit", vec![json!({"command": "artboard.fitToSelection"})])]);
log_with(&mut s, "app.activeDocument.artboards.setActiveArtboardIndex(1); app.doScript('Fit', 'Set');", &actions);
let now: Vec<_> = s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect();
assert_eq!(now[0], was[0], "the artboard active as the run started is unchanged");
assert_ne!(now[1], was[1], "the artboard the script made active is fitted");
// Choosing the artboard that is already active, after an insert moved it, also counts.
make_active(&mut s, 0);
let was: Vec<_> = s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect();
log_with(
&mut s,
"var b = app.activeDocument.artboards; b.insert([300, 300, 400, 200], 0); b.setActiveArtboardIndex(1); app.doScript('Fit', 'Set');",
&actions,
);
let now: Vec<_> = s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect();
assert_ne!(now[1], was[0], "the artboard chosen again is fitted");
}
#[test]
fn steps_use_the_chosen_index_when_the_chosen_artboard_is_deleted() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 100, "height": 100, "units": "Points", "artboards": 3})).unwrap();
let id = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 30})).unwrap()["id"].as_u64().unwrap();
s.execute("paint.setStroke", &json!({"none": true})).unwrap();
s.execute("select.set", &json!({"ids": [id]})).unwrap();
let was: Vec<_> = s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect();
make_active(&mut s, 2);
let actions = set(&[("Fit", vec![json!({"command": "artboard.fitToSelection"})])]);
let report = run_with(
&mut s,
"var b = app.activeDocument.artboards; b.setActiveArtboardIndex(2); b.remove(2);\
vc.log(b.getActiveArtboardIndex()); app.coordinateSystem = CoordinateSystem.ARTBOARDCOORDINATESYSTEM;\
vc.log(app.activeDocument.selection[0].position); app.doScript('Fit', 'Set');",
&actions,
)
.unwrap();
assert_eq!(report["log"], json!([0, [10, 10]]));
assert_eq!(report["activeArtboards"], json!([{"document": 0, "artboard": 0}]));
let now: Vec<_> = s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect();
assert_eq!(now.len(), 2);
assert_ne!(now[0], was[0], "the fallback artboard is fitted");
assert_eq!(now[1], was[1], "the other artboard is unchanged");
}
#[test]
fn steps_discard_the_chosen_artboard_after_revert() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 100, "height": 100, "units": "Points", "artboards": 3})).unwrap();
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 30})).unwrap();
let folder = vectorcraft_testkit::TempDir::new("script-actions-revert-artboard");
let path = folder.join("saved.vectorcraft");
s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap();
let was: Vec<_> = s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect();
make_active(&mut s, 2);
let actions = set(&[("Fit", vec![json!({"command": "artboard.fitToSelection"})])]);
log_with(
&mut s,
"app.activeDocument.artboards.setActiveArtboardIndex(0); app.activeDocument.pageItems[0].name = 'changed'; vc.run('file.revert');\
app.activeDocument.selection = app.activeDocument.pageItems[0]; app.doScript('Fit', 'Set');",
&actions,
);
let now: Vec<_> = s.active().unwrap().doc.artboards.iter().map(|a| a.rect).collect();
assert_eq!(now[..2], was[..2]);
assert_ne!(now[2], was[2], "playback uses the run's original index after revert");
}
/// A recorded `command.batch` step that names its `artboard` gives it to its steps that name none,
/// past the last artboard the last one, as `command.batch` does; a step that names its own keeps it.
#[test]
+541 -7
View File
@@ -665,6 +665,23 @@ fn assigning_the_reported_opacity_changes_nothing() {
assert_eq!(undo_steps(&s), steps + 1);
}
/// An item's or a layer's opacity that differs from the reported one, however little, is set as
/// given.
#[test]
fn an_opacity_near_the_reported_one_is_still_set() {
let (mut s, a, _) = doc();
s.execute("object.setProps", &json!({"id": a.0, "opacity": 0})).unwrap();
let out = log(
&mut s,
"var q = app.activeDocument.pageItems, i = q[0].opacity === 0 ? q[0] : q[1]; i.opacity = 0.00009; vc.log(i.opacity);\
var l = app.activeDocument.layers[0]; l.opacity = 0; l.opacity = 0.00009; vc.log(l.opacity);",
);
assert_eq!(out, vec![json!(0.0001), json!(0.0001)]);
let d = &s.active().unwrap().doc;
assert!(d.node(a).unwrap().opacity > 0.0);
assert!(d.node(d.layer_containing(a).unwrap()).unwrap().opacity > 0.0);
}
/// `blendingMode` reads and sets the object's own blend mode as a `BlendModes` value; the mode it
/// already has adds no undo step, and any other value throws and changes nothing.
#[test]
@@ -2293,6 +2310,25 @@ fn scoped_collections_find_names_that_are_numbers() {
assert_eq!(out, vec![json!(true), json!(true), json!("1.5"), json!("-1"), json!(true), json!(true), json!("Not found"), json!("Not found")]);
}
/// A layer's or group's collection and an artboard read before File › Revert are stale after it,
/// while the document's own collections follow the loaded document.
#[test]
fn scoped_collections_and_artboards_go_stale_after_revert() {
let (mut s, ..) = doc();
let folder = vectorcraft_testkit::TempDir::new("script-dom-revert-scoped");
let path = folder.join("saved.vectorcraft");
s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap();
let held = "var d = app.activeDocument, p = d.layers[0].pageItems, g = d.layers[0].groupItems, ab = d.artboards[0], all = d.groupItems;\
d.pageItems[0].name = 'changed'; vc.run('file.revert');";
for (read, stale) in
[("p.length", "Stale page item"), ("g.length", "Stale page item"), ("ab.name", "Stale artboard"), ("ab.name = 'x'", "Stale artboard")]
{
let source = format!("{held} try {{ {read}; vc.log('ran'); }} catch (e) {{ vc.log(e.message); }}");
assert_eq!(log(&mut s, &source), vec![json!(stale)], "{read}");
}
assert_eq!(log(&mut s, &format!("{held} vc.log(all.length); vc.log(d.artboards[0].name);")), vec![json!(0), json!("Artboard 1")]);
}
#[test]
fn remove_all_refuses_locked_art_before_deleting_anything() {
let (mut s, a, b) = doc();
@@ -2423,6 +2459,24 @@ fn scoped_remove_all_refuses_art_on_a_locked_artboard() {
assert_eq!(out, vec![json!(0)]);
}
/// `removeAll()` on a compound path's `pathItems` deletes its paths and keeps the compound path,
/// empty, as `remove()` on its last path does.
#[test]
fn removing_all_the_paths_of_a_compound_path_keeps_the_compound_path() {
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 compound = layer_order(&s)[0];
let steps = undo_steps(&s);
let out = log(
&mut s,
"var c = app.activeDocument.compoundPathItems[0]; c.pathItems.removeAll(); vc.log([c.typename, c.pathItems.length, app.activeDocument.compoundPathItems.length]);",
);
assert_eq!(out, vec![json!(["CompoundPathItem", 0, 1])]);
assert!(s.active().unwrap().doc.node(compound).is_some_and(|n| n.children().is_some_and(|c| c.is_empty())), "the compound path stays, empty");
assert_eq!(undo_steps(&s), steps + 1);
}
/// `move` leaves art on a locked artboard where it is, and a move that leaves an object where it
/// is runs no command, also in a layer whose ruler guides are above its art.
#[test]
@@ -3315,6 +3369,29 @@ fn node_move_refuses_a_guide_and_a_locked_or_hidden_compound_path() {
assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before);
}
/// `node.move` refuses a clip group's clipping path for a compound path and leaves the group
/// clipped as it was; the art the group clips still goes in.
#[test]
fn node_move_refuses_a_clipping_path_for_a_compound_path() {
let (mut s, a, b) = doc();
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
let g = NodeId(s.execute("object.clippingMask.make", &json!({})).unwrap()["id"].as_u64().unwrap());
s.execute("select.none", &json!({})).unwrap();
let cid = NodeId(s.execute("object.newGroup", &json!({"compound": true})).unwrap()["id"].as_u64().unwrap());
let d = &s.active().unwrap().doc;
assert_eq!(d.position(b).map(|(p, i, _)| (p, i)), Some((Some(g), 0)));
let (before, steps) = (format!("{:?}", d.layers), undo_steps(&s));
let err = s.execute("node.move", &json!({"id": b.0, "parent": cid.0, "index": 0})).unwrap_err().to_string();
assert!(err.contains("clipping path"), "{err}");
assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before);
assert_eq!(undo_steps(&s), steps);
s.execute("node.move", &json!({"id": a.0, "parent": cid.0, "index": 0})).unwrap();
let d = &s.active().unwrap().doc;
assert_eq!(d.parent_of(a), Some(cid));
assert!(d.node(g).unwrap().clips());
assert_eq!(d.position(b).map(|(p, i, _)| (p, i)), Some((Some(g), 0)));
}
/// `duplicate(compoundPath)` puts the copy into the compound path; an empty one takes its paint.
#[test]
fn a_path_duplicated_into_an_empty_compound_path_becomes_its_path() {
@@ -3357,6 +3434,211 @@ fn a_compound_paths_path_items_list_the_topmost_path_first() {
assert_eq!(log(&mut s, source), [json!(30), json!(50)]);
}
/// `index(i)` on a layer's `pageItems` and a compound path's `pathItems` gives the object `[i]`
/// gives, and `Not found` past the end.
#[test]
fn scoped_collections_index_by_number() {
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 d = app.activeDocument, L = d.layers[0].pageItems, P = d.compoundPathItems[0].pathItems;\
vc.log(L.index(0).typename); vc.log(P.index(1).width === P[1].width);",
);
assert_eq!(out, vec![json!("CompoundPathItem"), json!(true)]);
let e = failure(&mut s, "app.activeDocument.compoundPathItems[0].pathItems.index(5);");
assert!(e.contains("Not found"), "{e}");
}
#[test]
fn scoped_collection_methods_reject_the_other_collection_class() {
let (mut s, a, b) = doc();
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
s.execute("object.compoundPath.make", &json!({})).unwrap();
rect(&mut s, 200.0, 20.0, 30.0, 40.0);
let before = s.active().unwrap().doc.clone();
let steps = undo_steps(&s);
for (class, receiver) in
[("PathItems", "app.activeDocument.layers[0].pageItems"), ("PageItems", "app.activeDocument.compoundPathItems[0].pathItems")]
{
for call in ["removeAll.call(r)", "getByName.call(r, '')", "index.call(r, 0)"] {
let source = format!("var r = {receiver}; {class}.prototype.{call};");
let error = failure(&mut s, &source);
assert!(error.contains(&format!("not a {class}")), "{source}: {error}");
assert_eq!(s.active().unwrap().doc, before);
assert_eq!(undo_steps(&s), steps);
}
for property in ["typename", "length", "parent"] {
let source = format!("Object.getOwnPropertyDescriptor({class}.prototype, '{property}').get.call({receiver});");
let error = failure(&mut s, &source);
assert!(error.contains(&format!("not a {class}")), "{source}: {error}");
}
}
assert_eq!(s.active().unwrap().doc, before);
assert_eq!(undo_steps(&s), steps);
}
#[test]
fn clear_releases_a_group_after_removing_its_last_compound_mask_member() {
for mode in ["whole", "anchors", "mixed"] {
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 compound = s.active().unwrap().doc.parent_of(a).unwrap();
s.execute("edit.clear", &json!({"ids": [b.0]})).unwrap();
s.execute("select.set", &json!({"ids": [compound.0]})).unwrap();
let group = NodeId(s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap());
run(&mut s, "app.activeDocument.groupItems[0].clipped = true;").unwrap();
let other = rect(&mut s, 200.0, 20.0, 30.0, 40.0);
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
if mode == "anchors" {
s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 0], [0, 1], [0, 2]]})).unwrap();
} else if mode == "mixed" {
s.execute("select.anchors", &json!({"id": other.0, "anchors": [[0, 0]], "mode": "add"})).unwrap();
}
let before = s.active().unwrap().doc.clone();
let selection = s.active().unwrap().selection.clone();
let steps = undo_steps(&s);
s.execute("edit.clear", &json!({})).unwrap();
let d = &s.active().unwrap().doc;
assert!(d.node(a).is_none() && d.node(compound).is_none(), "{mode}");
assert!(d.node(other).is_some(), "{mode}");
assert!(d.node(group).unwrap().children().unwrap().is_empty(), "{mode}");
assert!(!d.node(group).unwrap().clips(), "{mode}");
assert_eq!(undo_steps(&s), steps + 1, "{mode}");
let after = d.clone();
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(s.active().unwrap().doc, before, "{mode}");
assert_eq!(s.active().unwrap().selection, selection, "{mode}");
s.execute("edit.redo", &json!({})).unwrap();
assert_eq!(s.active().unwrap().doc, after, "{mode}");
}
}
/// Ruler guides left in a clipped layer do not count as other objects: `removeAll()` deletes the
/// layer's clipping compound path.
#[test]
fn scoped_remove_all_deletes_a_clipping_path_beside_ruler_guides() {
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 cid = s.active().unwrap().doc.parent_of(a).unwrap();
let layer = s.active().unwrap().doc.parent_of(cid).unwrap();
s.execute("guide.add", &json!({"vertical": true, "pos": 120})).unwrap();
s.execute("layer.clippingMask.toggle", &json!({"id": layer.0})).unwrap();
run(&mut s, "app.activeDocument.layers[0].compoundPathItems.removeAll();").unwrap();
assert!(s.active().unwrap().doc.node(cid).is_none());
assert!(!s.active().unwrap().doc.node(layer).unwrap().clips());
let added = rect(&mut s, 200.0, 20.0, 30.0, 40.0);
assert_eq!(s.active().unwrap().doc.parent_of(added), Some(layer));
assert!(!s.active().unwrap().doc.node(layer).unwrap().clips());
s.execute("edit.undo", &json!({})).unwrap();
s.execute("edit.undo", &json!({})).unwrap();
assert!(s.active().unwrap().doc.node(cid).is_some());
assert!(s.active().unwrap().doc.node(layer).unwrap().clips());
s.execute("edit.redo", &json!({})).unwrap();
rect(&mut s, 200.0, 20.0, 30.0, 40.0);
assert!(!s.active().unwrap().doc.node(layer).unwrap().clips());
}
#[test]
fn scoped_remove_all_releases_an_empty_clipping_group_in_one_step() {
let (mut s, a, b) = doc();
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
s.execute("object.group", &json!({})).unwrap();
run(&mut s, "app.activeDocument.groupItems[0].clipped = true;").unwrap();
let steps = undo_steps(&s);
let out = log(&mut s, "var g = app.activeDocument.groupItems[0]; g.pageItems.removeAll(); vc.log(g.clipped); vc.log(g.pageItems.length);");
assert_eq!(out, [json!(false), json!(0)]);
assert_eq!(undo_steps(&s), steps + 1);
s.execute("edit.undo", &json!({})).unwrap();
let out = log(&mut s, "var g = app.activeDocument.groupItems[0]; vc.log(g.clipped); vc.log(g.pageItems.length);");
assert_eq!(out, [json!(true), json!(2)]);
}
#[test]
fn clipped_setter_refuses_locked_artboards_layers_and_groups() {
for target in ["artboard", "layer", "group"] {
for clipped in [false, true] {
let (mut s, a, b) = doc();
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
let g = s.execute("object.group", &json!({})).unwrap()["id"].as_u64().unwrap();
if clipped {
run(&mut s, "app.activeDocument.groupItems[0].clipped = true;").unwrap();
}
let layer = s.active().unwrap().doc.layer_containing(NodeId(g)).unwrap();
s.edit("Lock", |d, _| {
match target {
"artboard" => d.artboards[0].locked = true,
"layer" => d.node_mut(layer).unwrap().locked = true,
_ => d.node_mut(NodeId(g)).unwrap().locked = true,
}
Ok(())
})
.unwrap();
let steps = undo_steps(&s);
let src = format!(
"var g = app.activeDocument.groupItems[0]; try {{ g.clipped = {}; vc.log('changed'); }} catch (e) {{ vc.log(e.message); }} vc.log(g.clipped);",
!clipped
);
let out = log(&mut s, &src);
assert!(out[0].as_str().unwrap().contains("locked"), "{target}: {out:?}");
assert_eq!(out[1], json!(clipped));
assert_eq!(undo_steps(&s), steps);
}
}
}
#[test]
fn scoped_collections_convert_to_strings() {
let (mut s, ..) = doc();
let out = log(
&mut s,
"var l = app.activeDocument.layers[0], g = l.groupItems.add(), c = g.compoundPathItems.add();\
var lists = [l.pageItems, g.pageItems, l.layers, l.groupItems, g.groupItems, l.compoundPathItems, g.compoundPathItems, c.pathItems];\
for (var i = 0; i < lists.length; i++) { vc.log(String(lists[i])); vc.log(lists[i].toString()); }",
);
let expected: Vec<_> = ["PageItems", "PageItems", "Layers", "GroupItems", "GroupItems", "CompoundPathItems", "CompoundPathItems", "PathItems"]
.into_iter()
.flat_map(|name| [json!(format!("[{name}]")), json!(format!("[{name}]"))])
.collect();
assert_eq!(out, expected);
}
#[test]
fn layer_color_can_be_assigned_to_path_paint() {
let (mut s, ..) = doc();
let out = log(
&mut s,
"var l = app.activeDocument.layers[0]; l.color = {red: 10, green: 20, blue: 30};\
var c = l.color; vc.log(c.typename); var p = l.pageItems[0]; p.fillColor = c;\
vc.log([p.fillColor.red, p.fillColor.green, p.fillColor.blue]);",
);
assert_eq!(out, [json!("RGBColor"), json!([10, 20, 30])]);
}
/// `removeAll()` refuses to delete the compound path that clips a group while the group keeps
/// other art, and deletes nothing.
#[test]
fn scoped_remove_all_refuses_a_clipping_compound_path() {
let (mut s, a, b) = doc();
let e = rect(&mut s, 200.0, 100.0, 20.0, 20.0);
s.execute("select.set", &json!({"ids": [a.0, b.0]})).unwrap();
s.execute("object.compoundPath.make", &json!({})).unwrap();
s.execute("object.arrange.bringToFront", &json!({})).unwrap();
let cid = s.active().unwrap().doc.parent_of(a).unwrap();
s.execute("select.set", &json!({"ids": [cid.0, e.0]})).unwrap();
s.execute("object.group", &json!({})).unwrap();
run(&mut s, "app.activeDocument.groupItems[0].clipped = true;").unwrap();
let before = format!("{:?}", s.active().unwrap().doc.layers);
let steps = undo_steps(&s);
let err = failure(&mut s, "app.activeDocument.groupItems[0].compoundPathItems.removeAll();");
assert!(err.contains("clipping"), "{err}");
assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before);
assert_eq!(undo_steps(&s), steps);
}
/// A path that leaves a compound path for a layer is drawn as it was: it takes the compound
/// path's paint and pixel alignment, as Release Compound Path gives them.
#[test]
@@ -3426,6 +3708,33 @@ fn a_pixel_aligned_compound_path_snaps_a_path_moved_into_it() {
}
}
/// A path off the pixel grid that moves into a pixel-aligned compound path is snapped to the grid
/// with the compound path's other paths.
#[test]
fn a_path_moved_into_a_pixel_aligned_compound_path_is_snapped() {
let (mut s, a, _) = doc();
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
s.execute("object.compoundPath.make", &json!({})).unwrap();
s.execute("object.setPixelAligned", &json!({"on": true})).unwrap();
s.execute("select.none", &json!({})).unwrap();
let to = s.active().unwrap().doc.parent_of(a).unwrap();
let r = rect(&mut s, 200.3, 100.3, 20.4, 20.4);
s.execute("object.setPixelAligned", &json!({"ids": [r.0], "on": false})).unwrap();
s.execute("select.none", &json!({})).unwrap();
assert!(!s.active().unwrap().doc.node(r).unwrap().extras().pixel_aligned);
let before = s.active().unwrap().doc.bounds_of(&[r], false).unwrap();
assert!(before.x0.fract().abs() > 0.01, "{before:?}");
s.execute("node.move", &json!({"id": r.0, "parent": to.0, "index": 0})).unwrap();
let d = &s.active().unwrap().doc;
assert!(d.node(to).unwrap().extras().pixel_aligned);
let after = d.bounds_of(&[r], false).unwrap();
assert_ne!(after, before);
assert!(!d.node(r).unwrap().extras().pixel_aligned);
assert!([after.x0, after.y0, after.x1, after.y1].iter().all(|v| (v * 2.0).fract().abs() < 1e-9), "not snapped: {after:?}");
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(s.active().unwrap().doc.bounds_of(&[r], false).unwrap(), before);
}
#[test]
fn a_compound_paths_path_items_are_path_items() {
let (mut s, a, b) = doc();
@@ -3434,9 +3743,28 @@ fn a_compound_paths_path_items_are_path_items() {
let out = log(
&mut s,
"var d = app.activeDocument, p = d.compoundPathItems[0].pathItems; vc.log(p.typename); vc.log(p.length);\
vc.log(p[0].typename); vc.log(d.layers[0].pageItems.typename);",
vc.log(p[0].typename); vc.log(d.layers[0].pageItems.typename); vc.log(p instanceof PathItems);\
vc.log(p instanceof PageItems); vc.log(p.parent === d.compoundPathItems[0]);\
p[0].name = 'member'; vc.log(p.getByName('member') === p[0]); vc.log(p.index(0) === p[0]);",
);
assert_eq!(out, [json!("PathItems"), json!(2), json!("PathItem"), json!("PageItems")]);
assert_eq!(
out,
[json!("PathItems"), json!(2), json!("PathItem"), json!("PageItems"), json!(true), json!(false), json!(true), json!(true), json!(true)]
);
// The path creation methods make the new path inside the compound path.
for (made, call) in
["add()", "rectangle(100, 100, 10, 10)", "roundedRectangle(100, 100, 10, 10)", "ellipse(100, 100, 10, 10)", "polygon()", "star()"]
.into_iter()
.enumerate()
{
let source = format!(
"var p = app.activeDocument.compoundPathItems[0].pathItems; try {{ p.{call}; vc.log('made'); }} catch (e) {{ vc.log(e.message); }} vc.log(p.length);"
);
let out = log(&mut s, &source);
assert_eq!(out, [json!("made"), json!(made + 3)], "{call}");
}
run(&mut s, "var c = app.activeDocument.compoundPathItems[0]; c.pathItems.removeAll(); vc.log(c.pathItems.length);").unwrap();
assert!(s.active().unwrap().doc.node(a).is_none() && s.active().unwrap().doc.node(b).is_none());
}
#[test]
@@ -3487,11 +3815,84 @@ fn a_loop_over_groups_and_their_items_lists_each_collection_once() {
for (var i = 0; i < gs.length; i++) { all.push(gs[i]); }\
for (var k = 0; k < all.length; k++) { var p = all[k].pageItems; for (var j = 0; j < p.length; j++) { p[j]; n++; } }\
vc.log(n);";
let (a, b) = (run(&mut s, nested).unwrap(), run(&mut s, in_order).unwrap());
crate::script::dom::ART_SCANS.with(|c| c.set(0));
let a = run(&mut s, nested).unwrap();
// The groups' list and each group's list are built once: 1 + 5 lists.
let scans = crate::script::dom::ART_SCANS.with(std::cell::Cell::get);
assert!(scans <= 6, "{scans} lists built for 5 groups");
let b = run(&mut s, in_order).unwrap();
assert_eq!((a["log"].clone(), b["log"].clone()), (json!([10]), json!([10])));
assert_eq!(a["hostCalls"], b["hostCalls"], "{a}\n{b}");
}
/// A loop over `layers.length` and `layers[i]` lists the layers once while the document is
/// unchanged, so it looks at each layer a bounded number of times.
#[test]
fn a_loop_over_layers_lists_them_once() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
for _ in 0..39 {
s.execute("layer.new", &json!({})).unwrap();
}
let n = s.active().unwrap().doc.layers.len() as u64;
crate::script::dom::LAYER_SCANS.with(|c| c.set(0));
let out = log(&mut s, "var L = app.activeDocument.layers, n = 0; for (var i = 0; i < L.length; i++) { L[i]; n++; } vc.log(n);");
assert_eq!(out, vec![json!(n)]);
let scans = crate::script::dom::LAYER_SCANS.with(std::cell::Cell::get);
assert!(scans <= 2 * n, "{scans} nodes looked at for {n} layers");
}
/// Each `getByName` on a layer's `pageItems` is charged to the host budget like one on the
/// document's `pageItems`, also when the list was already built.
#[test]
fn scoped_name_searches_are_charged_each_time() {
let (mut s, ..) = doc();
let calls = |s: &mut Session, list: &str, k: usize| {
let source = format!("var p = {list}; p.length; for (var i = 0; i < {k}; i++) {{ try {{ p.getByName('none'); }} catch (e) {{}} }}");
run(s, &source).unwrap()["hostCalls"].as_u64().unwrap()
};
let doc_cost = calls(&mut s, "app.activeDocument.pageItems", 6) - calls(&mut s, "app.activeDocument.pageItems", 1);
let layer_cost = calls(&mut s, "app.activeDocument.layers[0].pageItems", 6) - calls(&mut s, "app.activeDocument.layers[0].pageItems", 1);
assert_eq!(layer_cost, doc_cost);
}
#[test]
fn layer_z_order_scans_are_charged_each_time() {
let (mut s, ..) = doc();
let repeated = "var l = app.activeDocument.layers[0]; for (var i = 0; i < 512; i++) l.zOrderPosition;";
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(1 << 16)));
let small = run(&mut s, repeated);
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None));
small.unwrap();
for _ in 0..100 {
s.execute("layer.new", &json!({})).unwrap();
}
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(1 << 16)));
let once = run(&mut s, "var l = app.activeDocument.layers[0]; l.zOrderPosition;");
let large = run(&mut s, repeated);
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None));
once.unwrap();
let error = large.unwrap_err().to_string();
assert!(error.contains("passed more data"), "{error}");
}
#[test]
fn has_selected_artwork_keeps_selected_objects_in_other_layers() {
let (mut s, a, b) = doc();
s.execute("layer.new", &json!({})).unwrap();
let other = rect(&mut s, 220.0, 30.0, 10.0, 10.0);
s.execute("select.set", &json!({"ids": [a.0, other.0]})).unwrap();
for (operation, a_selected, b_selected) in
[("vc.log(l.hasSelectedArtwork)", true, false), ("l.hasSelectedArtwork = false", false, false), ("l.hasSelectedArtwork = true", true, true)]
{
let source = format!("var l = app.activeDocument.layers.getByName('Layer 1'); {operation};");
run(&mut s, &source).unwrap();
assert!(s.active().unwrap().selection.objects.contains(&other), "{operation}");
let selected = &s.active().unwrap().selection.objects;
assert_eq!((selected.contains(&a), selected.contains(&b)), (a_selected, b_selected), "{operation}");
}
}
#[test]
fn layer_lists_follow_edits_between_reads() {
let (mut s, _, _) = doc();
@@ -3530,6 +3931,11 @@ fn new_group_command_checks_its_parent() {
assert!(s.execute("object.newGroup", &json!({"parent": 999_999})).unwrap_err().to_string().contains("no layer or group"));
assert!(s.execute("object.newGroup", &json!({"parent": "x"})).unwrap_err().to_string().contains("parent must be"));
assert!(s.execute("object.newGroup", &json!({"index": -1})).unwrap_err().to_string().contains("index must be"));
let before = format!("{:?}", s.active().unwrap().doc.layers);
assert!(s.execute("object.newGroup", &json!({"parent": null})).unwrap_err().to_string().contains("parent must be"));
assert!(s.execute("object.newGroup", &json!({"index": null})).unwrap_err().to_string().contains("index must be"));
assert!(s.execute("object.newGroup", &json!({"compound": null})).unwrap_err().to_string().contains("compound must be"));
assert_eq!(format!("{:?}", s.active().unwrap().doc.layers), before);
s.execute("layer.setProps", &json!({"id": layer.0, "locked": true})).unwrap();
assert!(s.execute("object.newGroup", &json!({"parent": layer.0})).unwrap_err().to_string().contains("hidden or locked"));
}
@@ -3561,7 +3967,7 @@ fn new_artboards_get_a_name_no_other_artboard_has() {
let out = log(
&mut s,
"var A = app.activeDocument.artboards; A[0].name = 'Artboard 2';\
vc.log(A.add([500, 300, 700, 100]).name); vc.log(A.insert([0, -100, 100, -200], 0).name);\
vc.log(A.add([500, 300, 700, 100]).name); A.insert([0, -100, 100, -200], 0); vc.log(A[0].name);\
vc.log(A.add([800, 300, 900, 100]).name);",
);
assert_eq!(out, [json!("Artboard 3"), json!("Artboard 4"), json!("Artboard 5")]);
@@ -3656,6 +4062,119 @@ fn set_active_artboard_index_is_reported_without_an_undo_step() {
assert!(r.get("activeArtboards").is_none());
}
/// Choosing the artboard that is active only by default keeps that artboard: one inserted before it
/// moves it to the next index, and the report gives that index.
#[test]
fn choosing_the_default_active_artboard_keeps_it_when_one_is_inserted_before() {
let (mut s, _, _) = doc();
assert_eq!(s.active().unwrap().active_artboard, None);
let first = s.active().unwrap().doc.artboards[0].id;
let r = run(
&mut s,
"var A = app.activeDocument.artboards; A.setActiveArtboardIndex(0); A.insert([800, 300, 900, 100], 0);\
vc.log(A.getActiveArtboardIndex());",
)
.unwrap();
assert_eq!(r["log"], json!([1]));
assert_eq!(r["activeArtboards"], json!([{"document": 0, "artboard": 1}]));
assert_eq!(s.active().unwrap().active_artboard, Some(first));
}
/// In a document the run makes, choosing artboard 0 and then inserting one before it still puts
/// the document in the report.
#[test]
fn a_new_documents_chosen_artboard_is_reported_after_an_insert_before_it() {
let (mut s, _, _) = doc();
let r = run(
&mut s,
"var d = app.documents.add(); var A = d.artboards; A.setActiveArtboardIndex(0); A.insert([800, 300, 900, 100], 0);\
vc.log(A.getActiveArtboardIndex());",
)
.unwrap();
assert_eq!(r["log"], json!([1]));
let list = r["activeArtboards"].as_array().cloned().unwrap_or_default();
assert!(list.iter().any(|e| e["artboard"] == json!(1)), "{r}");
}
/// `artboards.insert` gives nothing back; `artboards.add` gives the new artboard.
#[test]
fn artboards_insert_returns_nothing() {
let (mut s, _, _) = doc();
let out = log(
&mut s,
"var A = app.activeDocument.artboards; vc.log(typeof A.insert([0, -100, 100, -200], 0)); vc.log(A.add([500, 300, 700, 100]).typename);",
);
assert_eq!(out, [json!("undefined"), json!("Artboard")]);
}
/// The collections' `index` is described as giving an element, and `toString` of a collection
/// whose container is gone fails as `typename` does.
#[test]
fn collection_index_reflection_and_stale_to_string() {
let (mut s, a, _) = doc();
let out = log(
&mut s,
"var d = app.activeDocument; vc.log([d.layers.reflect.find('index').dataType, d.groupItems.reflect.find('index').dataType,\
d.compoundPathItems.reflect.find('index').dataType, d.artboards.reflect.find('index').dataType]);",
);
assert_eq!(out, [json!(["Layer", "GroupItem", "CompoundPathItem", "Artboard"])]);
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
s.execute("object.group", &json!({})).unwrap();
let live = log(&mut s, "vc.log(app.activeDocument.groupItems[0].groupItems.toString()); vc.log(app.activeDocument.layers[0].layers.toString());");
assert_eq!(live, [json!("[GroupItems]"), json!("[Layers]")]);
let source = "var g = app.activeDocument.groupItems[0]; var c = g.groupItems; g.remove(); c.toString();";
let error = failure(&mut s, source);
assert!(error.contains("Stale page item"), "{error}");
let source = "var l = app.activeDocument.layers.add(); var c = l.layers; l.remove(); c.toString();";
let error = failure(&mut s, source);
assert!(error.contains("Stale layer"), "{error}");
}
/// Setting `hasSelectedArtwork = true` on a layer whose art is all selected runs no command but
/// is still charged for the art it looks at.
#[test]
fn has_selected_artwork_charges_the_walk_when_nothing_is_added() {
// `locked`: the art is locked, so nothing is selectable; otherwise it is all selected.
let repeated = |n: usize, locked: bool| {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
let ids: Vec<u64> = (0..n).map(|i| rect(&mut s, i as f64, 0.0, 1.0, 1.0).0).collect();
if locked {
s.execute("object.setProps", &json!({"ids": ids, "locked": true})).unwrap();
s.execute("select.none", &json!({})).unwrap();
} else {
s.execute("select.set", &json!({"ids": ids})).unwrap();
}
let steps = undo_steps(&s);
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(1 << 13)));
let r = run(&mut s, "var l = app.activeDocument.layers[0]; for (var i = 0; i < 50; i++) l.hasSelectedArtwork = true;");
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None));
assert_eq!(undo_steps(&s), steps);
r
};
for locked in [false, true] {
repeated(1, locked).unwrap();
let error = repeated(200, locked).unwrap_err().to_string();
assert!(error.contains("passed more data"), "{locked}: {error}");
}
// `false` on an empty layer is charged for the selection held in another layer, which stays.
let deselect = |n: usize| {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
let ids: Vec<u64> = (0..n).map(|i| rect(&mut s, i as f64, 0.0, 1.0, 1.0).0).collect();
s.execute("layer.new", &json!({})).unwrap();
s.execute("select.set", &json!({"ids": ids})).unwrap();
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(Some(1 << 13)));
let r = run(&mut s, "var l = app.activeDocument.layers[0]; for (var i = 0; i < 50; i++) l.hasSelectedArtwork = false;");
crate::script::TEST_BRIDGE_BYTES.with(|b| b.set(None));
assert_eq!(s.active().unwrap().selection.objects.len(), n);
r
};
deselect(1).unwrap();
let error = deselect(200).unwrap_err().to_string();
assert!(error.contains("passed more data"), "{error}");
}
#[test]
fn the_report_gives_the_active_artboard_the_run_leaves() {
let (mut s, _, _) = doc();
@@ -3740,6 +4259,21 @@ fn has_selected_artwork_keeps_the_rest_of_the_selection() {
assert_eq!(sel.guides.len(), 1);
}
/// The selection limit counts only the art an assignment would add: a layer with nothing to add
/// changes nothing beside a selection already at the limit, and one with art to add throws.
#[test]
fn has_selected_artwork_checks_the_limit_only_for_art_it_adds() {
let (mut s, a, _) = doc();
run(&mut s, "app.activeDocument.layers.add();").unwrap();
// A selection of 10,001 entries, as the limit counts them.
s.active_mut().unwrap().selection.objects = vec![a; 10_001];
run(&mut s, "var l = app.activeDocument.layers[0]; l.hasSelectedArtwork = true;").unwrap_or_else(|e| panic!("{e}"));
assert_eq!(s.active().unwrap().selection.objects.len(), 10_001);
s.active_mut().unwrap().selection.objects = vec![a; 10_000];
let e = failure(&mut s, "app.activeDocument.layers.getByName('Layer 1').hasSelectedArtwork = true;");
assert!(e.contains("at most 10000"), "{e}");
}
#[test]
fn artboards_stop_at_one_hundred() {
let (mut s, _, _) = doc();
@@ -3758,7 +4292,7 @@ fn every_page_item_has_its_layer_and_members_check_this() {
let out = log(
&mut s,
"var d = app.activeDocument, p = d.pageItems[0], n = d.layers.add(); n.name = 'Up'; p.move(n);\
vc.log(p.layer.name); vc.log(d.pageItems[1].layer.name); vc.log(p.layer.layers.typename);\
vc.log(p.layer.name); vc.log(d.pageItems[d.pageItems.length - 1].layer.name); vc.log(p.layer.layers.typename);\
vc.log(n.pageItems.typename); vc.log(n.groupItems.typename);",
);
assert_eq!(out, [json!("Up"), json!("Layer 1"), json!("Layers"), json!("PageItems"), json!("GroupItems")]);
@@ -3866,13 +4400,13 @@ 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('bringInPerspective'), d.hasOwnProperty('layers'),\
vc.log([p.hasOwnProperty('isIsolated'), p.hasOwnProperty('bringInPerspective'), d.hasOwnProperty('swatches'),\
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')]);",
);
assert_eq!(out[0], json!([true, true, true, true, true, true, true]));
// Members that are not available yet, unknown names and inherited ones are not the object's own.
assert_eq!(out[1], json!([false, false, true, false, false, false]));
assert_eq!(out[1], json!([false, false, false, false, false, false]));
// `for`-`in` lists the properties, not the methods or the members that are not available yet.
assert_eq!(out[2], json!([true, true, -1, -1]));
}
+54 -2
View File
@@ -448,6 +448,55 @@ fn image_matrix_assignment_transforms_the_image() {
let _ = std::fs::remove_dir_all(base);
}
#[test]
fn a_tiny_matrix_change_still_transforms_the_image() {
let base = folder("matrix-tiny");
let g = base.join("main/g.png");
std::fs::write(&g, gray_png(10, 20)).unwrap();
let mut s = session();
let id = place(&mut s, &g, false);
let before = undo_steps(&s);
let tx = |s: &Session| match &s.active().unwrap().doc.node(id).unwrap().kind {
NodeKind::Image(im) => im.xf.as_coeffs()[4],
_ => panic!("not an image"),
};
let old = tx(&s);
log(&mut s, &base, "var r = app.activeDocument.rasterItems[0], m = r.matrix; m.mValueTX = m.mValueTX + 5e-10; r.matrix = m;");
assert_eq!(undo_steps(&s), before + 1);
assert!(tx(&s) != old, "the image did not move");
let _ = std::fs::remove_dir_all(base);
}
#[test]
fn a_stale_placed_item_is_not_a_relative_object() {
let base = folder("stale-relative");
let a = base.join("main/a.png");
std::fs::write(&a, gray_png(4, 4)).unwrap();
let mut s = session();
place(&mut s, &a, true);
place(&mut s, &a, true);
place(&mut s, &a, true);
let out = log(
&mut s,
&base,
&format!(
"var d = app.activeDocument, p = d.placedItems[0], q = d.placedItems[1], r = d.placedItems[2], m = [];\
r.move(q, ElementPlacement.PLACEBEFORE); m.push('live');\
var n = d.placedItems.add(); n.file = new File('{}'); r.move(n, ElementPlacement.PLACEAFTER); m.push('added');\
p.embed();\
try {{ r.move(p, ElementPlacement.PLACEBEFORE); }} catch (e) {{ m.push(e.message); }}\
try {{ r.duplicate(p, ElementPlacement.PLACEAFTER); }} catch (e) {{ m.push(e.message); }}\
n.embed();\
try {{ r.move(n, ElementPlacement.PLACEBEFORE); }} catch (e) {{ m.push(e.message); }}\
try {{ r.duplicate(n, ElementPlacement.PLACEAFTER); }} catch (e) {{ m.push(e.message); }}\
vc.log(m);",
js_path(&a)
),
);
assert_eq!(out, vec![json!(["live", "added", "Stale page item", "Stale page item", "Stale page item", "Stale page item"])]);
let _ = std::fs::remove_dir_all(base);
}
#[test]
fn image_matrix_refuses_bad_values_without_changing_the_image() {
let base = folder("matrix-bad");
@@ -599,16 +648,19 @@ fn stale_and_foreign_placed_items_are_refused() {
std::fs::write(&a, gray_png(4, 4)).unwrap();
let mut s = session();
let id = place(&mut s, &a, true);
place(&mut s, &a, false);
let out = log(
&mut s,
&base,
"var p = app.activeDocument.placedItems[0], m = []; p.remove();\
try { p.relink(null); } catch (e) { m.push(e.message); }\
try { app.activeDocument.placedItems.add().file; RasterItem.prototype.embedded.call(1); } catch (e) { m.push(e.name); }\
var g = Object.getOwnPropertyDescriptor(RasterItem.prototype, 'embedded').get;\
try { g.call(1); } catch (e) { m.push(e.name); }\
m.push(g.call(app.activeDocument.rasterItems[0]));\
try { PlacedItem.prototype.embed.call(app.activeDocument); } catch (e) { m.push(e.message); }\
vc.log(m);",
);
assert_eq!(out, vec![json!(["Stale page item", "TypeError", "this is not a PlacedItem"])]);
assert_eq!(out, vec![json!(["Stale page item", "TypeError", true, "this is not a PlacedItem"])]);
assert!(s.active().unwrap().doc.node(id).is_none());
let _ = std::fs::remove_dir_all(base);
}
+69 -2
View File
@@ -163,7 +163,7 @@ fn no_to_the_confirm_or_stop_leaves_the_warning_on() {
#[test]
fn the_confirm_cannot_be_skipped() {
let mut s = Session::new();
framed(&mut s, &format!("try {{ app.userInteractionLevel = 'DONTDISPLAYALERTS'; }} catch (e) {{}} {ASK_OFF}"));
framed(&mut s, &format!("app.userInteractionLevel = UserInteractionLevel.DONTDISPLAYALERTS; {ASK_OFF}"));
assert_eq!(s.script_dialog().map(|d| d.message), Some(WARNING_OFF_QUESTION.to_string()));
assert!(s.script_answer(DialogAnswer::Confirm(false)));
assert!(pump(&mut s).unwrap().is_ok());
@@ -349,7 +349,7 @@ fn a_run_merges_its_keys_with_keys_the_app_changed_meanwhile() {
assert!(s.script_running());
s.prefs.script_preferences.insert("theirs".into(), ScriptPreference::Boolean(true));
s.prefs.script_preferences.insert("kept".into(), ScriptPreference::Integer(3));
while s.script_pump().is_none() {}
pump(&mut s).unwrap().unwrap();
let keys: Vec<(&str, &ScriptPreference)> = s.prefs.script_preferences.iter().map(|(k, v)| (k.as_str(), v)).collect();
assert_eq!(
keys,
@@ -386,6 +386,26 @@ fn matrix_functions_give_new_records() {
assert_eq!(r, vec![json!([c, sn, -sn, c])]);
}
#[test]
fn reflect_reports_the_matrix_argument_defaults() {
let mut s = Session::new();
let out = log(
&mut s,
"function d(f, a) { return String(app.reflect.find(f).arguments[a].defaultValue); }\
vc.log([d('getScaleMatrix', 'scaleX'), d('concatenateScaleMatrix', 'scaleX'), d('getTranslationMatrix', 'deltaX'),\
d('concatenateTranslationMatrix', 'deltaY'), d('getRotationMatrix', 'angle'), d('concatenateRotationMatrix', 'angle'),\
d('getScaleMatrix', 'scaleY'), d('concatenateMatrix', 'matrix')]);\
vc.log(app.reflect.find('getScaleMatrix').arguments.scaleY.description);",
);
assert_eq!(
out,
vec![
json!(["100", "100", "0", "0", "0", "0", "undefined", "undefined"]),
json!("The vertical scale; when it is left out, the horizontal scale."),
]
);
}
#[test]
fn concatenation_applies_the_first_matrix_first() {
let mut s = Session::new();
@@ -526,6 +546,53 @@ fn a_turn_just_short_of_a_negative_quarter_turn_is_not_rounded_to_it() {
assert_eq!(out, vec![json!(true), json!(-1), json!([0, -1, 1, 0]), json!([-1, 0, 0, -1]), json!([0, -1, 1, 0])]);
}
#[test]
fn an_inverse_translation_next_to_the_overflow_midpoint_rounds_once() {
let mut s = Session::new();
// The x-translation's numerator is MAX + 2^970, the overflow midpoint. With b = 2^-53 the
// determinant is 1 + 2^-53, so the exact quotient is MAX - 2^970 + about 2^917, which rounds
// to MAX, while the rounded determinant 1 gives infinity. With b = 0 the quotient is the
// midpoint itself, which rounds to infinity. With a = 1 + 2^-51 and the numerator
// 2^1024 + 3·2^971, the rounded quotient overflows while the exact one is MAX - 2^971 and a
// little more, which rounds to the number below MAX. With b = -2^-54 and ty = -2^969 the rounded
// quotient is MAX, while the exact one is past the overflow midpoint.
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 i = app.invertMatrix(mat([1, Math.pow(2, -53), -1, 1, -Number.MAX_VALUE, -Math.pow(2, 970)]));\
vc.log(i.mValueTX === Number.MAX_VALUE);\
try { app.invertMatrix(mat([1, 0, -1, 1, -Number.MAX_VALUE, -Math.pow(2, 970)])); vc.log('finite'); }\
catch (e) { vc.log(e.name); }\
var j = app.invertMatrix(mat([1 + Math.pow(2, -51), Math.pow(2, -53), -1, 1, -Math.pow(2, 1023), -(Math.pow(2, 1023) + 3 * Math.pow(2, 971))]));\
vc.log(j.mValueTX === Number.MAX_VALUE - Math.pow(2, 971));\
try { app.invertMatrix(mat([1, -Math.pow(2, -54), -1, 1, -Number.MAX_VALUE, -Math.pow(2, 969)])); vc.log('finite'); }\
catch (e) { vc.log(e.name); }",
);
assert_eq!(out, vec![json!(true), json!("RangeError"), json!(true), json!("RangeError")]);
}
#[test]
fn an_inverse_translation_next_to_half_the_smallest_number_rounds_once() {
let mut s = Session::new();
// The x-translation's numerator is 2^-1021 + 2^-1075 and the determinant 2^54, so the exact
// quotient is 2^-1075 + 2^-1129, just past half the smallest number, which rounds to it. The
// rounded numerator 2^-1021 gives 2^-1075, which rounds to 0. With c = 0 the quotient is 2^-1075
// itself, which rounds to 0. With both translations negated, the x-translation rounds to minus
// the smallest number.
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 t = Math.pow(2, -1021), big = Math.pow(2, 54), small = Math.pow(2, -54);\
var i = app.invertMatrix(mat([big, 0, small, 1, -t, t]));\
vc.log([i.mValueTX === Number.MIN_VALUE, i.mValueTY === -t]);\
var j = app.invertMatrix(mat([big, 0, 0, 1, -t, t]));\
vc.log([j.mValueTX, 1 / j.mValueTX > 0]);\
var k = app.invertMatrix(mat([big, 0, small, 1, t, -t]));\
vc.log([k.mValueTX === -Number.MIN_VALUE, k.mValueTY === t]);",
);
assert_eq!(out, vec![json!([true, true]), json!([0, true]), json!([true, true])]);
}
#[test]
fn inverse_singular_and_equal_matrices() {
let mut s = Session::new();
@@ -98,9 +98,9 @@ const INSIDE: &[(&str, &str)] = &[
"",
"activeDocument activeDocument= app Application Artboard Artboards BlendModes CompoundPathItem CompoundPathItems \
CoordinateSystem Document DocumentArtboardLayout DocumentColorSpace DocumentPreset DocumentPresetType \
DocumentPreviewMode DocumentRasterResolution DocumentTransparencyGrid documents Documents ElementPlacement GroupItem \
GroupItems Layer Layers PageItem PageItems PathItem PathItems PathPoint PathPointSelection PathPoints PlacedItem \
PlacedItems PluginItem PointType PolarityValues Preferences RasterItem RasterItems RulerUnits ScreenMode selection \
DocumentPreviewMode DocumentRasterResolution DocumentTransparencyGrid documents Documents ElementPlacement \
GroupItem GroupItems Layer Layers PageItem PageItems PathItem PathItems PathPoint PathPointSelection PathPoints \
PlacedItem PlacedItems PluginItem PointType PolarityValues Preferences RasterItem RasterItems RulerUnits ScreenMode selection \
selection= StrokeCap StrokeJoin Tag Tags TracingObject TracingOptions Transformation View Views ZOrderMethod",
),
("Application.", "prototype"),
@@ -559,8 +559,8 @@ const INSIDE: &[(&str, &str)] = &[
/// The classes the host adds with nothing but a prototype and its constructor: the page item types
/// that have no members of their own, the color classes, and the save and export option classes.
const BARE_CLASSES: &str = "BlendItem CMYKColor EnvelopeItem GradientColor GraphItem GrayColor IntertwineItem LabColor \
MeshItem NoColor PatternColor PlacedDocumentItem RGBColor RepeatItem SpotColor SymbolItem cmykColor EPSSaveOptions \
ExportOptionsAutoCAD ExportOptionsJPEG ExportOptionsPNG24 ExportOptionsSVG IllustratorSaveOptions PDFSaveOptions";
MeshItem NoColor PatternColor PlacedDocumentItem RGBColor RepeatItem SpotColor SymbolItem cmykColor \
EPSSaveOptions ExportOptionsAutoCAD ExportOptionsJPEG ExportOptionsPNG24 ExportOptionsSVG IllustratorSaveOptions PDFSaveOptions";
/// The name the checker does not read, which also stands for its members: `vc` is VectorCraft's
/// own API, and what `vc.run` does depends on the command it runs.
+9
View File
@@ -1022,6 +1022,15 @@ fn a_host_class_constructor_called_with_new_cannot_wait() {
assert_eq!(could.get(), Some(false));
}
#[test]
fn a_host_class_constructor_called_with_new_cannot_give_a_primitive() {
let mut r = realm(1_000_000);
let make: HostFunction = Rc::new(|_| Ok(Data::Number(7.0)));
with_thing(&mut r, Some(make));
r.start("var r; try { r = new Thing(); } catch (e) { r = e instanceof TypeError; } r").unwrap();
assert_eq!(finish(&mut r, 1_000).0.unwrap(), JsValue::Bool(true));
}
#[test]
fn new_on_a_host_constructor_that_gives_a_value_other_than_an_object_throws() {
let mut r = realm(1_000_000);
+1 -1
View File
@@ -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; 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}",
"{} 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), paper? (the printer driver's paper keyword, such as Letter or CR80: the queue is asked for that paper as the job's media on macOS and Linux; on Windows, with file output, with directPdf, or anything but a keyword it is an error; the Print dialog sends the driver's keyword for the Size chosen), 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",
+46 -5
View File
@@ -583,19 +583,24 @@ fn more_settings_rows(ui: &mut egui::Ui, s: &mut DocSettings, lengths: LengthUni
let shown = f64::from(shown_columns(s));
let field = NumberField::new(columns.clone(), Bind::given(Some(shown))).range(1.0..=n).step(1.0).commit_decimals(0).enabled(several && grid);
if let Some(v) = field.show(ui).edit.events.committed().copied().flatten().filter(|v| v.is_finite()) {
// A column count replaces a preset's rows.
s.columns = v.round().clamp(1.0, n) as u32;
s.rows = 0;
set_columns(s, v.round().clamp(1.0, n) as u32);
}
});
}
/// The columns More Settings shows: for a grid by column made with `file.new`'s `rows`, the columns
/// those rows give the current number of artboards, as `file.new` lays them out; otherwise the
/// stored count. At most one for each artboard.
/// stored count, where a stored 0 shows the columns `file.new` lays out for the layout. At most
/// one for each artboard.
fn shown_columns(s: &DocSettings) -> u32 {
let n = s.artboards.max(1);
if s.layout == ArtboardLayout::GridByColumn && s.rows > 0 { u32::try_from(s.grid_columns()).unwrap_or(n) } else { s.columns.max(1).min(n) }
if s.layout == ArtboardLayout::GridByColumn && s.rows > 0 {
u32::try_from(s.grid_columns()).unwrap_or(n)
} else if s.columns == 0 {
u32::try_from(s.grid_columns()).unwrap_or(n).clamp(1, n)
} else {
s.columns.min(n)
}
}
/// Chooses a layout in More Settings. Another layout replaces a preset's rows and keeps the column
@@ -611,6 +616,15 @@ fn choose_layout(s: &mut DocSettings, l: ArtboardLayout) {
s.layout = l;
}
/// A column count entered in More Settings replaces the rows of a preset made with `file.new`'s
/// `rows`; the same count as shown changes nothing.
fn set_columns(s: &mut DocSettings, columns: u32) {
if columns != shown_columns(s) {
s.columns = columns;
s.rows = 0;
}
}
/// Manage Profiles' pop-up: a row per New Document profile with Edit, which opens the profile as a
/// document, and Reset, which brings back the shipped profile. The button pressed is put in `action`.
fn manage_profiles(ui: &mut egui::Ui, setup: &Setup, action: &mut Option<String>) {
@@ -1332,6 +1346,33 @@ mod tests {
assert!(app.session.documents().is_empty(), "no document was made");
}
/// A new column count replaces a preset's rows; the count already shown changes nothing.
#[test]
fn a_new_column_count_replaces_a_presets_rows() {
let rows = DocSettings { artboards: 9, layout: ArtboardLayout::GridByColumn, columns: 2, rows: 4, ..DocSettings::default() };
let mut s = rows.clone();
set_columns(&mut s, 3);
assert_eq!(s, rows, "3 is what the rows show");
set_columns(&mut s, 2);
assert_eq!((s.layout, s.columns, s.rows), (ArtboardLayout::GridByColumn, 2, 0));
assert_eq!(s.grid_columns(), 2);
}
/// A stored column count of 0 shows the one row of all the artboards that `file.new` lays out, so
/// entering 1 is stored and the same count as the row changes nothing.
#[test]
fn a_column_count_without_rows_is_stored() {
let mut s = DocSettings { artboards: 4, layout: ArtboardLayout::GridByRow, columns: 0, rows: 0, ..DocSettings::default() };
assert_eq!(shown_columns(&s), u32::try_from(s.grid_columns()).unwrap_or(0));
set_columns(&mut s, 4);
assert_eq!((s.columns, s.rows), (0, 0), "4 is what the row shows");
set_columns(&mut s, 1);
assert_eq!((s.columns, s.rows), (1, 0));
assert_eq!(s.grid_columns(), 1);
let column = DocSettings { artboards: 4, layout: ArtboardLayout::Column, columns: 0, rows: 0, ..DocSettings::default() };
assert_eq!(shown_columns(&column), 1, "the Column layout is one column");
}
/// The preset keeps the artboard layout, spacing and columns More Settings set (#4893); an empty
/// name is refused.
#[test]
+26 -8
View File
@@ -219,6 +219,17 @@ fn printer_paper<'a>(fields: &DialogFields, papers: &'a [Paper]) -> Option<&'a P
papers.iter().find(|p| p.key == key)
}
/// The driver's keyword for the paper the Size row names, for the job to ask the queue for: the printer's own paper
/// (`printer:CR80`), or the driver's paper of the size of one of the dialog's own papers (`letter` on a driver that lists
/// `Letter`). `None` when the driver lists no such paper, or names it with characters a keyword can't hold.
fn driver_paper_key<'a>(fields: &DialogFields, papers: &'a [Paper]) -> Option<&'a str> {
let paper = printer_paper(fields, papers).or_else(|| {
let own = Media::from_name(fields.text("media")?).filter(|m| *m != Media::Custom)?;
papers.iter().find(|p| own_media_of(p) == Some(own))
})?;
crate::print::is_paper_keyword(&paper.key).then_some(paper.key.as_str())
}
/// Whether two papers have the same Width and Height, to within half a point.
fn same_size(a: &Paper, b: &Paper) -> bool {
(a.width - b.width).abs() <= 0.5 && (a.height - b.height).abs() <= 0.5
@@ -575,15 +586,16 @@ fn serve(app: &mut VectorcraftApp, ctx: &egui::Context, dialogs: &WindowDialogs,
// The paper chosen from the previous list, read before the list is replaced.
let chosen = on(dialogs, |p| printer_paper(p.fields(), &open.papers.1).cloned()).flatten();
if printer_changed || open.papers_pending {
let (papers, pending) = papers_of(app, open.mode, &d.printer, printer_changed);
// The held answer still names a paper from the previous list.
if let Some(answer) = &mut d.ok
&& let Some(paper) = printer_paper(&answer.fields, &open.papers.1)
&& (pending || !printer_paper(&answer.fields, &papers).is_some_and(|new| same_size(paper, new)))
{
answer.fields.set("width", paper.width);
answer.fields.set("height", paper.height);
answer.fields.set("media", Media::Custom.id());
}
let (papers, pending) = papers_of(app, open.mode, &d.printer, printer_changed);
// While the new printer's lookup runs, the Size list keeps the sizes before it, so the paper chosen keeps its
// name and size until the driver answers.
papers_changed = !pending;
@@ -759,7 +771,7 @@ fn serve(app: &mut VectorcraftApp, ctx: &egui::Context, dialogs: &WindowDialogs,
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)));
on(dialogs, |p| p.answer_ok(result.map_err(|e| crate::i18n::message(crate::i18n::current(), &e).into())));
}
true
}
@@ -824,17 +836,23 @@ fn accept(app: &mut VectorcraftApp, open: &Open, answer: &PrintAnswer, name: &st
if open.mode == PrintMode::PresetEditor {
return save_preset(app, open, name, settings);
}
let (printer, to_file) = match &answer.settings.destination {
Destination::Printer(name) if name != PDF_FILE => (name.as_str(), false),
_ => ("", true),
};
let direct_pdf = answer.fields.bool("directPdf").unwrap_or(false);
let applies_paper = !to_file && !direct_pdf && app.services.print.as_ref().is_some_and(|s| s.applies_paper());
if matches!(answer.finish, PrintFinish::Print) && applies_paper && (open.papers_pending || open.papers.0 != printer) {
return Err("The printer's paper sizes are still loading; try Print again in a moment.".into());
}
// Laid out first, so a bad range or overlap is refused before anything is kept.
app.session.execute("print.preview", &json!({ "settings": settings })).map_err(|e| e.to_string())?;
app.run("print.setup", json!({ "settings": settings }))?;
match answer.finish {
PrintFinish::Print => {
let (printer, to_file) = match &answer.settings.destination {
Destination::Printer(name) if name != PDF_FILE => (name.as_str(), false),
_ => ("", true),
};
let direct_pdf = answer.fields.bool("directPdf").unwrap_or(false);
crate::print::run(app, &json!({ "settings": settings, "printer": printer, "toFile": to_file, "directPdf": direct_pdf })).map(|_| ())
let paper = if applies_paper { driver_paper_key(&answer.fields, &open.papers.1) } else { None };
let job = json!({ "settings": settings, "printer": printer, "toFile": to_file, "directPdf": direct_pdf, "paper": paper });
crate::print::run(app, &job).map(|_| ())
}
// Done only keeps the settings.
_ => Ok(()),
+207
View File
@@ -650,6 +650,107 @@ fn windows_paper_sizes_are_read_in_hundredths_of_an_inch() {
assert_eq!((got[3].0, got[3].1), ("256", "256"), "no name: the number");
}
#[test]
fn a_queue_without_a_ppd_lists_the_paper_sizes_lpoptions_reports() {
let out = "ColorModel/Color Mode: Gray *RGB\n\
PageSize/Media Size: *Letter A4 Legal na_index-4x6_4x6in iso_a5_148x210mm B5 ISOB4 Custom.WIDTHxHEIGHT Unknown Letter\r\n\
media/Media: om_cr80_54x85.6mm tiny_1x1mm\n\
InputSlot/Source: *Auto Tray1\n";
let papers = crate::print::lpoptions_papers(out);
let got: Vec<(&str, i64, i64)> = papers.iter().map(|p| (p.key.as_str(), p.width.round() as i64, p.height.round() as i64)).collect();
// The custom size, the keyword of unknown size, the repeated Letter and a size below 72 pt are left out.
assert_eq!(
got,
[
("Letter", 612, 792),
("A4", 595, 842),
("Legal", 612, 1008),
("na_index-4x6_4x6in", 288, 432),
("iso_a5_148x210mm", 420, 595),
// CUPS names the JIS B sizes B4 and B5, and the ISO ones ISOB4 and ISOB5.
("B5", 516, 729),
("ISOB4", 709, 1001),
("om_cr80_54x85.6mm", 153, 243)
]
);
assert!(crate::print::lpoptions_papers("PageSize: \nbroken\nInputSlot: *A4\n").is_empty());
}
#[test]
fn a_queue_without_any_ppd_lists_the_media_its_ipp_attributes_report() {
let out = "\"get-printer-attributes.test\":\n\
\x20 media-default (keyword) = na_letter_8.5x11in\n\
\x20 media-supported (1setOf keyword) = na_letter_8.5x11in,iso_a4_210x297mm,custom_min_1x1in,oe_photo-l_3.5x5in,na_letter_8.5x11in\r\n\
\x20 media-ready (1setOf keyword) = iso_a5_148x210mm\n";
let papers = crate::print::ipp_papers(out);
let got: Vec<(&str, i64, i64)> = papers.iter().map(|p| (p.key.as_str(), p.width.round() as i64, p.height.round() as i64)).collect();
// Only media-supported counts; the custom range and the repeated Letter are left out.
assert_eq!(got, [("na_letter_8.5x11in", 612, 792), ("iso_a4_210x297mm", 595, 842), ("oe_photo-l_3.5x5in", 252, 360)]);
assert!(crate::print::ipp_papers("media-supported (1setOf keyword) = \n").is_empty());
}
#[test]
fn the_ipp_lookup_asks_the_scheduler_cups_uses_for_the_queue() {
use crate::print::ipp_queue_uri;
assert_eq!(ipp_queue_uri(None, None, "Office+Color").as_deref(), Some("ipp://localhost/printers/Office%2BColor"));
assert_eq!(ipp_queue_uri(Some(" "), None, "Lab").as_deref(), Some("ipp://localhost/printers/Lab"));
assert_eq!(ipp_queue_uri(Some("print.example.com:631/version=1.1"), None, "Lab").as_deref(), Some("ipp://print.example.com:631/printers/Lab"));
assert_eq!(ipp_queue_uri(Some("/run/cups/cups.sock"), None, "Lab"), None, "a domain socket has no URI");
assert_eq!(ipp_queue_uri(None, None, ""), None);
}
#[test]
fn the_ipp_lookup_uses_ipp_port_for_a_server_without_a_port() {
use crate::print::{ipp_port, ipp_queue_uri};
assert_eq!(ipp_queue_uri(Some("print.example.com"), Some(8631), "Lab").as_deref(), Some("ipp://print.example.com:8631/printers/Lab"));
assert_eq!(
ipp_queue_uri(None, Some(8631), "Lab").as_deref(),
Some("ipp://localhost/printers/Lab"),
"with no server named, CUPS uses its domain socket, not IPP_PORT"
);
assert_eq!(
ipp_queue_uri(Some("print.example.com:631"), Some(8631), "Lab").as_deref(),
Some("ipp://print.example.com:631/printers/Lab"),
"a port in the server name wins"
);
assert_eq!(ipp_queue_uri(Some("[::1]"), Some(8631), "Lab").as_deref(), Some("ipp://[::1]:8631/printers/Lab"));
assert_eq!(ipp_queue_uri(Some("[::1]:632"), Some(8631), "Lab").as_deref(), Some("ipp://[::1]:632/printers/Lab"));
assert_eq!(ipp_port(Some("8631")), Some(8631));
for invalid in [None, Some(""), Some("0"), Some("70000"), Some("ipp")] {
assert_eq!(ipp_port(invalid), None, "{invalid:?}");
}
assert_eq!(ipp_queue_uri(Some("print.example.com"), ipp_port(Some("x")), "Lab").as_deref(), Some("ipp://print.example.com/printers/Lab"));
}
/// What the paper-keyword service was asked to print on: each job's paper.
type SentPapers = Rc<RefCell<Vec<Option<String>>>>;
/// One printer, Card, whose driver lists US Letter and a CR80 card, and which keeps each job's paper keyword.
struct KeywordPrint(SentPapers, bool);
impl PrintService for KeywordPrint {
fn applies_paper(&self) -> bool {
self.1
}
fn printers(&mut self) -> Vec<Printer> {
vec![Printer::new("Card").is_default(true), Printer::new("Slow")]
}
fn print(&mut self, job: &PrintJob) -> Result<String, String> {
self.0.borrow_mut().push(job.paper.map(str::to_string));
Ok("Sent".into())
}
fn papers(&mut self, printer: &str, _fresh: bool) -> Papers {
if printer == "Slow" {
return Papers::Pending;
}
let paper = |key: &str, label: &str, width, height| crate::print::Paper { key: key.into(), label: label.into(), width, height };
Papers::Ready(vec![paper("Letter", "US Letter", 612.0, 792.0), paper("CR80", "CR80 Card", 153.0, 243.0)])
}
}
#[test]
fn windows_paper_sizes_that_share_a_name_are_all_listed() {
// A driver form whose name looks like a size suffix is a size of its own.
@@ -684,6 +785,77 @@ impl PrintService for WindowsForms {
}
}
#[test]
fn the_job_asks_the_queue_for_the_driver_paper_chosen() {
let sent = SentPapers::default();
let services = Services { print: Some(Box::new(KeywordPrint(sent.clone(), true))), ..Default::default() };
let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), services));
app.run("file.new", json!({"width": 120, "height": 90})).unwrap();
for (media, keyword) in [("printer:CR80", Some("CR80")), ("letter", Some("Letter")), ("custom", None)] {
app.run("file.print", json!({})).unwrap();
pump(&mut app);
set(&mut app, "media", json!(media));
pump(&mut app);
confirm(&mut app);
assert!(!is_open(&app));
assert_eq!(sent.borrow().last().cloned().flatten().as_deref(), keyword, "{media}");
}
assert_eq!(sent.borrow().len(), 3);
// Printing to Slow is refused while its paper sizes are still loading.
app.run("file.print", json!({})).unwrap();
pump(&mut app);
set(&mut app, "media", json!("letter"));
set(&mut app, "printer", json!("Slow"));
pump(&mut app);
confirm(&mut app);
assert!(is_open(&app));
assert_eq!(sent.borrow().len(), 3);
call(&mut app, "ui.dialog.cancel", json!({}));
// Without the dialog, the keyword is given as `paper`, and anything else is refused before printing.
app.run("file.print", json!({"printer": "Card", "paper": "iso_a4_210x297mm"})).unwrap();
assert_eq!(sent.borrow().last().cloned().flatten().as_deref(), Some("iso_a4_210x297mm"));
for bad in [json!("US Letter"), json!(""), json!("a=b"), json!("Letter,Tray1"), json!("Let'ter"), json!("Let\\ter"), json!(4)] {
assert!(app.run("file.print", json!({"printer": "Card", "paper": bad})).is_err(), "{bad}");
}
assert!(app.run("file.print", json!({"toFile": true, "paper": "Letter"})).is_err());
assert_eq!(sent.borrow().len(), 4, "no refused job was sent");
}
#[test]
fn a_job_without_a_paper_keyword_prints_while_the_paper_lookup_is_pending() {
let sent = SentPapers::default();
let services = Services { print: Some(Box::new(KeywordPrint(sent.clone(), false))), ..Default::default() };
let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), services));
app.run("file.new", json!({"width": 120, "height": 90})).unwrap();
app.run("file.print", json!({})).unwrap();
pump(&mut app);
set(&mut app, "printer", json!("Slow"));
pump(&mut app);
confirm(&mut app);
assert!(!is_open(&app));
assert_eq!(*sent.borrow(), [None]);
}
struct PendingKeywordPrint(Rc<Cell<bool>>, SentPapers);
impl PrintService for PendingKeywordPrint {
fn printers(&mut self) -> Vec<Printer> {
PendingTwin(self.0.clone()).printers()
}
fn print(&mut self, job: &PrintJob) -> Result<String, String> {
KeywordPrint(self.1.clone(), true).print(job)
}
fn applies_paper(&self) -> bool {
true
}
fn papers(&mut self, printer: &str, fresh: bool) -> Papers {
PendingTwin(self.0.clone()).papers(printer, fresh)
}
}
#[test]
fn distinct_windows_sizes_matching_one_built_in_size_are_selectable() {
let out = "11\tA5\t582\t827\n11\tA5\t583\t827\n";
@@ -706,6 +878,41 @@ fn distinct_windows_sizes_matching_one_built_in_size_are_selectable() {
}
}
#[test]
fn a_held_print_keeps_the_paper_keyword_when_the_lookup_finishes() {
let ready = Rc::new(Cell::new(false));
let sent = SentPapers::default();
let services = Services { print: Some(Box::new(PendingKeywordPrint(ready.clone(), sent.clone()))), ..Default::default() };
let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), services));
app.run("file.new", json!({"width": 120, "height": 90})).unwrap();
app.run("file.print", json!({})).unwrap();
pump(&mut app);
set(&mut app, "media", json!("printer:CR80"));
pump(&mut app);
set(&mut app, "printer", json!("Twin"));
pump(&mut app);
let ctx = ctx(&app);
let (id, _) = top(&app).expect("the print dialog is open");
let _ = app.dialogs().expect("a window host").with(|host| host.confirm_by_id(&ctx, id));
ready.set(true);
pump(&mut app);
pump(&mut app);
assert!(!is_open(&app));
assert_eq!(*sent.borrow(), [Some("CR80".to_string())]);
}
#[test]
fn an_explicit_paper_is_refused_when_the_print_path_cannot_apply_it() {
let (mut app, jobs) = app();
assert!(app.run("file.print", json!({"paper": "Letter"})).is_err());
assert!(jobs.borrow().is_empty());
let sent = SentPapers::default();
app.services.print = Some(Box::new(KeywordPrint(sent.clone(), true)));
assert!(app.run("file.print", json!({"paper": "Letter", "directPdf": true})).is_err());
assert!(sent.borrow().is_empty());
}
#[test]
fn windows_forms_stay_selected_when_queue_enumeration_order_changes() {
for out in ["256\tCustom\t400\t600\n256\tCustom\t500\t700\n", "11\tA5\t582\t827\n11\tA5\t583\t827\n"] {
+1 -1
View File
@@ -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; 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}",
"{} 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), paper? (the printer driver's paper keyword, such as Letter or CR80: the queue is asked for that paper as the job's media on macOS and Linux; on Windows, with file output, with directPdf, or anything but a keyword it is an error; the Print dialog sends the driver's keyword for the Size chosen), 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",
@@ -172,6 +172,8 @@ pub(crate) fn after_journaled_edit(app: &mut VectorcraftApp) -> bool {
Ok(()) => false,
Err(e) => {
app.status(e);
// The limit is named once: the notes of the edit's Copy or Cut do not replace it.
app.clipboard_publishing.keep_status(&app.ui);
true
}
}
@@ -295,6 +295,35 @@ fn script_run_checks_recording_step_limit_on_completion() {
}
}
/// A script that copies type in a family that is not installed, whose Copy's formats therefore
/// have notes, and whose commands take a recording past 10,000 steps: the status bar keeps naming
/// the limit once the formats are written. Without the recording the notes show.
#[test]
fn a_scripts_copy_notes_do_not_replace_the_recording_limit() {
let steps = "the action already has 10,000 steps";
let copy = "var t = vc.run('text.create', {x: 5, y: 20, text: 'Ab', font: 'Nonexistent Sans Probe'});\
vc.run('select.set', {ids: [t.id]}); app.copy();";
for frames in [false, true] {
for recording in [true, false] {
let services = crate::tests::sysclip::fake_clipboard_services();
let app = crate::testing::windowed(VectorcraftApp::new(vectorcraft_engine::Session::new(), services));
let (mut app, _) = three_moves_in(app);
if recording {
recording_with(&mut app, files::MAX_ACTION_STEPS - 1);
}
app.ui.status.clear();
run_script(&mut app, copy, frames);
let _ = app.written_clipboard_text();
let what = format!("frames {frames}, recording {recording}");
if recording {
assert_eq!(app.ui.status, steps, "{what}: the limit stays in the status bar");
} else {
assert!(app.ui.status.starts_with("Copied with "), "{what}: {}", app.ui.status);
}
}
}
}
/// A script whose commands give the recording's set a file larger than 8 MiB keeps its edit,
/// the status bar names the limit as the run ends, and Stop Playing/Recording keeps the steps
/// that fit in a set that Load Actions… reads. One that fills the file exactly names no limit.
+143 -4
View File
@@ -13,6 +13,7 @@
use serde_json::{Value, json};
use vectorcraft_engine::cmd::fileio;
use vectorcraft_engine::script::printing::{PreparedPrint, Printers};
use vectorcraft_pdf::Media;
use crate::{VectorcraftApp, io};
@@ -25,6 +26,9 @@ pub struct PrintJob<'a> {
/// The job's name in the print queue.
pub title: &'a str,
pub pdf: &'a [u8],
/// The printer driver's keyword for the paper the job prints on (`Letter`, `CR80`, `iso_a4_210x297mm`), sent to
/// CUPS as the job's `media`; `None` leaves the paper to the queue.
pub paper: Option<&'a str>,
/// Send the PDF to the printer's own PDF interpreter over its RAW TCP port instead of
/// spooling it through the platform driver (Windows).
pub direct_pdf: bool,
@@ -42,6 +46,10 @@ pub trait PrintService {
fn printers(&mut self) -> Vec<Printer>;
/// Send `job` to its printer → what happened, for the status bar.
fn print(&mut self, job: &PrintJob) -> Result<String, String>;
/// Whether the service applies the job's paper keyword when printing through the driver.
fn applies_paper(&self) -> bool {
false
}
/// Desktop services can submit on the existing background worker; browser services stay
/// on the UI thread to invoke their print dialog.
fn shared_print(&self) -> Option<SharedPrintFn> {
@@ -194,6 +202,118 @@ pub fn windows_papers(out: &str) -> Vec<Paper> {
papers
}
/// The paper sizes of a queue that has no local PPD, from `lpoptions -p NAME -l` (`PageSize/Media Size: *Letter A4
/// na_legal_8.5x14in`), which asks the queue's server: each choice of its `PageSize` or `media` line, sized by a PWG
/// self-describing name (`iso_a4_210x297mm`, `na_letter_8.5x11in`) or by one of the dialog's own paper names. Custom
/// sizes (`Custom.WxH`), keywords of unknown size and the limits of [`ppd_papers`] are left out.
pub fn lpoptions_papers(out: &str) -> Vec<Paper> {
let mut papers: Vec<Paper> = Vec::new();
for line in out.lines() {
let Some((head, choices)) = line.trim_end_matches('\r').split_once(':') else { continue };
let key = head.split('/').next().unwrap_or_default().trim();
if !key.eq_ignore_ascii_case("PageSize") && !key.eq_ignore_ascii_case("media") {
continue;
}
for choice in choices.split_whitespace().map(|c| c.trim_start_matches('*')) {
if !is_paper_keyword(choice) || choice.get(..7).is_some_and(|p| p.eq_ignore_ascii_case("custom.")) {
continue;
}
let size = pwg_size(choice).or_else(|| cups_b_size(choice)).or_else(|| Media::from_name(choice).and_then(Media::size));
if let Some((width, height)) = size {
push_paper(&mut papers, Paper { key: choice.into(), label: choice.into(), width, height });
}
}
}
papers
}
/// The IPP URI of the queue `printer` on the CUPS scheduler `server` (`CUPS_SERVER` or a `ServerName`: `host`,
/// `host:port`, `host:port/version=1.1`; `None` or empty for this machine's). `None` for a domain-socket server (a path),
/// which `ipptool` can't reach by URI. A server named without a port of its own gets `port` (from [`ipp_port`]) when
/// there is one; a bracketed IPv6 host (`[::1]`) has a port only after its `]`. With no server named, the URI is
/// `localhost` on the IPP default port, for a CUPS that reaches its own scheduler through its domain socket; a caller
/// whose CUPS has no socket names `localhost` to get `port`. The queue name is percent-encoded.
pub fn ipp_queue_uri(server: Option<&str>, port: Option<u16>, printer: &str) -> Option<String> {
let named = server.map(str::trim).filter(|s| !s.is_empty());
let port = if named.is_some() { port } else { None };
let server = named.unwrap_or("localhost");
if server.starts_with('/') || printer.is_empty() {
return None;
}
let host = server.split('/').next().unwrap_or_default();
if host.is_empty() || host.contains(['@', '?', '#', ' ']) {
return None;
}
let mut name = String::new();
for b in printer.bytes() {
if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.' | b'~') {
name.push(char::from(b));
} else {
name.push_str(&format!("%{b:02X}"));
}
}
let has_port = match host.strip_prefix('[') {
Some(rest) => rest.split_once(']').is_some_and(|(_, after)| after.starts_with(':')),
None => host.contains(':'),
};
let port = match port {
Some(port) if !has_port => format!(":{port}"),
_ => String::new(),
};
Some(format!("ipp://{host}{port}/printers/{name}"))
}
/// The port CUPS clients use for a server named without one, from the value of `IPP_PORT`: `None` when it is unset,
/// empty or not a port number from 1 to 65535.
pub fn ipp_port(value: Option<&str>) -> Option<u16> {
value.and_then(|v| v.trim().parse::<u16>().ok()).filter(|p| *p != 0)
}
/// The size in points of a CUPS PPD keyword for a B size: `B4` and `B5` are the JIS sizes, `ISOB4` and `ISOB5` the ISO
/// ones.
fn cups_b_size(keyword: &str) -> Option<(f64, f64)> {
let mm = match keyword.to_ascii_uppercase().as_str() {
"B4" => (257.0, 364.0),
"B5" => (182.0, 257.0),
"ISOB4" => (250.0, 353.0),
"ISOB5" => (176.0, 250.0),
_ => return None,
};
Some((mm.0 * 72.0 / 25.4, mm.1 * 72.0 / 25.4))
}
/// The paper sizes of a queue that serves no PPD at all, from the `media-supported` line of `ipptool -tv URI
/// get-printer-attributes.test` (`media-supported (1setOf keyword) = na_letter_8.5x11in,iso_a4_210x297mm`): each PWG
/// self-describing name, sized by its name. Custom ranges (`custom_min_…`, `custom_max_…`) and the limits of
/// [`ppd_papers`] are left out.
pub fn ipp_papers(out: &str) -> Vec<Paper> {
let mut papers: Vec<Paper> = Vec::new();
for line in out.lines() {
let Some((head, values)) = line.trim_end_matches('\r').split_once('=') else { continue };
if head.split_whitespace().next() != Some("media-supported") {
continue;
}
for name in values.split(',').map(str::trim) {
if !is_paper_keyword(name) || name.get(..7).is_some_and(|p| p.eq_ignore_ascii_case("custom_")) {
continue;
}
if let Some((width, height)) = pwg_size(name) {
push_paper(&mut papers, Paper { key: name.into(), label: name.into(), width, height });
}
}
}
papers
}
/// The size in points a PWG 5101.1 self-describing media name ends with (`_8.5x11in`, `_210x297mm`).
fn pwg_size(name: &str) -> Option<(f64, f64)> {
let dims = name.rsplit('_').next()?;
let (dims, scale) = if let Some(d) = dims.strip_suffix("mm") { (d, 72.0 / 25.4) } else { (dims.strip_suffix("in")?, 72.0) };
let (w, h) = dims.split_once('x')?;
let (w, h) = (w.parse::<f64>().ok()?, h.parse::<f64>().ok()?);
(w.is_finite() && h.is_finite()).then_some((w * scale, h * scale))
}
/// `print.printers`: the system's printers, and what the print service offers.
pub fn printers(app: &mut VectorcraftApp) -> Value {
let (printers, setup) = app.services.print.as_mut().map(|s| (s.printers(), s.has_setup())).unwrap_or_default();
@@ -282,7 +402,7 @@ pub(crate) fn send_script_prints(app: &mut VectorcraftApp, jobs: Vec<PreparedPri
fn send_each(submit: &mut dyn FnMut(&PrintJob<'_>) -> Result<String, String>, jobs: &[PreparedPrint]) -> Result<Vec<String>, String> {
let mut notes = Vec::new();
for (sent, job) in jobs.iter().enumerate() {
match submit(&PrintJob { printer: Some(&job.printer), title: &job.title, pdf: &job.pdf, direct_pdf: false }) {
match submit(&PrintJob { printer: Some(&job.printer), title: &job.title, pdf: &job.pdf, paper: None, direct_pdf: false }) {
Ok(note) => notes.push(note),
Err(e) if sent == 0 => return Err(e),
Err(e) => return Err(format!("{e} ({sent} of {} print jobs were sent)", jobs.len())),
@@ -291,6 +411,21 @@ fn send_each(submit: &mut dyn FnMut(&PrintJob<'_>) -> Result<String, String>, jo
Ok(notes)
}
/// `file.print`'s `paper`: the printer driver's keyword for the paper (absent or null: none). Anything but printable
/// ASCII without spaces, `,`, `/`, `:`, `=`, `"`, `'` or `\`, up to 64 characters, is an error.
fn paper_param(p: &Value) -> Result<Option<String>, String> {
match p.get("paper") {
None | Some(Value::Null) => Ok(None),
Some(Value::String(k)) if is_paper_keyword(k) => Ok(Some(k.clone())),
Some(v) => Err(format!("paper must be a printer driver's paper keyword, such as `Letter` or `CR80`, not {v}")),
}
}
/// A driver's paper keyword: 1 to 64 printable ASCII characters other than space, `,`, `/`, `:`, `=`, `"`, `'` and `\`.
pub fn is_paper_keyword(k: &str) -> bool {
!k.is_empty() && k.len() <= 64 && k.bytes().all(|b| b.is_ascii_graphic() && !matches!(b, b',' | b'/' | b':' | b'=' | b'"' | b'\'' | b'\\'))
}
/// `file.print` with settings: print the active document with `settings` (over the document's, or
/// over those of the print preset `preset` names) on `printer` (default: the system's default), or
/// save the job as a PDF at `path` (else a picked file, the web downloads it) with `toFile`, a
@@ -301,6 +436,11 @@ pub fn run(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
let s = |k: &str| p.get(k).and_then(Value::as_str).map(str::to_string);
let postscript = s("format").as_deref() == Some("postscript") || s("path").is_some_and(|path| fileio::extension(&path) == "ps");
let to_file = p.get("toFile").and_then(Value::as_bool).unwrap_or(false) || s("path").is_some() || postscript;
let paper = paper_param(p)?;
let direct_pdf = p.get("directPdf").and_then(Value::as_bool).unwrap_or(false);
if paper.is_some() && (to_file || direct_pdf || !app.services.print.as_ref().is_some_and(|s| s.applies_paper())) {
return Err("The print service cannot apply a paper keyword for this job.".into());
}
let mut q = json!({});
for k in ["preset", "settings", "format", "level", "flattenerPreset", "maxPages"] {
// An explicit null `maxPages` goes on, so the engine rejects it instead of printing every page.
@@ -338,7 +478,6 @@ pub fn run(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
let pdf = data.as_ref().and_then(Value::as_str).and_then(vectorcraft_format::base64_decode).ok_or("the print job has no data")?;
let title = app.session.active().map(|d| d.title()).unwrap_or_default();
let printer = s("printer").filter(|n| !n.is_empty());
let direct_pdf = p.get("directPdf").and_then(Value::as_bool).unwrap_or(false);
let service = app.services.print.as_mut().ok_or("no print service")?;
if let Some(submit) = service.shared_print() {
let pending_printer = printer.clone();
@@ -348,7 +487,7 @@ pub fn run(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
format!("Printing {title}"),
None,
move |_| {
submit(&PrintJob { printer: printer.as_deref(), title: &title, pdf: &pdf, direct_pdf })
submit(&PrintJob { printer: printer.as_deref(), title: &title, pdf: &pdf, paper: paper.as_deref(), direct_pdf })
.map(|note| json!({ "note": note, "printer": printer }))
},
move |app, result| {
@@ -370,7 +509,7 @@ pub fn run(app: &mut VectorcraftApp, p: &Value) -> Result<Value, String> {
}
return Ok(v);
}
let done = service.print(&PrintJob { printer: printer.as_deref(), title: &title, pdf: &pdf, direct_pdf })?;
let done = service.print(&PrintJob { printer: printer.as_deref(), title: &title, pdf: &pdf, paper: paper.as_deref(), direct_pdf })?;
app.status(done);
v["printer"] = json!(printer);
v["printed"] = json!(true);
+10 -1
View File
@@ -94,6 +94,9 @@ pub(crate) struct Publishing {
/// The status bar's message the latest Copy or Cut with notes left, with
/// [`crate::state::UiState::status_sets`] then.
notes_status: Option<(String, u64)>,
/// A message that no Copy or Cut's notes replace while the status bar shows it (a recording's
/// limit, which is named once), with [`crate::state::UiState::status_sets`] then.
kept: Option<(String, u64)>,
}
impl Publishing {
@@ -118,7 +121,13 @@ impl Publishing {
/// Does `ui`'s status bar still show the message the latest Copy or Cut left, with nothing
/// setting the status since?
fn shows_status(&self, ui: &crate::state::UiState) -> bool {
ui.status == self.status.0 && ui.status_sets == self.status.1
let kept = self.kept.as_ref().is_some_and(|(s, sets)| ui.status == *s && ui.status_sets == *sets);
!kept && ui.status == self.status.0 && ui.status_sets == self.status.1
}
/// `ui`'s status bar message stays while it shows: no Copy or Cut's notes replace it.
pub(crate) fn keep_status(&mut self, ui: &crate::state::UiState) {
self.kept = Some((ui.status.clone(), ui.status_sets));
}
/// Is the latest Copy or Cut one whose formats could not be written to `cb`, with nothing
+13 -13
View File
@@ -21,7 +21,7 @@ use craft::ui::contract::{Bind, BodyCx, Entry, Gap, Props as _, Show as _, ShowC
use craft::ui::display::Divider;
use craft::ui::docking::{DockGrid, GroupAt};
use craft::ui::form::Field;
use craft::ui::layout_components::{Row, Stack};
use craft::ui::layout_components::Row;
use craft::ui::pickers::{Anchor9, ReferencePointLook, Select};
use craft::ui::rails::{LastUsed, RailDensity, RailFooter, RailTool, SlotId, ToolRail, ToolSlot};
use craft::ui::runtime::commands::{self, CommandRef};
@@ -899,17 +899,21 @@ fn puppet_warp_options(app: &mut VectorcraftApp, ui: &mut Ui) {
}
pub(crate) mod card;
/// Search and Edit Toolbar share a row in a wide rail; a narrow rail keeps Edit Toolbar last.
/// Search and Edit Toolbar share a row in a wide rail. A one-column rail shows Edit Toolbar alone, so the default
/// rail still fits a 1000 pt window; Search Commands stays in the title bar, the Help menu and on its shortcut.
fn search_and_edit_buttons(app: &VectorcraftApp, ui: &mut Ui, footer: RailFooter) -> Option<egui::Response> {
let enabled = !crate::panel_docking::modal_window_up(app);
let wide = footer.columns > 1;
let mut edit = None;
let buttons = |ui: &mut Ui, _: &mut BodyCx<'_>| {
IconButton::command(IconId::new("search"), "help.commandPalette")
.label(tl!("Search commands"))
.tooltip(tl!("Search commands, tools, panels and effects"))
.selected(app.ui.palette_open)
.enabled(enabled)
.show(ui);
if wide {
IconButton::command(IconId::new("search"), "help.commandPalette")
.label(tl!("Search commands"))
.tooltip(tl!("Search commands, tools, panels and effects"))
.selected(app.ui.palette_open)
.enabled(enabled)
.show(ui);
}
edit = Some(
IconButton::new(IconId::new("more"))
.label(tl!("Edit Toolbar"))
@@ -919,11 +923,7 @@ fn search_and_edit_buttons(app: &VectorcraftApp, ui: &mut Ui, footer: RailFooter
.response,
);
};
if footer.columns > 1 {
Row::new().gap(Gap::Tight).id_salt("tools-footer-actions").show(ui, buttons);
} else {
Stack::new().gap(Gap::Tight).id_salt("tools-footer-actions").show(ui, buttons);
}
Row::new().gap(Gap::Tight).id_salt("tools-footer-actions").show(ui, buttons);
edit
}
+41 -9
View File
@@ -727,19 +727,22 @@ fn review_8758_layout(double: bool) {
let nodes = settled(&mut app, &ctx, 0.0, 1400.0);
review_8758_edit_control(&mut app, &ctx, &nodes);
let nodes = settled(&mut app, &ctx, 3.0, 1400.0);
let search = bounds(review_8758_button(&app, &ctx, &nodes, "Search commands")).unwrap();
let edit = bounds(review_8758_button(&app, &ctx, &nodes, "Edit Toolbar")).unwrap();
let panel = review_8758_panel(&app, &ctx);
if !double {
assert!(panel.contains_rect(edit) && edit.bottom() <= 1400.0, "Edit Toolbar fits the actual Tools panel");
assert!(
!nodes
.iter()
.any(|n| n.role() == Role::Button && n.label() == Some("Search commands") && bounds(n).is_some_and(|r| panel.contains_rect(r))),
"a one-column rail shows Edit Toolbar alone"
);
return;
}
let search = bounds(review_8758_button(&app, &ctx, &nodes, "Search commands")).unwrap();
assert!(panel.contains_rect(search) && panel.contains_rect(edit), "both controls fit the actual Tools panel");
assert!(search.bottom() <= 1400.0 && edit.bottom() <= 1400.0, "both controls fit the window");
if double {
assert!(search.right() <= edit.left() && (search.center().y - edit.center().y).abs() < 0.01, "Search left of Edit on one row");
} else {
assert!(
search.bottom() <= edit.top() && (search.center().x - edit.center().x).abs() < 0.01,
"one column keeps both controls in a fitted stack"
);
}
assert!(search.right() <= edit.left() && (search.center().y - edit.center().y).abs() < 0.01, "Search left of Edit on one row");
let chord = crate::menus::shortcut_of(&app, "help.commandPalette").expect("the native Search command has its current shortcut");
let expected = craft::ui::contract::tooltip::with_chord("Search commands, tools, panels and effects", &chord, crate::keymap::platform());
let tips = review_8758_hovered_texts(&mut app, &ctx, 4.0, search.center());
@@ -768,10 +771,39 @@ fn review_8758_toolbar_search_fits_beside_edit_and_opens_the_existing_palette()
}
}
/// The default one-column rail in a window 1000 points tall: its footer ends with Edit Toolbar inside the rail's
/// visible area, so the button shows without scrolling the rail.
#[test]
fn one_column_rail_shows_edit_toolbar_in_a_1000_point_window() {
crate::i18n::set_current(crate::i18n::Lang::EN);
let mut app = app_with(300, 300);
let ctx = reader();
let nodes = settled(&mut app, &ctx, 0.0, 1000.0);
let panel = review_8758_panel(&app, &ctx);
let rail = nodes
.iter()
.find(|n| n.role() == Role::Toolbar && n.label() == Some("Tools") && bounds(n).is_some_and(|r| panel.contains_rect(r)))
.and_then(bounds)
.expect("the Tools rail is drawn");
let edit = bounds(review_8758_button(&app, &ctx, &nodes, "Edit Toolbar")).unwrap();
let screen_mode = named_rect(&nodes, "Change Screen Mode (F)");
assert!(rail.contains_rect(edit), "Edit Toolbar shows inside the rail without scrolling: {edit:?} in {rail:?}");
assert!(screen_mode.bottom() <= edit.top(), "Edit Toolbar stays the last control of the footer");
assert!(
!nodes.iter().any(|n| n.role() == Role::Button && n.label() == Some("Search commands") && bounds(n).is_some_and(|r| rail.intersects(r))),
"one column leaves Search Commands to the title bar, the Help menu and its shortcut"
);
// Edit Toolbar still opens the Tools customization drawer.
click(&mut app, &ctx, 1.0, edit.center(), 1000.0);
assert!(app.ui.tools_drawer, "the footer's Edit Toolbar opens the customization drawer");
}
#[test]
fn review_8758_toolbar_search_accepts_a_tool_query_and_is_disabled_over_a_dialog() {
crate::i18n::set_current(crate::i18n::Lang::EN);
let mut app = app_with(300, 300);
// The two-column rail, whose footer has Search.
app.run("window.toolbarColumns", json!({"double": true})).unwrap();
let ctx = reader();
let nodes = settled(&mut app, &ctx, 0.0, 1400.0);
let search = bounds(review_8758_button(&app, &ctx, &nodes, "Search commands")).unwrap();
+7 -6
View File
@@ -27,7 +27,7 @@ History panel row context menus (2026-11-20, G12): Right-clicking any state offe
OpenType panel feature-row context menus (part of G12): a secondary click on a feature row keeps the text selection and offers Turn Off when that feature is on for every character the panel acts on, or Turn On when it is off or mixed. Turn On and Turn Off use the same toggle as a click on the checkbox, so a mixed row turns the feature on for every character. Reset OpenType Features applies the same default as the panel menu and is enabled on the same condition. Each choice is one undo step. Evidence: `panels::opentype::tests::right_clicking_an_opentype_row_offers_turn_on_or_turn_off`, `panels::opentype::tests::clicking_turn_on_sets_that_feature_in_one_undo_step`, and `panels::opentype::tests::clicking_reset_opentype_features_clears_the_rows` in `crates/ui-egui/src/panels/opentype.rs`. Scores and estimates unchanged.
**Tools toolbar search (#8758):** Search sits beside Edit Toolbar in the two-column Tools panel and above it in one column. It opens the existing command palette, which finds and activates tools, and is disabled while a modal window is open. Edit Toolbar keeps the existing native customization drawer and focus opener. Focused toolbar-frame cases in `crates/ui-egui/src/toolbar/tests.rs` cover layout, actual search/tool activation, dialog admission and retained document/history/customization behavior. Scores and estimates are unchanged.
**Tools toolbar search (#8758):** Search sits beside Edit Toolbar in the two-column Tools panel. A one-column Tools panel shows Edit Toolbar alone, so the default rail fits a 1000 pt window; Search there is in the title bar, Help › Search Commands… and its shortcut. It opens the existing command palette, which finds and activates tools, and is disabled while a modal window is open. Edit Toolbar keeps the existing native customization drawer and focus opener. Focused toolbar-frame cases in `crates/ui-egui/src/toolbar/tests.rs` cover layout, actual search/tool activation, dialog admission and retained document/history/customization behavior. Scores and estimates are unchanged.
- **Implemented and tested (2026-11-20, G12):** Variables panel row context menus: Right-click highlights the clicked variable without changing the canvas selection and offers Select Bound Object, Variable Options…, Unbind Variable, the four Make Dynamic actions, and Delete Variable. Shift+F10 opens the same menu for the focused row; Escape dismisses it. Row actions target that variable; dynamic actions use the canvas selection. Lock and selection checks disable unavailable actions. Headless pointer/accessibility tests cover opening the menu, highlighting, bound-object selection, deletion in one undo step and restoration, and disabled actions. Scores and estimates unchanged.
@@ -857,12 +857,13 @@ macOS cursor delivery (#2292) is narrowed to a native host adapter using the exi
## G6 Automation and scripting
- **Missing:** the rest of the document object model for scripts (views, the selected path points, gradient stops
and the other classes) and the `#engine` script directive (#1183 is open). Scripts have `app`, the open
documents, new documents, each document's selection, its page items, layers, groups, compound paths and
artboards, its text frames with their text ranges and
- **Missing:** the rest of the document object model for scripts (gradient stops and the other classes) and the
`#engine` script directive (#1183 is open). Scripts have `app`, the open documents, new documents, each document's
selection, its page items, layers, groups, compound paths and artboards, its text frames with their text ranges and
character and paragraph attributes, their links to each other and the stories they form, its character and
paragraph styles, the installed fonts, and each document's variables, data sets and variable libraries, and
paragraph styles, the installed fonts, each document's variables, data sets and variable libraries, and its
linked and embedded images (`placedItems` and `rasterItems`, with `PlacedItem` and `RasterItem`); tracing,
rasterizing and capturing images are still missing.
`Document.pathItems` makes paths and reads and changes their points, colors, stroke options and transforms.
Scripts save, export and open documents with `Document.saveAs`, `Document.exportFile` and `app.open`, read a
document's `fullName`, `path` and `saved`, and close it with `Document.close`.
+59 -25
View File
@@ -3218,12 +3218,13 @@ through `$`:
a position only (VectorCraft's own rule). `JSON.stringify` does not read `toJSON` from a collection this way. `name` and `note`
take a number or a Boolean as the text `String(value)` gives. `String(object)` gives
`[PathItem Logo]` for a page item named `Logo` (`[PathItem ]` with no name), `[Document <name>]`,
`[Layer <name>]`, `[Application]` and `[PageItems]` (VectorCraft's own rule).
`[Layer <name>]`, `[Artboard <name>]`, `[Application]`, `[PageItems]`, `[Layers]`, `[GroupItems]`,
`[CompoundPathItems]` and `[Artboards]` (VectorCraft's own rule).
`documents[0]` is always the active document, as the same page says. VectorCraft's own rules: the other
documents follow from the one active most recently to the one active longest ago, and a change a script
makes to a document in the back does not move it in the list; page items are listed with the objects inside groups and compound paths after their group and without layers and ruler guides. A document's
`selection`, and `app.selection` while a document is open, is an empty list when nothing is selected. The layers
paragraph below gives the order of a layer's, a group's and a compound path's lists. Script coordinates
makes to a document in the back does not move it in the list; page items are listed with the objects inside groups and compound paths after their group and without layers and ruler guides (the layers
paragraph below gives the order of a layer's, a group's and a compound path's lists). A document's
`selection`, and `app.selection` while a document is open, is an empty list when nothing is selected. Script coordinates
are points with Y up from the bottom-left corner of the first artboard, or, with
`CoordinateSystem.ARTBOARDCOORDINATESYSTEM`, Y down from the top-left corner of the active artboard. `typename`
is `TextFrame` for type, and `BlendItem`, `EnvelopeItem`, `RepeatItem`, `PlacedDocumentItem` and `IntertwineItem`
@@ -3232,10 +3233,13 @@ through `$`:
tab as it was. A command that selects the objects it changes leaves the current layer and the highlighted Layers
panel rows as they were before the change. A bad value throws an error and changes nothing. An object that was
deleted, that a named engine kept from an earlier run, or whose document was reverted with `file.revert`, throws
`Stale page item`. Layer and artboard objects also become stale after their document is reverted (an artboard
throws `Stale artboard`), and so do the `layers`,
`Stale page item`. Layer objects also become stale after their document is reverted, and so do the `layers`,
`pageItems`, `groupItems`, `compoundPathItems` and `pathItems` of a layer, group or compound path read before the
revert; the document's own collections stay usable. `remove()` on an object that
revert (`Stale page item`) and `Artboard` objects (`Stale artboard`); the document's own collections list the
reverted document.
`removeAll()` on a layer's or group's `pageItems`, `groupItems` or `compoundPathItems`, or on the document's
`groupItems` or `compoundPathItems`, throws and deletes nothing when it would delete the clipping path of a group
or layer that keeps other objects. `remove()` on an object that
is hidden or locked, is inside a hidden or locked layer or group, or is a group that holds one, and `removeAll()`
when any object is, throw `cannot delete hidden or locked objects` and delete nothing. `remove()` on an object on
a locked artboard, and `removeAll()` when any object is on one, throw `cannot delete objects on a locked artboard`
@@ -3283,8 +3287,9 @@ through `$`:
(https://ai-scripting.docsforadobe.dev/jsobjref/GroupItems/) and `compoundPathItems` have `length`, `[i]`,
`index(key)`, `getByName(name)`, `add()` and `removeAll()`. `groupItems.add()` runs `object.newGroup`.
`clipped` runs `layer.clippingMask.toggle`. `artboards` (https://ai-scripting.docsforadobe.dev/jsobjref/Artboards/)
has `length`, `[i]`, `index(key)`, `getByName(name)`, `add(artboardRect)` (runs `artboard.new`),
`insert(artboardRect, index)` (runs `artboard.new` and `artboard.reorder`), `remove(index)` (runs
has `length`, `[i]`, `index(key)`, `getByName(name)`, `add(artboardRect)` (runs `artboard.new` and returns
the new artboard), `insert(artboardRect, index)` (runs `artboard.new` and `artboard.reorder`, returns nothing;
read `artboards[index]` afterward), `remove(index)` (runs
`artboard.delete`), `getActiveArtboardIndex()` and `setActiveArtboardIndex(index)`. An `Artboard`
(https://ai-scripting.docsforadobe.dev/jsobjref/Artboard/) has `typename`, `parent`, `artboardRect`, `name`,
`rulerOrigin`, `rulerPAR` (0.1 to 10), `showCenter`, `showCrossHairs`, `showSafeAreas` and `remove()`; its
@@ -3295,21 +3300,29 @@ through `$`:
it, topmost first. The document's `groupItems` and `compoundPathItems` hold every group or compound path at any
depth, in the order of the document's `pageItems`. A layer's `pageItems` leave out its sublayers. A compound
path's `pathItems` are a `PathItems` collection: `add()` and its shape methods make the new path inside the
compound path. A layer's or artboard's `name` takes a number or a boolean as
`String()` writes it. `locked` true means the layer is locked. `color` is an object `{red, green, blue}` of whole
compound path.
Scoped collections support `toString()` and `String()`. For `Layers`, `GroupItems`, `CompoundPathItems` and
`Artboards`, the conversion throws the same error as `typename` once the container is deleted or the document is
closed. A layer's or artboard's `name` takes a number or a boolean as
`String()` writes it. `locked` true means the layer is locked. `color` is an `RGBColor` object with `typename` and `{red, green, blue}` of whole
numbers from 0 to 255. A layer's name is from 1 to 512 characters. A layer's `zOrderPosition` counts the layers
beside it from 1 at the bottom, leaving out art, and `zOrder` with `BRINGFORWARD` or `SENDBACKWARD` moves it past
beside it from 1 at the bottom, leaving out art; each scan counts toward the script's operation budget.
`zOrder` with `BRINGFORWARD` or `SENDBACKWARD` moves it past
the next layer beside it and any art between them.
`hasSelectedArtwork = true` adds the layer's shown, unlocked art to the selection (`select.add`), and `false`
deselects only the layer's art (`select.toggle`); the rest of the selection, ruler guides included, stays. A layer
with nothing to add or deselect runs no command.
with nothing to add or deselect runs no command. Each assignment counts the current selection toward the script's
operation budget, and `true` also counts every node of the layer it looks at, hidden and locked ones included.
`clipped = true` makes the group's topmost object, which must be a path, a compound path or type, its clipping
path; `false` releases the mask; the group keeps its id. `groupItems.add()` makes an empty group on top of the
path; `false` releases the mask; the group keeps its id. Changes are refused when the group or its layer is
hidden or locked, or its artboard is locked. A scoped `removeAll()` that leaves a clipping group or layer
without art releases its mask in the same undo step. `groupItems.add()` makes an empty group on top of the
layer's or group's contents, or of the current layer's for the document's collection, and `compoundPathItems.add()`
makes an empty compound path in the same place
(https://ai-scripting.docsforadobe.dev/jsobjref/CompoundPathItems/). A path that `move` or `duplicate` puts into a
compound path becomes one of its paths and gives up its own paint, as Make Compound Path leaves its paths. The
compound path becomes pixel-aligned when the path was, or when the compound path it leaves was. An empty
compound path becomes pixel-aligned when the path was, or when the compound path it leaves was. A path moved
into an already pixel-aligned compound path is snapped to the pixel grid. An empty
compound path takes the paint the first path that goes in was drawn with: the path's own, or the paint of the
compound path it leaves. Other objects are refused. A path that `move` takes out of a compound path into a layer or
a group takes the compound path's paint and pixel alignment, as Release Compound Path gives them to its paths.
@@ -3331,9 +3344,11 @@ through `$`:
default: the current layer), on top of its contents or at `index` (0 is the bottom; in a clipping layer or group,
index 0 puts it directly above the clipping path), as one undo step named Group, and
gives `{id}`. With `compound: true` it adds an empty compound path instead, as one undo step named Compound Path.
An omitted key takes its default (`parent`: the current layer; `index`: on top; `compound`: false).
Explicit `null` is refused for `parent`, `index` and `compound`.
The selection stays as it is. `node.move` also puts a path into a shown, unlocked compound path (its layer and
groups shown and unlocked too, and not on a locked artboard), where the path
gives up its own paint, and an empty compound path takes the paint the first path that goes in was drawn with. A
gives up its own paint (a clip group's or clipping layer's clipping path is refused until its mask is released), and an empty compound path takes the paint the first path that goes in was drawn with. A
path that `node.move` takes out of a compound path into a layer or a group takes the compound path's paint and pixel
alignment.
- `app.preferences` (https://ai-scripting.docsforadobe.dev/jsobjref/Preferences/) has `getBooleanPreference(key)`,
@@ -3356,7 +3371,8 @@ through `$`:
`concatenateTranslationMatrix(matrix, deltaX?, deltaY?)`, `concatenateScaleMatrix(matrix, scaleX?, scaleY?)`,
`concatenateRotationMatrix(matrix, angle?)`, `invertMatrix(matrix)`, `isEqualMatrix(matrix, secondMatrix)` and
`isSingularMatrix(matrix)` work on `Matrix` records (https://ai-scripting.docsforadobe.dev/jsobjref/Matrix/): plain
objects with `mValueA`, `mValueB`, `mValueC`, `mValueD`, `mValueTX`, `mValueTY` and `typename` `"Matrix"`. Each
objects with the finite numbers `mValueA`, `mValueB`, `mValueC`, `mValueD`, `mValueTX` and `mValueTY`. A record
passed in needs only those six fields; each record a function gives also has `typename` `"Matrix"`. Each
function other than `isEqualMatrix` and `isSingularMatrix` gives a new record; those two give `true` or `false`.
No function changes the records passed to it. A record maps `(x, y)` to
`(a·x + c·y + tx, b·x + d·y + ty)`, as a PDF `cm` matrix does (ISO 32000-1, 8.3.4), with Y up. VectorCraft's own
@@ -3365,7 +3381,9 @@ through `$`:
`scaleY` is `scaleX`; quarter turns are exact; each value `concatenateMatrix` gives is its exact sum of products
rounded once; a matrix whose determinant is 0 is singular, and `invertMatrix` of one
throws; `isEqualMatrix` compares the six values exactly. A value that is not a finite number throws a `TypeError`,
and a result too large for a number throws a `RangeError`.
and a result too large for a number throws a `RangeError`. `invertMatrix` decides overflow from each value's exact
quotient: when its magnitude is below the halfway point between `Number.MAX_VALUE` and 2^1024 the value is a finite
number, and at that point or past it the call throws a `RangeError`.
- `app.copy()`, `app.cut()` and `app.paste()` (https://ai-scripting.docsforadobe.dev/jsobjref/Application/) run
`edit.copy`, `edit.cut` and `edit.paste` on the active document inside the run's transaction. With nothing selected
`copy` and `cut` do nothing, and with the clipboard empty `paste` does nothing; `paste` with no document open throws
@@ -3496,8 +3514,9 @@ through `$`:
`null`, `embedded` is `true` and takes only `true`, and `status` is `RasterLinkState.NODATA`. `transparent` is true
for an image with an alpha channel or a transparent palette entry. `matrix` is a record of `mValueA` to `mValueTY`
that maps the image's pixels, row 0 at the top, to script coordinates, and a distorted image has none. Assigning
`matrix` runs `object.transform`; a value that is not finite, a matrix with no area and one that puts a corner of
the image outside the canvas throw an error with nothing changed. `boundingBox` is the pixel rectangle at one point
`matrix` runs `object.transform`, except that a matrix equal to the one `matrix` reads runs no command; a value
that is not finite, a matrix with no area, one that puts a corner of the image outside the canvas and one that a
nearly singular image cannot reach exactly throw an error with nothing changed. `boundingBox` is the pixel rectangle at one point
a pixel. `removeAll()` refuses images as `pageItems.removeAll()` refuses objects, and so throws `cannot delete
objects on a locked artboard` and deletes nothing when an image is on one. Assigning `file` or `matrix` checks the
item before the value, so a stale item throws `Stale page item` whatever the value. Assigning `matrix` to an `add()`
@@ -3883,9 +3902,13 @@ through `$`:
app passes the Actions panel's actions with their included steps, and a recorded `command.batch` step gives its own
steps. A step that acts on the active artboard (Paste in Place, in Front and in Back, Align, Distribute Objects and
Distribute Spacing to the artboard, Select › All on Active Artboard, Edit Symbol, Fit to Artwork Bounds and Fit to
Selected Art) and does not name one acts on the active document's active artboard, by the index it had as the run
started, which the view keeps: after the script deletes artboards, the artboard now at that index, or the last one
past the end. While the Artboard tool has several artboards selected as the run starts, a paste step and a Fit to
Selected Art) and does not name one acts on the active document's active artboard. Once the script has called
`setActiveArtboardIndex` on that document, it is the artboard the script chose while that artboard exists. If it
has been deleted, playback uses the same fallback as `getActiveArtboardIndex()`, script coordinates and the view:
the saved active artboard if it still exists, otherwise index 0. File > Revert discards the script's stored choice.
If the script has not chosen an artboard on that document since its last revert, the step uses the index of its active artboard
as the run started: after the script deletes artboards, the artboard now at that index, or the last one past the
end. While the Artboard tool has several artboards selected as the run starts, a paste step and a Fit to
Artwork Bounds step act on those instead, as in the panel's playback. A step of a recorded `command.batch` step that
names its `artboard` acts on that artboard, or the last one past the end, as `command.batch` gives it. VectorCraft's
own rules: the action and its set are matched by their exact names, and a name that matches no action or more than
@@ -4977,6 +5000,7 @@ With `ids`, `guides: true` also deletes the selected ruler guides. The command r
boolean or `null`. A compound path left with no paths is deleted too, unless `keepEmpty: true` is given, which keeps
it, empty, also when the deleted parts are direct-selected anchors; a `keepEmpty` value that is not a boolean or `null`
is rejected. `null` for `guides`, `keepEmpty` or `keepJoined` counts as leaving the key out.
A clipping group or layer left without art releases its mask in the same undo step.
Without `ids`, `keepJoined: true` removes the direct-selected anchors of each path that has no selected segment as
`path.removeAnchors` does (see Removing anchor points): the path stays joined, and the next anchor along is selected
(the one before at an open path's end). When no subpath that lost an anchor keeps two anchors, the path stays selected
@@ -11107,7 +11131,8 @@ that category), `name`, `width`/`height`
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
fewer artboards, until `columns` without `rows`, or another layout, is given; New Document's Columns shows the columns
the rows give the current number of artboards, and New Document drops the rows when Columns or the layout changes),
the rows give the current number of artboards, and New Document drops the rows when Columns or the layout changes;
with neither `columns` nor `rows` set, Columns shows the columns `file.new` lays out: one row of all the artboards in a grid),
`bleed`, `backgroundContents`, `colorMode`, `rasterEffectsPpi` (1 to 2,400; a saved preset's
value outside that range is read as the nearer end), `previewMode` and `alignNewObjectsToPixelGrid` (see
[Align New Objects to Pixel Grid](#align-new-objects-to-pixel-grid)).
@@ -13524,7 +13549,16 @@ prints at most that many pages, copies counted; with more, `file.print` composes
`{pages, format}`. A composite job without `skipBlank` that prints its artboards is counted on the artboards before
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.
default printer) or, with `toFile`, a `path` or no printing available, saves the PDF. `paper` names the printer
driver's keyword for the paper (`Letter`, `CR80`, `iso_a4_210x297mm`), which the job asks the print queue for as its
`media` on macOS and Linux. `paper` is an error on Windows, with file output, with `directPdf`, or when the value is
not such a keyword. The Print dialog sends the keyword of the Size chosen when the printer's driver lists that paper. A printer whose PPD is not on this machine (a driverless or
remote queue), or any printer when `CUPS_SERVER` or `ServerName` names a scheduler other than a domain socket,
`localhost`, `127.0.0.1` or `::1` (each with no port or port 631), lists the paper sizes `lpoptions -l` reports for it, and when its server has no PPD either, the sizes
of its IPP `media-supported` attribute. That lookup asks the server named by `CUPS_SERVER` or, on Linux,
`client.conf`'s `ServerName`; a server named without a port, or `localhost` when no server is named and CUPS has no domain socket, is
asked on the port in `IPP_PORT` when it is set, and a port in the server name takes precedence. CUPS's own domain socket named as the
server is asked as `localhost` on port 631; another socket path is not asked.
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.
+1 -1
View File
@@ -33,7 +33,7 @@
## Feature submission evidence
Color conversion (#8804) builds one first-name index for the document's global swatch bases and uses indexed lookups for linked paints. Document Color Mode, new-art colors and text-style conversion keep first-record shadowing, spot handling, tint behavior and missing-link fallback. The base construction changes from quadratic name searches to O(N log N) index work; this is a source-complexity result, not a measured elapsed-time or budget improvement. Command-level semantic controls are in `crates/engine/src/tests/colormgmt.rs`; scores and estimates are unchanged.
**Tools toolbar search (#8758):** Search sits beside Edit Toolbar in the two-column Tools panel and above it in one column. It opens the existing command palette, which finds and activates tools, and is disabled while a modal window is open. Edit Toolbar keeps the existing native customization drawer and focus opener. Focused toolbar-frame cases in `crates/ui-egui/src/toolbar/tests.rs` cover layout, actual search/tool activation, dialog admission and retained document/history/customization behavior. Scores and estimates are unchanged.
**Tools toolbar search (#8758):** Search sits beside Edit Toolbar in the two-column Tools panel. A one-column Tools panel shows Edit Toolbar alone, so the default rail fits a 1000 pt window; Search there is in the title bar, Help › Search Commands… and its shortcut. It opens the existing command palette, which finds and activates tools, and is disabled while a modal window is open. Edit Toolbar keeps the existing native customization drawer and focus opener. Focused toolbar-frame cases in `crates/ui-egui/src/toolbar/tests.rs` cover layout, actual search/tool activation, dialog admission and retained document/history/customization behavior. Scores and estimates are unchanged.
**Layers appearance marker (#8710):** A small hollow diamond marks an item's own appearance or transparency, distinct from the double ring for targeting and the selected-art square. A tooltip explains the current marker state. Existing targeting, dragging and Alt-copy behavior are retained. This follow-up depends on Hassan1305's #8757 and preserves its visible target ring and four-state coverage. Source and focused native Layers-panel coverage are in `crates/ui-egui/src/panels/layers/cells.rs`, `crates/ui-egui/src/panels/layers/rows.rs` and `crates/ui-egui/src/panels/layers/tests.rs`; runtime validation is pending. Scores and estimates are unchanged.
+5 -5
View File
@@ -77,7 +77,7 @@ Script appearance and geometry setters reject objects on locked artboards. Assig
**Layers appearance marker (#8710):** A small hollow diamond marks an item's own appearance or transparency, distinct from the double ring for targeting and the selected-art square. A tooltip explains the current marker state. Existing targeting, dragging and Alt-copy behavior are retained. This follow-up depends on Hassan1305's #8757 and preserves its visible target ring and four-state coverage. Source and focused native Layers-panel coverage are in `crates/ui-egui/src/panels/layers/cells.rs`, `crates/ui-egui/src/panels/layers/rows.rs` and `crates/ui-egui/src/panels/layers/tests.rs`; runtime validation is pending. Scores and estimates are unchanged.
**Tools toolbar search (#8758):** Search sits beside Edit Toolbar in the two-column Tools panel and above it in one column. It opens the existing command palette, which finds and activates tools, and is disabled while a modal window is open. Edit Toolbar keeps the existing native customization drawer and focus opener. Focused toolbar-frame cases in `crates/ui-egui/src/toolbar/tests.rs` cover layout, actual search/tool activation, dialog admission and retained document/history/customization behavior. Scores and estimates are unchanged.
**Tools toolbar search (#8758):** Search sits beside Edit Toolbar in the two-column Tools panel. A one-column Tools panel shows Edit Toolbar alone, so the default rail fits a 1000 pt window; Search there is in Help › Search Commands… and its shortcut, and in the title bar while the app bar is wide enough to show it. It opens the existing command palette, which finds and activates tools, and is disabled while a modal window is open. Edit Toolbar keeps the existing native customization drawer and focus opener. Focused toolbar-frame cases in `crates/ui-egui/src/toolbar/tests.rs` cover layout, actual search/tool activation, dialog admission and retained document/history/customization behavior. Scores and estimates are unchanged.
Variables panel row context menus (2026-11-20, G12): Right-click highlights the clicked variable without changing the canvas selection and offers Select Bound Object, Variable Options…, Unbind Variable, the four Make Dynamic actions, and Delete Variable. Shift+F10 opens the same menu for the focused row; Escape dismisses it. Row actions target that variable; dynamic actions use the canvas selection. Lock and selection checks disable unavailable actions. Headless pointer/accessibility tests cover opening the menu, highlighting, bound-object selection, deletion in one undo step and restoration, and disabled actions. Scores and estimates unchanged.
@@ -1114,10 +1114,9 @@ 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 document's layers and sublayers with their options, stacking and current layer, its groups and compound paths with clipping masks, new empty groups and compound paths and paths moved into compound paths, and its artboards with their rectangles, names, ruler origins and display options, added, inserted, removed and made active, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Layer/, https://ai-scripting.docsforadobe.dev/jsobjref/Layers/, https://ai-scripting.docsforadobe.dev/jsobjref/GroupItems/, https://ai-scripting.docsforadobe.dev/jsobjref/CompoundPathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/CompoundPathItems/, https://ai-scripting.docsforadobe.dev/jsobjref/Artboard/ and https://ai-scripting.docsforadobe.dev/jsobjref/Artboards/ describe them (`docs/mcp.md`). `crates/engine/src/tests/script_dom.rs`, `crates/ui-egui/src/tests/script_run.rs`.
- Scripts: `Document.pathItems`, and a layer's or group's `pathItems` (https://ai-scripting.docsforadobe.dev/jsobjref/Layer/, https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/) for the paths directly in it, list the paths and make 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`, `crates/engine/src/tests/script_dom.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 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: `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.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: 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`.
@@ -1126,16 +1125,17 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- Scripts: `document.characterStyles` and `document.paragraphStyles` add, find, rename, redefine, apply and remove character and paragraph styles, with the Normal styles listed first and kept, and a text range lists the styles its text is in, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/CharacterStyles/, https://ai-scripting.docsforadobe.dev/jsobjref/CharacterStyle/, https://ai-scripting.docsforadobe.dev/jsobjref/ParagraphStyles/, https://ai-scripting.docsforadobe.dev/jsobjref/ParagraphStyle/ and https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/ describe them (`docs/mcp.md`). Style names of 1 to 256 characters without control characters, and at most 4,096 styles named in one run, are VectorCraft's own rules. Load Character Styles, Load Paragraph Styles and Load All Styles refuse a file larger than 64 MB. A paragraph style's character attributes are not there yet. `crates/engine/src/tests/script_styles.rs`.
- Scripts: a text frame's `nextFrame` and `previousFrame` read and set its links to the frames before and after it, `areaText` and `pathText` thread a new frame to a base frame, and `document.stories` lists the stories, each with its frames in thread order and its text across them as one text range with its characters, words and paragraphs, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/, https://ai-scripting.docsforadobe.dev/jsobjref/Story/ and https://ai-scripting.docsforadobe.dev/jsobjref/Stories/ describe them; `text.thread.setNeighbor` links or unlinks two frames by id (`docs/mcp.md`). Which links are refused, and how a story is listed and found, are VectorCraft's own rules. `crates/engine/src/tests/script_threads.rs`.
- Scripts: `PageItem.tags` reads, adds, renames and deletes an object's tags, name and value pairs that the native file keeps, and `Document.tags` reads, renames and deletes the tags of every page item but adds none (its `add` throws; a script adds a tag through the page item's `tags`), as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Tags/ and https://ai-scripting.docsforadobe.dev/jsobjref/Tag/ describe them, through `object.tags` and the `object.tag.*` commands, at most 64 tags an object (`docs/mcp.md`). `crates/engine/src/tests/script_tags.rs`.
- Scripts: a document's layers and sublayers with their options, stacking and current layer, its groups and compound paths with clipping masks, new empty groups and compound paths and paths moved into compound paths, and its artboards with their rectangles, names, ruler origins and display options, added, inserted, removed and made active, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Layer/, https://ai-scripting.docsforadobe.dev/jsobjref/Layers/, https://ai-scripting.docsforadobe.dev/jsobjref/GroupItems/, https://ai-scripting.docsforadobe.dev/jsobjref/CompoundPathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/CompoundPathItems/, https://ai-scripting.docsforadobe.dev/jsobjref/Artboard/ and https://ai-scripting.docsforadobe.dev/jsobjref/Artboards/ describe them (`docs/mcp.md`); `artboards.add` returns the new artboard and `artboards.insert` returns nothing. Scoped collections support string conversion, which fails for `Layers`, `GroupItems`, `CompoundPathItems` and `Artboards` once their container is gone; a compound path's `pathItems` are `PathItems` objects whose `add()` and shape methods make the new path inside it. Empty clipping containers release their masks in the deletion's undo step, and `clipped` changes check locks. Layer selection changes keep unrelated selected objects, layer colors are assignable `RGBColor` values, stacking scans count toward the script budget, and paths moved into pixel-aligned compound paths are snapped. `crates/engine/src/tests/script_dom.rs`, `crates/ui-egui/src/tests/script_run.rs`.
- Scripts: `Document.print` prints the document to a file with `PrintOptions` and the job, color management, color separation, coordinate, flattener, font, page marks, paper and PostScript option classes the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PrintOptions/ and https://ai-scripting.docsforadobe.dev/jsobjref/PrintJobOptions/ describe, over the document's print settings, and `app.printPresetsList` lists the print presets (`docs/mcp.md`); `CUSTOMPROFILE` without a profile `name` throws. `crates/engine/src/tests/script_print.rs`.
- Scripts: `Document.exportFile` with `ExportType.AutoCAD` writes a DXF file with the `ExportOptionsAutoCAD` options and the AutoCAD enumerations that https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsAutoCAD/ and https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/ describe; DWG throws an error that says it is not available (`docs/mcp.md`). `crates/engine/src/tests/script_save_open.rs`.
- Scripts: `Document.print` without a file prints to the printer `PrintOptions.printerName` names, or the default printer, and `app.printerList` lists the installed printers as `Printer` objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PrintOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/Application/ and https://ai-scripting.docsforadobe.dev/jsobjref/Printer/ describe. VectorCraft's own rules: the jobs are sent after the run's changes are kept and the person at the keyboard clicks Print or presses Space on it, which takes no click or focus for the first second, nothing is sent from a failed run, and the web build, and MCP or the command line without the app, cannot print to a printer from a script (`docs/mcp.md`). `crates/engine/src/tests/script_print.rs`, `crates/ui-egui/src/tests/script_print.rs`.
- Scripts: `Document.saveAs`, `Document.exportFile` and `app.open` save, export and open documents, `Document.fullName` and `saved` give a document's file and saved state, setting `saved` records that state (`document.setSaved`), `Document.path` gives its folder as a `Folder` (VectorCraft's own type), and `Document.close` closes it, saving to its file first with `SaveOptions.SAVECHANGES`, with the option classes the help pages https://ai-scripting.docsforadobe.dev/jsobjref/IllustratorSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/EPSSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/PDFSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsPNG24/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsJPEG/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsSVG/, https://ai-scripting.docsforadobe.dev/jsobjref/PDFFileOptions/ and https://ai-scripting.docsforadobe.dev/jsobjref/Document/ describe (the enumerations of the options that keep their defaults included), and read and write only where the script's `File` objects may, refusing a path whose real file name is not valid UTF-8; the warnings of each save, export and open go to the console (`docs/mcp.md`). `crates/engine/src/tests/script_save_open.rs`.
- Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). A script can check a member with `hasOwnProperty`, and can read a collection by name and name `activeDocument`, `documents` and `selection` without `app.` (https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/). A key such as `1` is an array index and reads that position; in `pageItems` and `documents`, a number that is not an array index, such as `-1` or `1.5`, is looked up by name when the key is the text JavaScript writes for that number. VectorCraft's own rule. `app.executeMenuCommand` runs the menu items Select All, Deselect, Group, Ungroup, Make and Release Clipping Mask, Make and Release Compound Path, and Fit to Artwork Bounds by their menu command names (https://community.adobe.com/questions-652/a-list-of-illustrator-menu-commands-we-can-call-from-javascript-769510, https://gist.github.com/shalakolee/df3246659d4289eb99149b9ed00a00ee). The `parent` of a page item at the top of a layer is a `Layer` with `name`, `typename` and `toString`. A page item's `blendingMode` reads and sets its blend mode with the `BlendModes` values (https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/).
`Document.views` lists the document's drawn windows with their bounds, center, zoom and screen mode (https://ai-scripting.docsforadobe.dev/jsobjref/View/). Zoom follows each window's displayed percentage, including display density with Display Print Size at 100% Zoom enabled; bounds retain the physical camera scale. View objects keep their targets when windows are renumbered. View changes run no command, add no undo step, and remain when a script fails. A center outside the canvas after coordinate conversion throws a `RangeError`. The other classes are not there yet. `crates/engine/src/tests/script_dom.rs`.
`Document.views` lists the document's drawn windows with their bounds, center, zoom and screen mode (https://ai-scripting.docsforadobe.dev/jsobjref/View/). Zoom follows each window's displayed percentage, including display density with Display Print Size at 100% Zoom enabled; bounds retain the physical camera scale. View objects keep their targets when windows are renumbered. View changes run no command, add no undo step, and remain when a script fails. A center outside the canvas after coordinate conversion throws a `RangeError`. Type and the other classes are not there yet. `crates/engine/src/tests/script_dom.rs`.
- Scripts: `app.redraw()` (https://ai-scripting.docsforadobe.dev/jsobjref/Application/) returns without changing the documents or adding an undo step; the app goes on drawing the documents as they were before the run until the run ends. VectorCraft's own rule. `crates/engine/src/tests/script_dom.rs`.
- Scripts: a document's variables and data sets, the variables its page items are bound to, Lock Variables, and importing and exporting a variable library through a `File`, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Variables/, https://ai-scripting.docsforadobe.dev/jsobjref/Variable/, https://ai-scripting.docsforadobe.dev/jsobjref/Datasets/ and https://ai-scripting.docsforadobe.dev/jsobjref/Dataset/ describe them; `variable.setBinding` binds one object for one slot, and `dataset.update {name}` updates a data set that is not the active one (`docs/mcp.md`). `crates/engine/src/tests/script_variables.rs`.
- Scripts: `app.selectTool(name)` makes the named tool the current tool when the run ends without an error (https://community.adobe.com/questions-652/what-s-new-in-illustrator-scripting-cc2020-769942). `crates/engine/src/tests/script_dom.rs`.
- Scripts: `app.doScript(action, set, dialogs?)` plays an action of the Actions panel inside the run, as the `DoScript` method of the scripting reference https://web.archive.org/web/20170621180804/https://wwwimages.adobe.com/content/dam/Adobe/en/devnet/illustrator/sdk/CC2015_3/Illustrator%20VBScript%20Reference.pdf describes it: its steps join the run's one undo step and keep the script's file limits, and a stop or a step a script may not run, or that plays an action or runs a script, is refused before any step runs (`docs/mcp.md`). `app.loadAction` and `app.unloadAction` are not there yet. `crates/engine/src/tests/script_actions.rs`.
- Scripts: `app.doScript(action, set, dialogs?)` plays an action of the Actions panel inside the run, as the `DoScript` method of the scripting reference https://web.archive.org/web/20170621180804/https://wwwimages.adobe.com/content/dam/Adobe/en/devnet/illustrator/sdk/CC2015_3/Illustrator%20VBScript%20Reference.pdf describes it: its steps join the run's one undo step and keep the script's file limits, and a stop or a step a script may not run, or that plays an action or runs a script, is refused before any step runs (`docs/mcp.md`). After deletion of an artboard chosen by the script, playback uses the same fallback as script coordinates, `getActiveArtboardIndex()` and the view; File > Revert discards that stored choice. `app.loadAction` and `app.unloadAction` are not there yet. `crates/engine/src/tests/script_actions.rs`.
- Scripts: Window › Script Console shows each run's `$.write` and `$.writeln` output, `vc.log` entries, uncaught error with the script's name, line and column, and a report of its time, host calls and slowest commands, keeping at most 2,048 lines and counting the lines it dropped. `script.run`'s report carries the same data, and `script.console`, `script.console.clear` and `ui.copyScriptConsole` read, clear and copy it. `crates/engine/src/tests/script_console.rs`.
- Scripts: the status bar translates its own words around a failed run's error and the app's own error messages, and shows text the script threw itself (a value, an error it made, or an error whose name or message it changed) as it is, even when that text reads like one of the app's messages. `script.run`'s report gives `messageOrigin` (`script` or `built-in`), and the advice about objects other applications give their scripts follows only the app's own reference errors. VectorCraft's own rule. `crates/js/src/interp_tests.rs`, `crates/engine/src/tests/script_run.rs`, `crates/ui-egui/src/chrome/tests.rs`.
- Scripts: the warning before File › Scripts › Other Script… runs a script lists what `script.check` finds the script reaches outside the document (files it writes, moves or deletes, other apps, the network, native code, environment variables, preferences, code the checker can't read), the files and dialogs it needs, features only the reference app has and its included files, read without running it. It says when the script is too large to check, compiled, not a script or not read, and when a list was cut short. VectorCraft's own rule. `crates/ui-egui/src/tests/script_run.rs`.
+2 -2
View File
@@ -29,7 +29,7 @@
**Layers appearance marker (#8710):** A small hollow diamond marks an item's own appearance or transparency, distinct from the double ring for targeting and the selected-art square. A tooltip explains the current marker state. Existing targeting, dragging and Alt-copy behavior are retained. This follow-up depends on Hassan1305's #8757 and preserves its visible target ring and four-state coverage. Source and focused native Layers-panel coverage are in `crates/ui-egui/src/panels/layers/cells.rs`, `crates/ui-egui/src/panels/layers/rows.rs` and `crates/ui-egui/src/panels/layers/tests.rs`; runtime validation is pending. Scores and estimates are unchanged.
**Tools toolbar search (#8758):** Search sits beside Edit Toolbar in the two-column Tools panel and above it in one column. It opens the existing command palette, which finds and activates tools, and is disabled while a modal window is open. Edit Toolbar keeps the existing native customization drawer and focus opener. Focused toolbar-frame cases in `crates/ui-egui/src/toolbar/tests.rs` cover layout, actual search/tool activation, dialog admission and retained document/history/customization behavior. Scores and estimates are unchanged.
**Tools toolbar search (#8758):** Search sits beside Edit Toolbar in the two-column Tools panel. A one-column Tools panel shows Edit Toolbar alone, so the default rail fits a 1000 pt window; Search there is in the title bar, Help › Search Commands… and its shortcut. It opens the existing command palette, which finds and activates tools, and is disabled while a modal window is open. Edit Toolbar keeps the existing native customization drawer and focus opener. Focused toolbar-frame cases in `crates/ui-egui/src/toolbar/tests.rs` cover layout, actual search/tool activation, dialog admission and retained document/history/customization behavior. Scores and estimates are unchanged.
**Scissors cut-point preview (#8655):** A native point marker shows the anchor or position on a curve that the current Scissors click targets, including the existing snapping rules. Hovering changes no artwork; an ineligible or stale hover has no marker. Existing cut and Alt Add Anchor behavior are retained. Focused tool and Session regressions live in `crates/tools/src/draw2/anchor/tests.rs` and `crates/engine/tests/it/scissors_snap.rs`. Scores and estimates are unchanged.
@@ -497,7 +497,7 @@ next unit in the order a right-click on a ruler lists them, from Feet back to Po
| The double triangle at the right end of a panel's tab strip cycles the panel's display sizes, the states its Show/Hide Options (and Transparency's Show/Hide Thumbnails) panel-menu items set ([archived user guide](https://web.archive.org/web/20220911143322/https://helpx.adobe.com/pdf/cs6/illustrator_reference.pdf#page=189), Transparency; [archived user guide](https://web.archive.org/web/20210601162814/https://helpx.adobe.com/pdf/illustrator_reference.pdf#page=479), Character and Paragraph) | done | `window.panel.cycleOptions {panel}`; Align, Attributes, Character, Color, Flattener Preview, Gradient, Info, Paragraph, Stroke, Transform and Transparency; the order of the sizes, the glyph and where it sits are VectorCraft's own (#3041) | unknown |
| Panels outside the app window (another monitor) | done | floating groups in OS windows of their own on the desktop (#4135) | unknown |
| Edit Toolbar (•••): the All Tools drawer opens beside the toolbar by its button (Escape or a click outside closes it), dims the tools already in the toolbar; while it is open, tools drag from it onto the toolbar (between two tools, or onto one to join its group), from the toolbar into it, and within the toolbar; each toolbar keeps its edits | done | #1018; `window.editToolbar`, `toolbar.addTool`/`removeTool`/`reset`; the drawer's Reset (Illustrator has it in a drawer menu); dragging a toolbar button moves the tool it shows, not its whole group; tool flyouts are as wide as their longest translated name and shortcut need (#1616) | unknown |
| Search beside Edit Toolbar (#8758) | implemented | Existing tool-aware command palette; search-left/edit-right in two columns and stacked in one, dialog-disabled, with retained customization. `crates/ui-egui/src/toolbar/tests.rs`. | unknown |
| Search beside Edit Toolbar (#8758) | implemented | Existing tool-aware command palette; search-left/edit-right in two columns and Edit Toolbar alone in one, dialog-disabled, with retained customization. `crates/ui-egui/src/toolbar/tests.rs`. | unknown |
| Window › Toolbars › New Toolbar… (also in the All Tools drawer's menu): a name and OK make a blank floating toolbar, listed under Window › Toolbars (its item shows or hides it); its title bar moves it, its × hides it and its double arrow shows its tools in one column or two; its ••• button opens the All Tools drawer beside it to fill it; kept with the workspace it was made in | done | #1759 in part; `window.toolbar.new`, `window.toolbar.custom`, `window.toolbar.list`, the `toolbar` param of `window.toolbarColumns`, `window.editToolbar` and `toolbar.addTool`/`removeTool`/`reset` | unknown |
| Window › Toolbars › Manage Toolbars… (also in the All Tools drawer's menu): the dialog lists the toolbars made with New Toolbar; a new name typed for the selected one renames it, + copies it (none selected: a blank toolbar) and the trash can deletes it; the changes stay in the workspace | done | #1759 in part; `window.toolbar.manage`, `window.toolbar.rename`, `window.toolbar.duplicate`, `window.toolbar.delete` | unknown |
| Quick Image Trace presets trace at once and leave the panel as it was; the Image Trace button (Control bar, Properties) opens the editable controls | done | Per the public documentation, choosing a preset traces the image with it straight away, and the panel is opened with the Image Trace button in the Control panel or in Properties' Image Trace section (<https://helpx.adobe.com/illustrator/using/image-trace-results-optimization.html>). The controls show Threshold, Paths, Corners and Noise with Advanced open; `panels/image_trace.rs` headless tests (`a_quick_trace_leaves_the_panel_as_it_was`, `sketch_quick_trace_reveals_all_adjustments_and_keeps_the_source` for the button's route). No algorithm parity claim. | unknown |