Merge main into fix/retrace-keeps-note-and-tags

This commit is contained in:
dotCooCoo committed 2026-12-03 02:03:44 -08:00
commit 21f219213f
68 files changed
+7288 -493

No files matched your search

Generated
+6 -6
View File
@@ -4,9 +4,9 @@ version = 4
[[package]]
name = "accesskit"
version = "0.25.1"
version = "0.25.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ad442f58ee04714aaa0ba0a2768c1ea1935b29507bb22ddece8cbbc76db02932"
checksum = "4e883d1d28c5fd5568c79ed2d2bd48d9f2fd3945c8974ed0f53690ceddb051be"
dependencies = [
"uuid",
]
@@ -27,9 +27,9 @@ dependencies = [
[[package]]
name = "accesskit_consumer"
version = "0.39.1"
version = "0.39.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8a45e2bb300bea6d5f33a82c3e051c3ddc6f41c209750f68a0acbe991a284344"
checksum = "f3da8f27636015191b2264ee1df681503170a632cafd832fdc1edfdd4e3a2fd3"
dependencies = [
"accesskit",
"hashbrown 0.17.1",
@@ -51,9 +51,9 @@ dependencies = [
[[package]]
name = "accesskit_macos"
version = "0.27.1"
version = "0.27.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5701624bf6a11efb6d4c8e922bf44126ed96250e5faa9a7a0468c979635839a4"
checksum = "123828ceeec755b05255e3976cb0852993202de98a0626c97dd8d34246991f84"
dependencies = [
"accesskit",
"accesskit_consumer",
+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:?}");
}
}
+6
View File
@@ -140,6 +140,12 @@ fn units_choose_the_default_scale() {
assert_eq!((i.unit, i.units.as_str()), (Unit::Millimeters, name));
assert!((i.scale * pt - 72.0 / 25.4).abs() < 1e-9, "{name}: 1 mm is {} units", i.scale);
}
// Miles and kilometers have no unit of their own, so they read as millimeters at their scale.
for (code, name, pt) in [("3", "Miles", 72.0 * 63_360.0), ("7", "Kilometers", 72.0 / 0.0254 * 1e3)] {
let i = info(&drawing(&[(9, "$INSUNITS"), (70, code)], &[], &[], LINE)).unwrap();
assert_eq!((i.unit, i.units.as_str()), (Unit::Millimeters, name));
assert!((i.scale * pt - 72.0 / 25.4).abs() < 1e-9, "{name}: 1 mm is {} units", i.scale);
}
let survey_in = open(&drawing(&[(9, "$INSUNITS"), (70, "22")], &[], &[], LINE), &ImportOptions::default()).document;
assert!((survey_in.artboards[0].rect.width() - 7200.0144000288).abs() < 1e-6, "{:?}", survey_in.artboards[0].rect);
let imperial = info(&drawing(&[(9, "$MEASUREMENT"), (70, "0")], &[], &[], LINE)).unwrap();
+5
View File
@@ -197,6 +197,11 @@ mod tests {
assert_eq!(Harmony::SplitComplementary.id(), "splitComplementary");
assert_eq!(Harmony::HighContrast3.id(), "highContrast3");
assert_eq!(parse("square"), None);
// The labels are written here and the ids come from the framework: a few shown labels read
// back as their rules.
for h in [Harmony::LeftComplement, Harmony::Monochromatic, Harmony::Compound2, Harmony::Pentagram] {
assert_eq!(parse(label(h)), Some(h), "{}", label(h));
}
}
#[test]
+6
View File
@@ -448,6 +448,12 @@ pub(crate) fn index_by_id(specs: &[CommandSpec]) -> std::collections::HashMap<&'
/// Runs command `spec`'s implementation with `p`. A plug-in command's runs the plug-in
/// ([`plugin::run_command`]), which needs the command's id.
pub(crate) fn run_spec(s: &mut Session, spec: &CommandSpec, p: &Value) -> Result<Value> {
if matches!(spec.id, "shape.rectangle" | "shape.ellipse" | "shape.polygon" | "shape.star" | "path.create") {
return create::on_layer(s, p, spec.id, |s| (spec.run)(s, p));
}
if matches!(spec.id, "paint.setFill" | "paint.setStroke" | "stroke.set") {
return paint::object_only(s, p, spec.id, |s| (spec.run)(s, p));
}
if plugin::is_command_id(spec.id) { plugin::run_command(s, spec.id, p) } else { (spec.run)(s, p) }
}
+62 -8
View File
@@ -12,6 +12,25 @@ use super::{
};
use crate::EngineError;
pub(crate) fn on_layer(s: &mut Session, p: &Value, cmd: &str, run: impl FnOnce(&mut Session) -> Result<Value>) -> Result<Value> {
if p.get("onLayer").is_none() {
return run(s);
}
let parent = object_param(p, "onLayer", cmd)?;
let d = &s.doc()?.doc;
if let Some(id) = parent
&& !d.node(id).is_some_and(|n| n.is_layer() && d.is_editable(id))
{
return Err(bad(cmd, "onLayer must name an editable layer"));
}
let mode = std::mem::replace(&mut s.draw_mode, crate::DrawMode::Normal);
let isolation = std::mem::replace(&mut s.doc_mut()?.isolation, parent);
let result = run(s);
s.doc_mut()?.isolation = isolation;
s.draw_mode = mode;
result
}
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!(
@@ -19,7 +38,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Rectangle",
[],
None,
"{x, y, width, height, radius?: pt, rotation?: deg clockwise about the centre (0: upright)} → {id}",
"{x, y, width, height, onLayer?: layer id|null (draw normally on this layer), radius?: pt, rotation?: deg clockwise about the centre (0: upright)} → {id}",
has_doc,
rectangle
),
@@ -28,7 +47,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Ellipse",
[],
None,
"{x, y, width, height, rotation?: deg clockwise about the centre (0: upright), anchors=4 (2–1000: smooth anchors spaced evenly by angle; any count but 4 draws a plain path, not a live ellipse)} → {id}",
"{x, y, width, height, onLayer?: layer id|null (draw normally on this layer), rotation?: deg clockwise about the centre (0: upright), anchors=4 (2–1000: smooth anchors spaced evenly by angle; any count but 4 draws a plain path, not a live ellipse)} → {id}",
has_doc,
ellipse
),
@@ -37,7 +56,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Polygon",
[],
None,
"{cx, cy, radius, sides=6, rotation?: deg clockwise (0: a corner straight up)} → {id}",
"{cx, cy, radius, onLayer?: layer id|null (draw normally on this layer), sides=6, rotation?: deg clockwise (0: a corner straight up)} → {id}",
has_doc,
polygon
),
@@ -46,7 +65,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Star",
[],
None,
"{cx, cy, radius1, radius2, points=5, rotation?: deg clockwise (0: a point straight up)} → {id}",
"{cx, cy, radius1, radius2, onLayer?: layer id|null (draw normally on this layer), points=5, rotation?: deg clockwise (0: a point straight up)} → {id}",
has_doc,
star
),
@@ -137,7 +156,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Create Path",
[],
None,
"{anchors: [{x, y, in?: [x,y], out?: [x,y]}], closed?: bool, d?: SVG path data} → {id}",
"{anchors: [{x, y, in?: [x,y], out?: [x,y]}], onLayer?: layer id|null (draw normally on this layer), closed?: bool, d?: SVG path data} → {id}",
has_doc,
path_create
),
@@ -155,7 +174,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Create Text",
[],
None,
"{x, y, text, rotation?: deg clockwise about x, y (0: level), vertical?: bool = false, size?: pt 0.1..1296 (outside it: an error, and no type is made), font?: family, style? (default Regular, or the family's closest style when it has no Regular), color? (#rrggbbaa and #rgba are refused; size, font, style and color left out come from [Normal Character Style], the defaults unless the document redefined it), keepModel?: bool (as paint.setFill), area?: {width, height, fit?: none|autoHeight|shrinkText|block, fitMinPercent?, wordGap?, lineGap? (as text.areaOptions)}, placeholder?: bool (fill it with placeholder text instead, as the Type tools do with prefs placeholderText), justify?: \"auto\" (default: the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\" (point type: aligned on x, so \"center\" centres each line on the point and \"right\" ends it there; text.setStyle changes it later), leadingModel?: \"romanBaseline\"|\"emBoxTop\", charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (default: emBoxTop and emBoxCenter while the interface is in Japanese, else romanBaseline)} → {id, bounds: {x, y, width, height} (the new type's box as document.inspect reports it, after justify), overflow?: [id] (area type whose text doesn't fit its frame: the lines past it aren't drawn; left out when it fits), warning?: text (the font or style given isn't available: the type is drawn in the fallback font or the family's closest style)}; new area type gets Auto Size (fit autoHeight) when the autoSizeAreaType preference is on",
"{x, y, text, parent?: id (a shown, unlocked layer or group: the type goes on top of its contents, whatever the drawing mode; default: where the Type tools put new type), rotation?: deg clockwise about x, y (0: level), vertical?: bool = false, size?: pt 0.1..1296 (outside it: an error, and no type is made), font?: family, style? (default Regular, or the family's closest style when it has no Regular), color? (#rrggbbaa and #rgba are refused; size, font, style and color left out come from [Normal Character Style], the defaults unless the document redefined it), keepModel?: bool (as paint.setFill), area?: {width, height, fit?: none|autoHeight|shrinkText|block, fitMinPercent?, wordGap?, lineGap? (as text.areaOptions)}, placeholder?: bool (fill it with placeholder text instead, as the Type tools do with prefs placeholderText), justify?: \"auto\" (default: the start of each paragraph's direction)|\"left\"|\"center\"|\"right\"|\"justifyAll\" (point type: aligned on x, so \"center\" centres each line on the point and \"right\" ends it there; text.setStyle changes it later), leadingModel?: \"romanBaseline\"|\"emBoxTop\", charAlign?: \"romanBaseline\"|\"emBoxTop\"|\"emBoxCenter\"|\"emBoxBottom\"|\"icfTop\"|\"icfBottom\" (default: emBoxTop and emBoxCenter while the interface is in Japanese, else romanBaseline)} → {id, bounds: {x, y, width, height} (the new type's box as document.inspect reports it, after justify), overflow?: [id] (area type whose text doesn't fit its frame: the lines past it aren't drawn; left out when it fits), warning?: text (the font or style given isn't available: the type is drawn in the fallback font or the family's closest style)}; new area type gets Auto Size (fit autoHeight) when the autoSizeAreaType preference is on",
has_doc,
text_create
),
@@ -956,7 +975,38 @@ fn path_create(s: &mut Session, p: &Value) -> Result<Value> {
add_look(s, "Pen", path_kind(path, None), look, None)
}
/// The shown, unlocked layer or group `text.create`'s `parent` names, if it names one.
fn text_parent(s: &Session, p: &Value) -> Result<Option<NodeId>> {
const C: &str = "text.create";
let Some(parent) = object_param(p, "parent", C)? else { return Ok(None) };
let d = &s.doc()?.doc;
let Some(n) = d.node(parent) else { return Err(bad(C, format!("no layer or group {}", parent.0))) };
if !matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. }) || n.extras().graph.is_some() {
return Err(bad(C, format!("{} is not a layer or group", parent.0)));
}
if !d.is_editable(parent) {
return Err(bad(C, "the layer or group is hidden or locked"));
}
Ok(Some(parent))
}
/// New type `kind` on top of the contents of `parent`, whatever the drawing mode; selected.
fn insert_text_into(s: &mut Session, parent: NodeId, kind: NodeKind, bbox_angle: f64) -> Result<Value> {
let id = s.edit("Type", |d, sel| {
let id = d.alloc_id();
let mut n = Node::new(id, kind);
NewArt::plain(Appearance::default()).apply(d, &mut n);
super::object::align_new_object(d, &mut n);
n.bbox_angle = bbox_angle;
d.insert(Some(parent), usize::MAX, n)?;
sel.set([id]);
Ok(id)
})?;
Ok(json!({ "id": id.0 }))
}
fn text_create(s: &mut Session, p: &Value) -> Result<Value> {
let parent = text_parent(s, p)?;
let x = f64_req(p, "x", "text.create")?;
let y = f64_req(p, "y", "text.create")?;
super::paint::check_keep_model(p, "text.create")?;
@@ -993,8 +1043,12 @@ fn text_create(s: &mut Session, p: &Value) -> Result<Value> {
// Lays the text out (and sizes an Auto Size frame).
super::typecmd::refresh_bounds(&mut t);
}
let made =
insert_look_turned(s, "Type", NodeKind::Text(Box::new(t)), NewArt::plain(Appearance::default()), None, true, bbox_turn(rotation), true)?;
let made = match parent {
Some(parent) => insert_text_into(s, parent, NodeKind::Text(Box::new(t)), bbox_turn(rotation))?,
None => {
insert_look_turned(s, "Type", NodeKind::Text(Box::new(t)), NewArt::plain(Appearance::default()), None, true, bbox_turn(rotation), true)?
}
};
let id = made.get("id").and_then(Value::as_u64).map(NodeId);
let made = super::typecmd::with_bounds(s, id, made);
let mut made = super::typecmd::with_overflow(s, id.as_slice(), made);
+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);
+64 -3
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; 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; the clipping path of a clip group or clipping layer stays at its bottom: it does not move until the mask is released, and a row put below it goes just above it; a path other than a clip group's or clipping layer's clipping path also goes into a shown, unlocked compound path 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
),
@@ -1001,18 +1001,79 @@ fn move_node(s: &mut Session, p: &Value) -> Result<Value> {
let index = p.get("index").and_then(Value::as_u64).map_or(usize::MAX, index);
let d = &s.doc()?.doc;
let n = d.node(id).ok_or(EngineError::NoNode(id))?;
if !accepts(d, parent, n) {
let compound = parent.and_then(|p| d.node(p)).filter(|p| matches!(p.kind, NodeKind::Compound { .. }));
if let Some(c) = compound {
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"));
}
} else if !accepts(d, parent, n) {
return Err(bad(C, "layers go only at the top level or in layers, objects in layers and groups"));
}
// The clipping path stays at the bottom of its clip group or clipping layer.
let from = d.parent_of(id);
let clips = |p: Option<NodeId>| p.and_then(|p| d.node(p)).filter(|p| p.clips());
let is_mask = clips(from).and_then(Node::children).and_then(|c| c.first()).is_some_and(|c| c.id == id);
if is_mask && (parent != from || index != 0) {
return Err(bad(C, "the clipping path stays at the bottom of its clip group; release the clipping mask first"));
}
let index = if !is_mask && clips(parent).and_then(Node::children).is_some_and(|c| c.iter().any(|c| c.id != id)) { index.max(1) } else { index };
// An empty compound path takes the paint of the first path that goes into it: the path's own,
// or the paint of the compound path it leaves, which is what painted it.
let from_compound = d.parent_of(id).and_then(|p| d.node(p)).filter(|p| matches!(p.kind, NodeKind::Compound { .. }));
let shown = from_compound.map_or(&n.appearance, |p| &p.appearance);
let paint = compound.filter(|c| c.children().is_some_and(Vec::is_empty)).map(|c| (c.id, shown.clone()));
let into = compound.map(|c| c.id);
// A compound path that is pixel-aligned already snaps the path it takes, too.
let from_aligned = from_compound.is_some_and(|c| c.extras().pixel_aligned) || compound.is_some_and(|c| c.extras().pixel_aligned);
// A path that leaves a compound path for a layer or a group takes the compound path's paint and
// pixel alignment, as Release Compound Path gives them to its paths.
let out_of = from_compound.filter(|_| compound.is_none()).map(|c| (c.appearance.clone(), c.extras().pixel_aligned));
if let Some(what) = super::intertwine::refused_in(d, parent, n) {
return Err(bad(C, format!("{what} can't be intertwined")));
}
let live_paint = LivePaintMove::plan(d, &[id], parent, false)?;
let label = if live_paint.joins() { "Merge Live Paint" } else { "Reorder" };
let from = d.parent_of(id);
let left = super::intertwine::groups_of(d, &[id]);
s.edit(label, |d, sel| {
d.move_node(id, parent, index)?;
if let Some((c, appearance)) = paint
&& let Some(n) = d.node_mut(c)
{
n.appearance = appearance;
}
// A path in a compound path keeps no paint, live shape or pixel alignment of its own, as
// Make Compound Path leaves its paths; the compound path becomes pixel-aligned instead when
// the path was, or when the compound path it leaves was.
if let Some(c) = into {
let mut aligned = from_aligned;
if let Some(m) = d.node_mut(id) {
m.appearance = vectorcraft_doc::Appearance::default().into();
aligned |= std::mem::take(&mut m.extras_mut().pixel_aligned);
if let NodeKind::Path { live, .. } = &mut m.kind {
*live = None;
}
}
if aligned && let Some(cn) = d.node_mut(c) {
cn.extras_mut().pixel_aligned = true;
super::object::snap_if_aligned(cn);
}
}
if let Some((appearance, aligned)) = out_of
&& let Some(m) = d.node_mut(id)
{
m.appearance = appearance;
if aligned {
m.extras_mut().pixel_aligned = true;
}
}
super::intertwine::settle_members(d, &[(id, from)], &left)?;
live_paint.finish(d, sel, &[id])?;
sel.prune(d);
+4 -4
View File
@@ -395,7 +395,7 @@ impl DocSettings {
}
"rows" => {
self.rows = if replaying {
v.as_f64().map(f64::round).filter(|n| (1.0..=f64::from(MAX_ARTBOARDS)).contains(n)).map(|n| n as u32)
v.as_f64().map(f64::round).filter(|n| *n >= 1.0).map(|n| n.min(f64::from(MAX_ARTBOARDS)) as u32)
} else {
count(v)
}
@@ -605,10 +605,10 @@ fn de_artboards<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result<u
Ok(f64::deserialize(d)?.round().clamp(1.0, MAX_ARTBOARDS as f64) as u32)
}
/// A saved or Recent preset's grid rows, kept to at most [`MAX_ARTBOARDS`]; 0 (columns in their
/// place) stays 0.
/// A saved or Recent preset's grid rows, rounded and kept to 0 (columns in their place) to
/// [`MAX_ARTBOARDS`], the counts `file.new` takes.
fn de_rows<'de, D: serde::Deserializer<'de>>(d: D) -> std::result::Result<u32, D::Error> {
Ok(u32::deserialize(d)?.min(MAX_ARTBOARDS))
Ok(f64::deserialize(d)?.round().clamp(0.0, MAX_ARTBOARDS as f64) as u32)
}
/// A count `file.new` takes (artboards, columns, rows): a whole number, written `4` or `4.0`, from 1
+43
View File
@@ -105,6 +105,49 @@ pub(super) fn group(s: &mut Session, _: &Value) -> Result<Value> {
Ok(json!({ "id": gid.0 }))
}
/// `object.newGroup`: an empty group, or with `compound` an empty compound path, in a layer or a
/// group (default: the current layer), on top of its contents or at `index` (0 = bottom). The
/// 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 => 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 => 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 => 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;
let Some(n) = d.node(parent) else { return Err(bad(C, format!("no layer or group {}", parent.0))) };
if !matches!(n.kind, NodeKind::Layer { .. } | NodeKind::Group { .. }) || n.extras().graph.is_some() {
return Err(bad(C, format!("{} is not a layer or group", parent.0)));
}
if !d.is_editable(parent) {
return Err(bad(C, "the layer or group is hidden or locked"));
}
let label = if compound { "Compound Path" } else { "Group" };
let gid = s.edit(label, |d, _| {
let gid = d.alloc_id();
let clips = d.node(parent).is_some_and(Node::clips);
let index = if clips { index.max(1) } else { index };
let node = if compound {
Node::new(gid, NodeKind::Compound { children: Vec::new(), rule: vectorcraft_geom::FillRule::NonZero })
} else {
Node::group(gid, Vec::new())
};
d.insert(Some(parent), index, node)?;
Ok(gid)
})?;
Ok(json!({ "id": gid.0 }))
}
/// Put `ids` (top-level objects, in paint order) in a new group where the front-most one was.
pub(crate) fn group_nodes(d: &mut Document, ids: &[NodeId]) -> Result<NodeId> {
if ids.is_empty() {
+10 -1
View File
@@ -1,5 +1,5 @@
use super::align::{align, can_distribute, distribute, distribute_spacing};
use super::arrange::{Arrange, arrange, exit_isolation, group, hide, isolate, lock, send_to_current_layer, show_all, ungroup, unlock_all};
use super::arrange::{Arrange, arrange, exit_isolation, group, hide, isolate, lock, new_group, send_to_current_layer, show_all, ungroup, unlock_all};
use super::bounds::set_bounds;
use super::compound::{clip_edit, clip_make, clip_release, compound_make, compound_release};
use super::pixelgrid::set_pixel_aligned;
@@ -137,6 +137,15 @@ pub fn specs() -> Vec<CommandSpec> {
has_selection,
group
),
cmd!(
"object.newGroup",
"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; an omitted key takes its default; null is refused for parent, index and compound; the selection stays as it is",
has_doc,
new_group
),
cmd!(
"object.ungroup",
"Ungroup",
+17 -1
View File
@@ -42,7 +42,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Fill",
[],
None,
"{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab; #rrggbbaa and #rgba are refused), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical: the stops sweep once around the center `start`, clockwise from the vector; diamond: the stops run from the center `start` out to a square with a corner at `end`), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (as paint.editGradient; default classic), spread?: pad|repeat|reflect (as paint.editGradient; default pad), repeats?: 1..100 (as paint.editGradient; default 1), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg counter-clockwise (0: the gradient runs left to right), start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep, counterclockwise, and is an error for the other kinds; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits; an error with a conic or diamond), dither?: bool (linear, radial, conic and diamond fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md), opacity?: 0..100 (a percentage, as transparency.set's; the opacity of that fill item on each target, in the undo step of the paint, or alone without color, none, swatch or gradient, when it changes neither the defaults nor the recent colors (with New Art Has Basic Appearance off, the next shape copies the first selected object's appearance after any command, its opacity included); with no paint or a solid color, the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso take it themselves, and with another paint the fill item takes it; with no paint, a target without that fill item is left as it is (a paint given with the opacity creates the item, which then takes it, except for the color a grayscale or 1-bit image is drawn in, which creates none), and an opacity that no target takes is an error that also leaves the paint undone; type characters have no opacity of their own, so an opacity that only characters would take is an error, and so are one with nothing selected and no ids and one for an object selected in a symbol instance), ids?|id?, defaultsOnly?: bool, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear, radial, conic or diamond `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid color recolors only the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso (unless an `item` index is given or the Appearance panel's active item is a fill); while the Type tool has characters selected (and no ids, id or item are given), the paint goes to those characters only; without `item`, a Live Paint group among the targets (or inside one) takes the fill on its faces only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white; a colorized image whose link is missing takes a solid color as its new colorize color, and refuses a process color while its color is a spot color, black or white); with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's fill changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph series, the graph also stores the paint of the topmost visible fill when the command wrote that row o Line truncated
"{color?: \"#rrggbb\"|[r,g,b]|{c,m,y,k}|{gray}|{l,a,b} (CIE Lab; #rrggbbaa and #rgba are refused), none?: true, swatch?: name (a global or spot colour stays linked, so swatch edits recolour it; a tint swatch links to its base at its tint; a gradient swatch is recorded as the gradient's swatch and fits each object, keeping its aspect; the built-in \"[Registration]\" prints on every plate), tint?: 0..100 (% of a global or spot `swatch`; default 100, or a tint swatch's own), gradient?: {kind?: linear|radial|conic|diamond|freeform (conic, also accepted as angle or conical: the stops sweep once around the center `start`, clockwise from the vector; diamond: the stops run from the center `start` out to a square with a corner at `end`), method?: classic|perceptual|hue-clockwise|hue-counterclockwise (as paint.editGradient; default classic), spread?: pad|repeat|reflect (as paint.editGradient; default pad), repeats?: 1..100 (as paint.editGradient; default 1), stops?: [{offset 0..1, color, opacity? 0..1 (or 0..100), midpoint? 0.13..0.87, swatch?: global or spot colour (or tint) swatch the stop links to (its colour comes from the swatch), tint?: 0..100}] (at least 2; default white→black), angle?: deg counter-clockwise (0: the gradient runs left to right), start?: [x,y], end?: [x,y] (the vector in document coordinates, both or neither; type objects keep it in text space), aspect?: % (radial, conic and diamond; a negative one mirrors a conic's sweep, counterclockwise, and is an error for the other kinds; without start/end the gradient is placed on each object's bounds), focal?: [x,y] (radial, with start/end: the focal point, where the first stop sits; an error with a conic or diamond), dither?: bool (linear, radial, conic and diamond fills: drawn with fine noise that hides banding, and as pixels in SVG and PDF exports; strokes ignore it), swatch?: linked gradient swatch name}, item?: appearance item index|null (omitted: the Appearance panel's active item if it is a fill, else the top fill), aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md), opacity?: 0..100 (a percentage, as transparency.set's; the opacity of that fill item on each target, in the undo step of the paint, or alone without color, none, swatch or gradient, when it changes neither the defaults nor the recent colors (with New Art Has Basic Appearance off, the next shape copies the first selected object's appearance after any command, its opacity included); with no paint or a solid color, the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso take it themselves, and with another paint the fill item takes it; with no paint, a target without that fill item is left as it is (a paint given with the opacity creates the item, which then takes it, except for the color a grayscale or 1-bit image is drawn in, which creates none), and an opacity that no target takes is an error that also leaves the paint undone; type characters have no opacity of their own, so an opacity that only characters would take is an error, and so are one with nothing selected and no ids and one for an object selected in a symbol instance), ids?|id?, objectOnly?: bool (requires ids or id; keeps new-art paint, the active proxy and remembered colors), defaultsOnly?: bool, focus?: true (false keeps the active proxy), keepModel?: false (in a CMYK document, RGB colours and gradient stops are stored as CMYK unless true; Gray stays Gray), target?: \"object\"|\"contents\", span?: \"object\" (default: each target fits a gradient to its own bounds)|\"selection\" (a linear, radial, conic or diamond `gradient` without start/end is placed once on the union of the targets' bounds, so it runs across them)} sets the selection's fill and the default (new art fits a gradient to itself); a solid color recolors only the gradient mesh points picked with the Mesh tool, Direct Selection or the Lasso (unless an `item` index is given or the Appearance panel's active item is a fill); while the Type tool has characters selected (and no ids, id or item are given), the paint goes to those characters only; without `item`, a Live Paint group among the targets (or inside one) takes the fill on its faces only; without `item`, a grayscale or 1-bit image takes a solid color as the color it is drawn in (white pixels transparent; `none` takes it off; an image with an alpha channel takes only a spot color, black or white; a colorized image whose link is missing takes a solid color as its new colorize color, and refuses a process color while its color is a spot color, black or white); with an object of a dynamic symbol instance selected by Direct Selection and no ids, id or item, that object's fill changes for this instance only (solid, none, gradient or pattern). On a path directly in a graph Line truncated
has_doc,
|s, p| set_paint(s, p, true)
),
@@ -948,6 +948,22 @@ pub(crate) fn apply_paint(s: &mut Session, p: &Value, paint: Paint, fill: bool)
apply_paint_opacity(s, p, Some(paint), None, fill)
}
pub(crate) fn object_only(s: &mut Session, p: &Value, cmd: &str, run: impl FnOnce(&mut Session) -> Result<Value>) -> Result<Value> {
if !switch_or(p, "objectOnly", false, cmd)? {
return run(s);
}
if (!names(p, "ids") && !names(p, "id")) || asks_defaults_only(p) {
return Err(bad(cmd, "objectOnly needs ids or id and cannot be combined with defaultsOnly"));
}
let kept = (s.paint.clone(), s.fill_active, s.last_solid, s.last_gradient.clone(), s.recent_colors.clone(), s.pending_paint.clone());
let result = run(s);
(s.paint, s.fill_active, s.last_solid, s.last_gradient, s.recent_colors, s.pending_paint) = kept;
if result.is_ok() {
s.note_defaults_only();
}
result
}
/// [`apply_paint`] with `paint` optional, which also sets the `opacity` (0..1) of the fill (or
/// stroke) item each target takes it on, in the same undo step: the picked gradient mesh points'
/// own opacity for a fill (with no paint or a solid color), nothing on a target without that item.
+2
View File
@@ -1921,6 +1921,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()
@@ -2002,6 +2003,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() {
@@ -346,6 +346,7 @@ pub(super) const ALLOWED: &[&str] = &[
"object.mesh.movePoints",
"object.mesh.setPointColor",
"object.move",
"object.newGroup",
"object.nudge",
"object.objectsOnPath.attach",
"object.objectsOnPath.detach",
+5 -4
View File
@@ -1034,8 +1034,7 @@ fn select_anchor_items(d: &Document, sel: &mut Selection, items: Vec<(NodeId, BT
}
let mut members = Members::of(sel);
for (id, refs) in items {
// A segment pick's endpoints aren't selected anchors: start from none of them.
let segment_pick = sel.segments.remove(&id).is_some();
let endpoints = sel.segments.remove(&id).and_then(|segments| segment_endpoints(d, id, &segments, "select.anchorsMany").ok());
let all: BTreeSet<AnchorRef> =
d.node(id).and_then(|n| n.path_data()).map(|p| p.anchors().map(|(s, i, _)| (s, i)).collect()).unwrap_or_default();
// Anything but a path is selected, toggled or deselected as a whole.
@@ -1049,8 +1048,10 @@ fn select_anchor_items(d: &Document, sel: &mut Selection, items: Vec<(NodeId, BT
}
// From the anchors selected now (all of them for a path selected as a whole).
let now = match sel.partial(id) {
_ if segment_pick => BTreeSet::new(),
Some(a) => a.clone(),
Some(a) => match &endpoints {
Some(endpoints) => a.difference(endpoints).copied().collect(),
None => a.clone(),
},
None if members.contains(id) => all.clone(),
None => BTreeSet::new(),
};
+1 -1
View File
@@ -23,7 +23,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Stroke Options",
["Window", "Stroke"],
None,
"{weight?: pt, cap?: butt|round|square, join?: miter|round|bevel, miterLimit?, align?: center|inside|outside, dash?: [d,g,…]|null (a 0 dash with a round or projecting cap draws dots or squares; a new pattern keeps the current offset and alignment), dashOffset? (exact dashes only), alignDashes?: bool (true: dashes fitted to corners and path ends, every run between them holding whole periods with a dash centred on each corner and end; false, the default for a new pattern: exact lengths), startArrow?, endArrow?: Arrow|NotchedArrow|ArrowOpen|LineArrow|Barbed|Concave|DoubleArrow|HalfArrowLeft|HalfArrowRight|Chevron|Feather|Swallowtail|Triangle|TriangleOpen|TriangleReverse|TriangleBar|Kite|Leaf|Drop|Circle|CircleOpen|HalfCircle|Oval|Target|Square|SquareOpen|Tag|TagOpen|Diamond|DiamondOpen|Hexagon|HexagonOpen|Star|Cross|Plus|Bar|DoubleBar|DotOnBar|Slash|DoubleSlash|Bracket|Fork|null|{custom: name} (a custom arrowhead of the arrowheads file, stroke.arrowheads.list)|{Custom: {name, path, stop?}} (a custom head with its art, as document.inspect reports one; stop: where the stroke ends under the head, in head units back from the tip, 0..64 (otherwise, or without one, halfway along the head); refused when the path fills no area, parts thinner than a millionth of a head unit counting as none, or has more than 4096 anchors, more than 4096 subpaths or a point more than 64 head units from the tip) (HalfArrowLeft/Right: one barb, left or right of the direction the head points), arrowAlign?: \"extend\" (tip past the end point, default)|\"tip\" (tip on the end point; the stroke is shortened), profile?: \"uniform\"|\"lens\"|\"taperStart\"|\"taperEnd\"|\"pinch\"|\"teardrop\"|\"wave\"|a saved profile's name (stroke.widthProfile.list), widthPoints?, gradientMode? (as document.inspect reports them in strokeOptions, so those read back unchanged; ignored here: a custom profile is set with the Width tool, gradientMode with paint.editGradient), item?: stroke item index|null (omitted: the Appearance panel's active item if it is a stroke, else the top stroke, created when missing), ids?|id?, defaultsOnly?: bool, target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md)} Without a stroke item, type takes weight, cap, join, miterLimit, align (around its glyph outlines; the type stays live) and the dash options as its characters' stroke (every run; text.setRangeStyle `strokeOptions` styles a range), and images and symbol instances (also in groups) are left alone; a Live Paint group takes them on its edges only. With nothing selected (and no ids) they set up the next object drawn (appearance.newArt; weight always does). On a path directly in a graph series, the graph also stores a weight it changes on the topmost visible stroke (docs/mcp.md); on a graph label's stroke row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind, and on its characters the stroke options they take; on a graph's axis line, tick mark or radar ring, the graph stores the paint, weight, opacity and blend mode of its topmost visible fill and stroke rows that the edit changes, and the weight it writes to the topmost visible stroke, for every line of its kind, and not its caps, joins, dashes, alignment or arrowheads. While the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), or `defaultsOnly: true` is given (refused with ids, id or item), only the stroke for new art changes (the bucket paints edges with its color and weight) → {objects: how many objects took the stroke options}",
"{weight?: pt, cap?: butt|round|square, join?: miter|round|bevel, miterLimit?, align?: center|inside|outside, dash?: [d,g,…]|null (a 0 dash with a round or projecting cap draws dots or squares; a new pattern keeps the current offset and alignment), dashOffset? (exact dashes only), alignDashes?: bool (true: dashes fitted to corners and path ends, every run between them holding whole periods with a dash centred on each corner and end; false, the default for a new pattern: exact lengths), startArrow?, endArrow?: Arrow|NotchedArrow|ArrowOpen|LineArrow|Barbed|Concave|DoubleArrow|HalfArrowLeft|HalfArrowRight|Chevron|Feather|Swallowtail|Triangle|TriangleOpen|TriangleReverse|TriangleBar|Kite|Leaf|Drop|Circle|CircleOpen|HalfCircle|Oval|Target|Square|SquareOpen|Tag|TagOpen|Diamond|DiamondOpen|Hexagon|HexagonOpen|Star|Cross|Plus|Bar|DoubleBar|DotOnBar|Slash|DoubleSlash|Bracket|Fork|null|{custom: name} (a custom arrowhead of the arrowheads file, stroke.arrowheads.list)|{Custom: {name, path, stop?}} (a custom head with its art, as document.inspect reports one; stop: where the stroke ends under the head, in head units back from the tip, 0..64 (otherwise, or without one, halfway along the head); refused when the path fills no area, parts thinner than a millionth of a head unit counting as none, or has more than 4096 anchors, more than 4096 subpaths or a point more than 64 head units from the tip) (HalfArrowLeft/Right: one barb, left or right of the direction the head points), arrowAlign?: \"extend\" (tip past the end point, default)|\"tip\" (tip on the end point; the stroke is shortened), profile?: \"uniform\"|\"lens\"|\"taperStart\"|\"taperEnd\"|\"pinch\"|\"teardrop\"|\"wave\"|a saved profile's name (stroke.widthProfile.list), widthPoints?, gradientMode? (as document.inspect reports them in strokeOptions, so those read back unchanged; ignored here: a custom profile is set with the Width tool, gradientMode with paint.editGradient), item?: stroke item index|null (omitted: the Appearance panel's active item if it is a stroke, else the top stroke, created when missing), ids?|id?, objectOnly?: bool (requires ids or id; keeps new-art paint, the active proxy and remembered colors), defaultsOnly?: bool, target?: \"object\"|\"contents\", aligned?: bool (index and item are rows of the first target's stack: each other target edits its equal one, as the Appearance panel does for a mixed selection; with the art of a graph design in a series given first, rows of the art's stack: docs/mcp.md)} Without a stroke item, type takes weight, cap, join, miterLimit, align (around its glyph outlines; the type stays live) and the dash options as its characters' stroke (every run; text.setRangeStyle `strokeOptions` styles a range), and images and symbol instances (also in groups) are left alone; a Live Paint group takes them on its edges only. With nothing selected (and no ids) they set up the next object drawn (appearance.newArt; weight always does). On a path directly in a graph series, the graph also stores a weight it changes on the topmost visible stroke (docs/mcp.md); on a graph label's stroke row, the graph stores the label's topmost visible fill and stroke rows for every label of its kind, and on its characters the stroke options they take; on a graph's axis line, tick mark or radar ring, the graph stores the paint, weight, opacity and blend mode of its topmost visible fill and stroke rows that the edit changes, and the weight it writes to the topmost visible stroke, for every line of its kind, and not its caps, joins, dashes, alignment or arrowheads. While the Live Paint Bucket is the active tool and no ids, id or item are given (a null ids or id counts as none), or `defaultsOnly: true` is given (refused with ids, id or item), only the stroke for new art changes (the bucket paints edges with its color and weight) → {objects: how many objects took the stroke options}",
has_doc,
stroke_set
),
+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);
+227 -91
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
@@ -53,7 +54,7 @@
//! [`TOOL_NAME_PREFIX`], and the tool becomes the current tool when the run ends without an
//! error. A run that fails leaves the tool as it was.
//! - `controlBounds` is the visible bounds, widened to take in the anchors and direction points of
//! the paths in the object; a clipping group counts its clipping path only.
//! the shown paths in the object; a clip group or clipping layer takes in only its clipping path's.
//! - `Document.views` holds the document's drawn windows ([`crate::Session::window_views`]),
//! in view-number order, and none without one. View objects keep their window's identity when
//! windows are renumbered. The screen mode is the app's:
@@ -98,8 +99,12 @@ use super::{HISTORY_LOST, Host, Link, Savepoint, command, command_kept, command_
use crate::{DocState, Document, NodeId, NodeKind, Session, WindowView};
mod clipboard;
mod colors;
mod defaults;
mod images;
pub(super) mod layers;
mod matrix;
mod paths;
pub mod preferences;
mod print;
mod save_open;
@@ -109,6 +114,9 @@ mod tracing;
mod transform;
mod variables;
#[cfg(test)]
pub(crate) use paths::POINT_LOOKS;
pub use variables::{MAX_HANDLES, STALE_DATASET, STALE_VARIABLE};
/// What [`after_command`] compares with, taken before each command a script runs
@@ -122,13 +130,6 @@ pub(super) fn after_command(h: &Host, before: Option<(u64, Vec<crate::doc::DataS
variables::after_command(h, before);
}
mod colors;
mod defaults;
mod paths;
#[cfg(test)]
pub(crate) use paths::POINT_LOOKS;
/// The error for a member read or called with no document open.
pub const NO_ACTIVE_DOCUMENT: &str = "No active document";
/// The error for an object that was deleted, or that came from an earlier run.
@@ -182,6 +183,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
@@ -208,9 +217,6 @@ pub(super) struct State {
/// Each path whose points the run read, as the run last saw it, by document uid and then path
/// id ([`paths`]).
point_nodes: RefCell<std::collections::HashMap<u64, std::collections::HashMap<u64, Arc<crate::doc::Node>>>>,
/// The path whose points the object model is writing with `path.setAnchors`, the only path
/// that command changes ([`paths`]).
one_path: Cell<Option<Item>>,
/// Each document, by uid, as it was when the run last looked at all the paths in it whose
/// points it read ([`paths`]).
point_docs: RefCell<std::collections::HashMap<u64, Arc<Document>>>,
@@ -219,6 +225,21 @@ pub(super) struct State {
editing: Cell<Option<Item>>,
locked: RefCell<Vec<LockedList>>,
saving: Cell<bool>,
/// The last [`layers::ART_LISTS`] lists of art [`layers`]' collections gave, least recently
/// used first, each kept while its document is unchanged.
art: RefCell<Vec<layers::ArtList>>,
/// The last [`layers::ART_LISTS`] lists of layers `Layers` objects gave, least recently used
/// first, each kept while its document is unchanged.
layers: 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`]).
@@ -236,9 +257,9 @@ pub(super) struct State {
}
impl State {
/// The state of a run whose heap is `heap_bytes`.
pub(super) fn new(heap_bytes: usize) -> Self {
Self { preset_limit: heap_bytes as u64, ..Self::default() }
/// 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() }
}
/// Whether a call's own savepoint is open: its commands take none of their own.
@@ -267,11 +288,13 @@ impl State {
/// Runs `f`, whose commands are kept together or put back together: when `f` fails, every
/// document, the selection and the undo histories are as they were before it, with no undo step
/// and no change to the document's saved state, and the growth its commands were charged is not
/// counted.
/// counted. Point changes that wait in [`State`] are written first, so a failure in `f` does not
/// put them back.
fn atomically<T>(h: &Host, f: impl FnOnce(&Host) -> std::result::Result<T, HostError>) -> std::result::Result<T, HostError> {
if h.dom.saving.get() {
return f(h);
}
flush(h)?;
let save = Savepoint::take(&mut h.session.borrow_mut(), "edit.duplicate");
let styles = text::styles::mark(h);
let mark = h.growth_mark();
@@ -434,7 +457,7 @@ fn point_method(link: &Link, f: Member) -> HostMember {
pub(super) type Described = (String, HostMember, MemberInfo);
/// A property's or a method's result's type for `reflect`.
fn typed(data_type: &str) -> MemberInfo {
pub(super) fn typed(data_type: &str) -> MemberInfo {
MemberInfo { data_type: data_type.into(), ..MemberInfo::default() }
}
@@ -445,7 +468,8 @@ pub(super) fn returns(data_type: &str, arguments: &[(&str, &str)]) -> MemberInfo
}
/// A member the help pages list that is not available yet: reading or assigning it throws, after
/// the check that a document, page item, path point or text range `this` is still there.
/// the check that a document, layer, page item, path point, text range or `GroupItems` collection
/// `this` is still there.
/// `hasOwnProperty` is false for it, so a script that checks for the member first skips it, and
/// `reflect` leaves it out.
pub(super) fn later(link: &Link, class: &'static str, name: &'static str) -> Described {
@@ -458,7 +482,10 @@ pub(super) fn later(link: &Link, class: &'static str, name: &'static str) -> Des
"Document" => {
doc_of(&h, arg(&a, 0), "Document")?;
}
"PageItem" | "PathItem" | "TextFrame" | "PlacedItem" | "RasterItem" => {
"Layer" => {
layers::layer_of(&h, arg(&a, 0))?;
}
c if c == "PageItem" || ITEM_CLASSES.contains(&c) => {
item_of(&h, arg(&a, 0))?;
}
"PathPoint" => {
@@ -467,6 +494,9 @@ pub(super) fn later(link: &Link, class: &'static str, name: &'static str) -> Des
"TextRange" => {
text::check_range(&h, arg(&a, 0))?;
}
"GroupItems" => {
layers::check_groups(&h, arg(&a, 0))?;
}
_ => {}
}
Err(HostError::Error(message.clone()))
@@ -926,14 +956,27 @@ fn on_doc<T>(
keep_selection: bool,
f: impl FnOnce(&Host) -> std::result::Result<T, HostError>,
) -> std::result::Result<T, HostError> {
atomically(h, |h| on_doc_steps(h, uid, keep_selection, f))
on_doc_layer(h, uid, keep_selection, true, f)
}
/// The steps of [`on_doc`].
/// [`on_doc`], with `keep_layer` false for `f`s that choose the current layer (`layers.add()`,
/// `activeLayer = layer`): the selection is put back, and the layer `f` left current stays current.
fn on_doc_layer<T>(
h: &Host,
uid: u64,
keep_selection: bool,
keep_layer: bool,
f: impl FnOnce(&Host) -> std::result::Result<T, HostError>,
) -> std::result::Result<T, HostError> {
atomically(h, |h| on_doc_steps(h, uid, keep_selection, keep_layer, f))
}
/// The steps of [`on_doc_layer`].
fn on_doc_steps<T>(
h: &Host,
uid: u64,
keep_selection: bool,
keep_layer: bool,
f: impl FnOnce(&Host) -> std::result::Result<T, HostError>,
) -> std::result::Result<T, HostError> {
let (index, active, before, layer, activated) = {
@@ -947,6 +990,12 @@ fn on_doc_steps<T>(
command(h, "document.activate", &json!({"index": index}))?;
}
let r = f(h);
let layer = if keep_layer {
layer
} else {
let s = h.session.borrow();
s.active().filter(|st| st.uid == uid).map_or(layer, |st| (st.active_layer, st.highlighted_rows()))
};
let mut restored = Ok(());
if keep_selection {
let doc = {
@@ -2169,22 +2218,35 @@ fn items_doc(h: &Host, a: &[Data]) -> std::result::Result<Doc, HostError> {
}
fn items_length(h: &Host, a: &[Data]) -> Answer {
if layers::is_scoped(a, "PageItems") {
return layers::scoped_length(h, a);
}
let doc = items_doc(h, a)?;
let n = with_doc(h, doc, |_, st| page_items(h, st).map(|ids| ids.len()))?;
Ok(num(float(n as u64)))
}
fn items_typename(h: &Host, a: &[Data]) -> Answer {
if layers::is_scoped(a, "PageItems") {
return layers::scoped_typename(h, a);
}
items_doc(h, a)?;
Ok(text("PageItems"))
}
fn items_to_string(h: &Host, a: &[Data]) -> Answer {
if layers::is_scoped(a, "PageItems") {
layers::scoped_typename(h, a)?;
return Ok(text("[PageItems]"));
}
items_doc(h, a)?;
Ok(text("[PageItems]"))
}
fn items_parent(h: &Host, a: &[Data]) -> Answer {
if layers::is_scoped(a, "PageItems") {
return layers::scoped_parent(h, a);
}
let doc = items_doc(h, a)?;
Ok(doc_ref(h, doc.uid))
}
@@ -2204,6 +2266,9 @@ fn position(n: f64) -> Option<usize> {
/// number but not an array index, such as `-1` or `1.5`, reaches the indexer as a number and is
/// looked up as that name, giving `undefined` when no object has it.
fn items_at(h: &Host, a: &[Data]) -> Answer {
if layers::is_scoped(a, "PageItems") {
return layers::scoped_at(h, a);
}
let doc = items_doc(h, a)?;
match arg(a, 1) {
Data::String(_) => match items_by_name(h, a) {
@@ -2227,6 +2292,9 @@ fn item_at(h: &Host, doc: Doc, i: usize) -> Answer {
}
fn items_by_name(h: &Host, a: &[Data]) -> Answer {
if layers::is_scoped(a, "PageItems") {
return layers::scoped_by_name(h, a);
}
let doc = items_doc(h, a)?;
let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) };
items_named(h, doc, name)
@@ -2243,6 +2311,9 @@ fn items_named(h: &Host, doc: Doc, name: &str) -> Answer {
}
fn items_index(h: &Host, a: &[Data]) -> Answer {
if layers::is_scoped(a, "PageItems") {
return layers::scoped_index(h, a);
}
match arg(a, 1) {
Data::String(_) => items_by_name(h, a),
Data::Number(n) => {
@@ -2260,14 +2331,21 @@ fn items_index(h: &Host, a: &[Data]) -> Answer {
/// locked object, or one in a hidden or locked layer or group, stops it before anything is deleted,
/// and so does an object on a locked artboard.
fn items_remove_all(h: &Host, a: &[Data]) -> Answer {
if layers::is_scoped(a, "PageItems") {
return layers::scoped_remove_all(h, a);
}
let doc = items_doc(h, a)?;
let (ids, refused, on_locked) = with_doc(h, doc, |_, st| {
let (ids, refused, on_locked, released, tracing) = with_doc(h, doc, |_, st| {
let ids = top_items(&st.doc);
let whole = |id: &NodeId| editable(&st.doc, *id) && st.doc.node(*id).is_some_and(all_editable);
let refused: Vec<u64> = ids.iter().filter(|i| !whole(i)).map(|i| i.0).take(20).collect();
let locks = st.doc.locked_artboards();
let on_locked: Vec<u64> = ids.iter().filter(|i| locks.holds_id(**i)).map(|i| i.0).take(20).collect();
(ids, refused, on_locked)
// A clipping layer emptied of its art releases its mask, so art added later is not made its
// clipping path.
let released = masks_cleared_by(&st.doc, &ids);
let tracing = release_makes_tracing(&st.doc, &released, &ids);
(ids, refused, on_locked, released, tracing)
});
if !refused.is_empty() {
let list = refused.iter().map(u64::to_string).collect::<Vec<_>>().join(", ");
@@ -2277,8 +2355,11 @@ fn items_remove_all(h: &Host, a: &[Data]) -> Answer {
let list = on_locked.iter().map(u64::to_string).collect::<Vec<_>>().join(", ");
return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {list}")));
}
if tracing {
return Err(HostError::Error(NOT_A_TRACING.into()));
}
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| clear_releasing(h, &released, &json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()})))?;
}
Ok(Data::Undefined)
}
@@ -2434,8 +2515,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 {
@@ -2452,7 +2539,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)
@@ -2560,26 +2647,39 @@ fn item_visible(h: &Host, a: &[Data]) -> Answer {
bounds(h, a, true)
}
/// `controlBounds`: the visible bounds and the Bézier handles of the item's paths, zeros for an
/// object with nothing in it.
/// `controlBounds`: the visible bounds, taking in the anchors and direction handles of the paths
/// in the item.
fn item_control(h: &Host, a: &[Data]) -> Answer {
let item = this_item(h, a)?;
let (r, f) = item_rect(h, item, true)?;
let handles = with_doc(h, item.doc, |_, st| st.doc.node(item.id).and_then(handle_bounds));
match r.into_iter().chain(handles).reduce(|a, b| a.union(b)) {
Some(r) => Ok(f.bounds(h.dom.coords.get(), r)),
None => Ok(Data::Array(vec![num(0.0), num(0.0), num(0.0), num(0.0)])),
}
// An object with nothing in it reads zeros, as its other bounds do.
let (Some(r), f) = item_rect(h, item, true)? else { return Ok(Data::Array(vec![num(0.0), num(0.0), num(0.0), num(0.0)])) };
// Each object and anchor the walk visits is charged, so reading a large group's bounds again
// and again counts against the run.
let mut steps = 0u64;
let r = with_doc(h, item.doc, |_, st| st.doc.node(item.id).map_or(r, |n| take_in_handles(n, r, &mut steps)));
h.charge_call(steps)?;
Ok(f.bounds(h.dom.coords.get(), r))
}
/// The bounds of the anchors and handles of `n`'s paths: a path's own, and those of the shown
/// paths in its children (a clip group's from its clipping path).
fn handle_bounds(n: &crate::doc::Node) -> Option<Rect> {
match &n.kind {
NodeKind::Path { path, .. } => path.control_bounds(),
NodeKind::Group { children, clip: true } => children.first().and_then(|c| handle_bounds(c)),
_ => n.children().and_then(|children| children.iter().filter(|c| c.visible).filter_map(|c| handle_bounds(c)).reduce(|a, b| a.union(b))),
/// `r` with the anchors and direction handles of the shown paths in `n`, adding the objects and
/// anchors it visits to `steps`. Hidden objects, the objects in them and guides are left out, as
/// the visible bounds leave them out, and a clip group or clipping layer gives only its clipping
/// path's.
fn take_in_handles(n: &crate::doc::Node, mut r: Rect, steps: &mut u64) -> Rect {
*steps += 1;
if !n.visible || matches!(n.kind, NodeKind::Path { guide: true, .. }) {
return r;
}
for a in n.path_data().iter().flat_map(|p| p.subpaths.iter()).flat_map(|s| s.anchors.iter()) {
*steps += 1;
r = r.union_pt(a.p).union_pt(a.h_in).union_pt(a.h_out);
}
let children = n.children().map_or(&[][..], Vec::as_slice);
let children = if n.clips() { &children[..children.len().min(1)] } else { children };
for c in children {
r = take_in_handles(c, r, steps);
}
r
}
fn item_position(h: &Host, a: &[Data]) -> Answer {
@@ -2752,11 +2852,55 @@ fn item_remove(h: &Host, a: &[Data]) -> Answer {
if with_doc(h, item.doc, |_, st| st.doc.parent_of(item.id).is_some_and(|p| makes_tracing(&st.doc, p, item.id, None))) {
return Err(HostError::Error(NOT_A_TRACING.into()));
}
let released = with_doc(h, item.doc, |_, st| masks_cleared_by(&st.doc, &[item.id]));
// A clip group named as a tracing, released with an image left first, would become one too.
if with_doc(h, item.doc, |_, st| release_makes_tracing(&st.doc, &released, &[item.id])) {
return Err(HostError::Error(NOT_A_TRACING.into()));
}
// A compound path whose last path this is stays, empty, as it does after `move`.
edit_item(h, item, "edit.clear", &json!({"ids": [item.id.0], "keepEmpty": true}))?;
let params = json!({"ids": [item.id.0], "keepEmpty": true});
paths::see_all_points(h);
let kept = h.dom.editing.replace(Some(item));
let r = atomically(h, |h| on_doc(h, item.doc.uid, true, |h| clear_releasing(h, &released, &params)));
h.dom.editing.set(kept);
r?;
Ok(Data::Undefined)
}
/// The clip groups and clipping layers whose clipping path is one of `ids`. Deleting a clipping
/// path releases its mask, so the object above it does not become the clipping path.
pub(super) fn masks_cleared_by(d: &Document, ids: &[NodeId]) -> Vec<NodeId> {
ids.iter()
.filter_map(|i| {
let p = d.parent_of(*i)?;
let n = d.node(p)?;
(n.clips() && n.children()?.first().is_some_and(|c| c.id == *i)).then_some(p)
})
.collect()
}
/// Whether releasing the masks of `released` and deleting `removed` would leave one of those groups
/// an ordinary group named as a tracing with an image first in it, which would make it a tracing.
pub(super) fn release_makes_tracing(d: &Document, released: &[NodeId], removed: &[NodeId]) -> bool {
if released.is_empty() {
return false;
}
let removed: std::collections::HashSet<NodeId> = removed.iter().copied().collect();
released.iter().filter_map(|g| d.node(*g)).any(|g| {
matches!(g.kind, NodeKind::Group { .. })
&& g.name.as_deref() == Some(crate::cmd::TRACE_NAME)
&& g.children().and_then(|c| c.iter().find(|n| !removed.contains(&n.id))).is_some_and(|n| matches!(n.kind, NodeKind::Image(_)))
})
}
/// Releases the masks of `released` ([`masks_cleared_by`]), then runs `edit.clear` with `params`.
pub(super) fn clear_releasing(h: &Host, released: &[NodeId], params: &Value) -> std::result::Result<Data, HostError> {
for g in released {
command(h, "layer.clippingMask.toggle", &json!({"id": g.0}))?;
}
command(h, "edit.clear", params)
}
/// The error of `remove()` and `removeAll()` for an object on a locked artboard.
pub(super) const ON_LOCKED_ARTBOARD: &str = "cannot delete objects on a locked artboard";
@@ -2831,7 +2975,11 @@ fn destination(h: &Host, item: Item, target: &Data, how: &Data, copy: bool) -> s
}
let (parent, beside) = match how {
Placement::Top | Placement::Bottom => {
if !matches!(t.kind, NodeKind::Layer { .. } | NodeKind::Group { .. }) {
if matches!(t.kind, NodeKind::Compound { .. }) {
if !d.node(item.id).is_some_and(|n| matches!(n.kind, NodeKind::Path { guide: false, .. })) {
return Err(HostError::Error("a compound path holds only paths".into()));
}
} else if !matches!(t.kind, NodeKind::Layer { .. } | NodeKind::Group { .. }) {
return Err(HostError::Error(format!("{} cannot hold objects", typename(t).unwrap_or("Layer"))));
}
(target, None)
@@ -2919,6 +3067,19 @@ pub(super) fn clearing_makes_tracing(d: &Document, ids: &[NodeId]) -> bool {
})
}
/// Whether deleting every object in `removed` together would leave one of their parents, an
/// ordinary group named as a tracing, with an image first in it, which would make it a tracing.
pub(super) fn removal_makes_tracing(d: &Document, removed: &[NodeId]) -> bool {
let going: std::collections::HashSet<NodeId> = removed.iter().copied().collect();
let mut parents: Vec<NodeId> = removed.iter().filter_map(|i| d.parent_of(*i)).collect();
parents.sort_unstable_by_key(|p| p.0);
parents.dedup();
parents
.into_iter()
.filter(|p| named_as_tracing(d, *p))
.any(|p| d.children(Some(p)).and_then(|c| c.iter().find(|n| !going.contains(&n.id))).is_some_and(|n| matches!(n.kind, NodeKind::Image(_))))
}
/// Moves the object `id` to `to` with `node.move`, its index worked out once it has left its place.
fn place(h: &Host, doc: Doc, id: NodeId, to: &Destination) -> std::result::Result<(), HostError> {
let index = with_doc(h, doc, |_, st| {
@@ -2934,6 +3095,8 @@ fn place(h: &Host, doc: Doc, id: NodeId, to: &Destination) -> std::result::Resul
return Err(HostError::Error("a tracing's source image cannot leave its tracing".into()));
}
let clips = d.node(to.parent).is_some_and(|n| n.clips() || crate::cmd::is_trace_group(n)) && count > 0;
// The clipping path itself, put back where it is, stays the clipping path.
let mask_stays = from.is_some_and(|(p, j, _)| p == Some(to.parent) && j == 0);
let at = match (to.how, to.beside) {
(Placement::Top, _) => count,
(Placement::Bottom, _) => 0,
@@ -2945,11 +3108,19 @@ fn place(h: &Host, doc: Doc, id: NodeId, to: &Destination) -> std::result::Resul
{
i -= 1;
}
if how == Placement::Above { i + 1 } else { i }
let at = if how == Placement::Above { i + 1 } else { i };
// A place behind a clipping path is refused; an object put into the clip group
// itself goes directly above the clipping path.
if clips && at == 0 && !mask_stays {
return Err(HostError::Error("an object cannot go below a clipping mask".into()));
}
at
}
(_, None) => count,
};
let at = if clips { at.max(1) } else { at };
// Any other place for the clipping path is left to `node.move`, which refuses it.
let stays = mask_stays && at == 0;
let at = if clips && !stays { at.max(1) } else { at };
// The index `node.move` puts the object at: art stays below the ruler guides.
// This is `Node::insert_index` on the parent's children without the object, read in place
// so that no list of them is copied.
@@ -3107,21 +3278,8 @@ fn item_z_order(h: &Host, a: &[Data]) -> Answer {
Ok(Data::Undefined)
}
fn layer_name(h: &Host, a: &[Data]) -> Answer {
let Some(handle) = handle_of(arg(a, 0), "Layer") else { return Err(HostError::Type("this is not a Layer".into())) };
let [run, uid, _, _, _] = handle.as_slice() else { return Err(HostError::Type("this is not a Layer".into())) };
find_doc(h, *run, *uid).ok_or_else(|| HostError::Error(STALE_DOCUMENT.into()))?;
let (doc, id) = node_of(h, &handle).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?;
with_doc(h, doc, |_, st| st.doc.node(id).map(|n| text(n.name.clone().unwrap_or_default())).ok_or_else(|| HostError::Error(STALE_ITEM.into())))
}
fn layer_typename(h: &Host, a: &[Data]) -> Answer {
layer_name(h, a)?;
Ok(text("Layer"))
}
/// `toString()` of an object with a name: `[Class name]`, `[PathItem ]` for an object with no name.
fn named_text(class: &str, name: Answer) -> Answer {
pub(super) fn named_text(class: &str, name: Answer) -> Answer {
match name? {
Data::String(n) => Ok(text(format!("[{class} {n}]"))),
_ => Ok(text(format!("[{class} ]"))),
@@ -3136,10 +3294,6 @@ fn doc_to_string(h: &Host, a: &[Data]) -> Answer {
named_text("Document", doc_name(h, a))
}
fn layer_to_string(h: &Host, a: &[Data]) -> Answer {
named_text("Layer", layer_name(h, a))
}
/// `toString()` of an object without a name: `[Class]`.
fn class_text(name: &'static str) -> HostMember {
HostMember::Method(Rc::new(move |_| Ok(text(format!("[{name}]")))))
@@ -3332,7 +3486,8 @@ fn classes(link: &Link) -> Vec<HostClass> {
]);
document.extend(defaults::document_members(l));
document.extend(text::styles::doc_members(l));
document.extend(["layers", "artboards", "groupItems", "swatches", "symbols", "activeLayer"].into_iter().map(|m| later(l, "Document", m)));
document.extend(["swatches", "symbols"].into_iter().map(|m| later(l, "Document", m)));
document.extend(layers::document_members(l));
document.extend(variables::document_members(l));
document.extend(save_open::document_members(l));
document.extend(print::document_members(l));
@@ -3371,7 +3526,7 @@ fn classes(link: &Link) -> Vec<HostClass> {
named(vec![
("typename", get(l, items_typename), typed("string")),
("length", get(l, items_length), typed("number")),
("parent", get(l, items_parent), typed("Document")),
("parent", get(l, items_parent), typed("*")),
("index", method(l, items_index), returns("PageItem", &[("itemKey", "*")])),
("getByName", method(l, items_by_name), returns("PageItem", &[("name", "string")])),
("removeAll", method(l, items_remove_all), returns("undefined", &[])),
@@ -3475,28 +3630,18 @@ fn classes(link: &Link) -> Vec<HostClass> {
),
),
]);
page_item.extend(layers::page_item_members(l));
page_item.extend(
[
"artworkKnockout",
"isIsolated",
"layer",
"pixelAligned",
"sliced",
"uRL",
"uuid",
"wrapInside",
"wrapOffset",
"wrapped",
"bringInPerspective",
]
.into_iter()
.map(|m| later(l, "PageItem", m)),
["artworkKnockout", "isIsolated", "pixelAligned", "sliced", "uRL", "uuid", "wrapInside", "wrapOffset", "wrapped", "bringInPerspective"]
.into_iter()
.map(|m| later(l, "PageItem", m)),
);
page_item.extend(variables::page_item_members(l));
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));
}
@@ -3506,21 +3651,12 @@ fn classes(link: &Link) -> Vec<HostClass> {
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));
classes.extend(save_open::classes(l));
classes.extend(print::classes(l));
classes.push(class(
"Layer",
None,
named(vec![
("typename", get(l, layer_typename), typed("string")),
("name", get(l, layer_name), typed("string")),
("toString", method(l, layer_to_string), returns("string", &[])),
]),
None,
));
classes.extend(tags::classes(l));
classes
}
+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")),
File diff suppressed because it is too large. Load diff
+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 {
+251 -132
View File
@@ -17,7 +17,8 @@
//! - A change to the geometry or paint of a path that is hidden or locked, or that is in a hidden
//! or locked layer or group, or that is on a locked artboard, throws `Cannot edit` with nothing
//! changed, and `pathItems.removeAll()` deletes nothing when one of the paths is on a locked
//! artboard.
//! artboard. A point assigned whose x or y is more than `MAX_COORD` from the origin throws a
//! range error when it is assigned.
//! - A path in a compound path or compound shape reads that owner's paint, which the paint
//! commands change in its place, and a gradient that `filled = true` gives it is placed on that
//! owner's bounds. A paint or stroke change leaves the paint for new art, the active proxy and
@@ -52,9 +53,7 @@
//! throws an error that says it is not available yet on a path inside a compound path, throws
//! `Cannot edit` on a path that cannot be edited or selected, and throws an error while guides
//! are locked; assigning the value the path has runs no command.
//! - The transforms take one setting for fill and stroke patterns, so `changeFillPatterns` and
//! `changeStrokePattern` given as different values throw an error; gradients move with the art,
//! so `changeFillGradients` false throws an error that says it is not available yet.
//! - The transforms are `PageItem`'s, with their rules in [`super::transform`].
use std::rc::Rc;
use std::sync::Arc;
@@ -69,9 +68,9 @@ use vectorcraft_js::{Data, HostClass, HostError, HostItem, HostMember, MemberInf
use vectorcraft_tools::params::gradient_params;
use super::{
Answer, Coords, Described, Doc, Item, Link, NOT_FOUND, ON_LOCKED_ARTBOARD, STALE_ITEM, arg, boolean, class, colors, command, command_value,
coordinate, doc_of, edit_item, editable, find_doc, float, frame, get, given, handle_of, id_of, id_parts, item_of, later, method, named, num,
number, on_doc, pair, point, point_get, point_method, point_property, property, returns, this_doc, typed, whole, with_doc,
Answer, Coords, Described, Doc, Item, Link, NOT_FOUND, ON_LOCKED_ARTBOARD, STALE_ITEM, arg, boolean, class, colors, command, coordinate, doc_of,
edit_item, editable, find_doc, float, frame, get, given, handle_of, id_of, item_of, later, method, named, num, number, on_doc, pair, point,
point_get, point_method, point_property, property, returns, this_doc, typed, whole, with_doc,
};
use crate::{DocState, NodeId, NodeKind};
@@ -108,16 +107,27 @@ fn cannot_edit(id: NodeId) -> HostError {
HostError::Error(format!("Cannot edit PathItem {}: it, or a layer or group it is in, is hidden or locked", id.0))
}
/// Refuses a change to the path `id` that is hidden or locked, is in a hidden or locked layer or
/// group ([`cannot_edit`]), or is on a locked artboard, as the PageItem setters refuse one.
fn refuse_path_edit(h: &super::Host, st: &DocState, id: NodeId) -> std::result::Result<(), HostError> {
/// The `Cannot edit` error for the path `id` of `st` when it, or a layer or group it is in, is
/// hidden or locked, or it is on a locked artboard.
fn protected(h: &super::Host, st: &DocState, id: NodeId) -> Option<HostError> {
if !editable(&st.doc, id) {
return Err(cannot_edit(id));
Some(cannot_edit(id))
} else if super::on_locked_artboard(h, st, id) {
Some(HostError::Error(format!("Cannot edit PathItem {}: it is on a locked artboard", id.0)))
} else if h.session.borrow().menu.guides_locked && st.doc.node(id).is_some_and(|n| matches!(n.kind, NodeKind::Path { guide: true, .. })) {
Some(HostError::Error(format!("Cannot edit PathItem {}: guides are locked", id.0)))
} else {
None
}
if super::on_locked_artboard(h, st, id) {
return Err(HostError::Error(format!("Cannot edit PathItem {}: it is on a locked artboard", id.0)));
}
/// `p`, a point the script assigned, whose x and y must each be within [`crate::MAX_COORD`] of the origin.
fn in_canvas(p: Point, what: &str) -> std::result::Result<Point, HostError> {
if p.x.abs() <= crate::MAX_COORD && p.y.abs() <= crate::MAX_COORD {
Ok(p)
} else {
Err(HostError::Range(format!("{what} is outside the canvas")))
}
Ok(())
}
/// The path `d` names, which must still be in its document.
@@ -131,9 +141,12 @@ fn this_path(h: &super::Host, a: &[Data]) -> std::result::Result<Item, HostError
path_of(h, arg(a, 0))
}
/// The path of the run `run`, document `uid` and id parts `high` and `low`, as a handle gives them.
fn path_at(h: &super::Host, run: f64, uid: f64, high: f64, low: f64) -> std::result::Result<Item, HostError> {
/// The path of the run `run`, document `uid`, id parts `high` and `low` and revert count `reverts`, as a handle gives them.
fn path_at(h: &super::Host, run: f64, uid: f64, high: f64, low: f64, reverts: f64) -> std::result::Result<Item, HostError> {
let doc = find_doc(h, run, uid).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?;
if with_doc(h, doc, |_, st| Some(st.reverts) != whole(reverts)) {
return Err(HostError::Error(STALE_ITEM.into()));
}
let id = id_of(high, low).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?;
path_of(h, &path_ref(h, Item { doc, id }))
}
@@ -149,12 +162,10 @@ fn read_path<T>(h: &super::Host, item: Item, f: impl FnOnce(&DocState, &crate::d
})
}
/// A `PathItem` handle for `item`, in the form `item_of` reads (with the document's revert count).
fn path_ref(h: &super::Host, item: Item) -> Data {
let s = h.session.borrow();
match s.documents().iter().find(|d| d.uid == item.doc.uid) {
Some(st) => host_ref("PathItem", &super::node_handle(h, st, item.id)),
None => Data::Null,
}
let handle = with_doc(h, item.doc, |_, st| super::node_handle(h, st, item.id));
host_ref("PathItem", &handle)
}
/// The index of the first point of each subpath of `subs`, followed by the number of points.
@@ -219,6 +230,8 @@ fn points_of(h: &super::Host, item: Item) -> std::result::Result<usize, HostErro
/// The subpath and the place in it of point `i`, among the subpaths `subs`.
fn locate(subs: &[SubPath], mut i: usize) -> Option<(usize, usize)> {
for (s, sp) in subs.iter().enumerate() {
#[cfg(test)]
tests::LOCATE_STEPS.with(|steps| steps.set(steps.get() + 1));
if i < sp.anchors.len() {
return Some((s, i));
}
@@ -248,7 +261,7 @@ fn read_points<T>(h: &super::Host, item: Item, f: impl FnOnce(&[SubPath]) -> T)
/// Changes the subpaths of the path of `item` with `f`. The change waits in [`super::State`] with
/// the path's other point changes until [`flush`] writes them. The first change of a path writes
/// the waiting changes of another path first, and throws `Cannot edit` when the path is hidden or
/// locked or is on a locked artboard ([`refuse_path_edit`]), unless it changes nothing. A path
/// locked or is on a locked artboard ([`protected`]), unless it changes nothing. A path
/// that is aligned to the pixel grid, or is in an object that is, is written at once, so that its
/// points read as the grid snaps them.
fn edit_points<T>(h: &super::Host, item: Item, f: impl FnOnce(&mut Vec<SubPath>) -> T) -> std::result::Result<T, HostError> {
@@ -264,10 +277,13 @@ fn edit_points<T>(h: &super::Host, item: Item, f: impl FnOnce(&mut Vec<SubPath>)
let (same, refused, aligned) = read_path(h, item, |st, _, pd| {
let d = &st.doc;
let aligned = d.ancestry(item.id).is_some_and(|a| a.iter().chain([&item.id]).any(|i| d.node(*i).is_some_and(|n| n.extras().pixel_aligned)));
(pd.subpaths == subs, refuse_path_edit(h, st, item.id), aligned)
let same = pd.subpaths == subs;
(same, if same { None } else { protected(h, st, item.id) }, aligned)
})?;
if !same {
refused?;
if let Some(e) = refused {
return Err(e);
}
*h.dom.pending.borrow_mut() = Some((item, subs));
if aligned {
flush(h)?;
@@ -325,12 +341,29 @@ pub(super) fn flush(h: &super::Host) -> std::result::Result<(), HostError> {
}
let subpaths: Vec<Value> =
subs.iter().map(|sp| json!({"anchors": sp.anchors.iter().map(anchor_json).collect::<Vec<_>>(), "closed": sp.closed})).collect();
// Changes made before this one are looked at in full first.
see_all_points(h);
let kept = h.dom.one_path.replace(Some(item));
let r = edit_item(h, item, "path.setAnchors", &json!({"id": item.id.0, "subpaths": subpaths}));
h.dom.one_path.set(kept);
r?;
super::atomically(h, |h| {
if let Some(st) = h.session.borrow_mut().document_mut(item.doc.uid) {
let selection = &mut st.selection;
if let Some(anchors) = selection.anchors.get_mut(&item.id) {
anchors.retain(|&(s, i)| subs.get(s).is_some_and(|sp| i < sp.anchors.len()));
}
if let Some(segments) = selection.segments.get_mut(&item.id) {
segments.retain(|&(s, i)| subs.get(s).is_some_and(|sp| i < sp.segment_count()));
if segments.is_empty() {
selection.segments.remove(&item.id);
}
}
if selection.key_anchor.is_some_and(|(id, (s, i))| id == item.id && !subs.get(s).is_some_and(|sp| i < sp.anchors.len())) {
selection.key_anchor = None;
}
if (selection.contains(item.id) || selection.anchors.contains_key(&item.id) || selection.segments.contains_key(&item.id))
&& (selection.anchors.get(&item.id).is_some_and(|a| a.is_empty()) || subs.iter().all(|sp| sp.anchors.is_empty()))
{
selection.remove(item.id);
}
}
edit_item(h, item, "path.setAnchors", &json!({"id": item.id.0, "subpaths": subpaths}))
})?;
Ok(())
}
@@ -340,26 +373,36 @@ fn paint_owner<'a>(d: &'a crate::Document, id: NodeId, n: &'a crate::doc::Node)
d.parent_of(id).and_then(|p| d.node(p)).filter(|p| matches!(p.kind, NodeKind::Compound { .. }) || p.is_compound_shape()).unwrap_or(n)
}
/// Runs `f` with the drawing mode set to normal, so that the paths it makes go on top of the active
/// layer, then puts the drawing mode back.
fn drawing_normally<T>(h: &super::Host, f: impl FnOnce() -> T) -> T {
let kept = std::mem::replace(&mut h.session.borrow_mut().draw_mode, crate::DrawMode::Normal);
let r = f();
h.session.borrow_mut().draw_mode = kept;
r
/// Runs a path creation command with its layer placement recorded.
fn drawing_normally(h: &super::Host, parent: Option<NodeId>, id: &str, params: &Value) -> std::result::Result<(Data, Value), HostError> {
let mut params = params.clone();
params["onLayer"] = json!(parent.map(|p| p.0));
super::command_value(h, id, &params)
}
/// Runs `id` with `params` and `ids: [item]` (unless `params` names its `ids`) on the item, which
/// must be one the user could edit ([`refuse_path_edit`]).
/// must be one the user could edit ([`protected`]).
/// The paint for new art, the active Fill or Stroke proxy, the last color and gradient and the
/// recent colors, which `paint.setFill`, `paint.setStroke` and `stroke.set` also set, are put
/// back afterwards, so the edit changes only the path.
fn edit_path(h: &super::Host, item: Item, id: &str, mut params: Value) -> std::result::Result<Data, HostError> {
with_doc(h, item.doc, |_, st| refuse_path_edit(h, st, item.id))?;
if let Some(e) = with_doc(h, item.doc, |_, st| protected(h, st, item.id)) {
return Err(e);
}
if let Some(o) = params.as_object_mut() {
o.entry("ids").or_insert_with(|| json!([item.id.0]));
if matches!(id, "paint.setFill" | "paint.setStroke" | "stroke.set") {
o.insert("objectOnly".into(), json!(true));
}
}
keeping_paint(h, || edit_item(h, item, id, &params))
let result = keeping_paint(h, || edit_item(h, item, id, &params))?;
let count = if id == "object.setOverprint" { "changed" } else { "objects" };
if matches!(id, "paint.setFill" | "paint.setStroke" | "stroke.set" | "object.setOverprint")
&& matches!(&result, Data::Object(o) if o.iter().any(|(k, v)| k == count && *v == Data::Number(0.0)))
{
return Err(HostError::Error(format!("Cannot edit PathItem {}: {id} did not change the path", item.id.0)));
}
Ok(result)
}
/// Runs `f`, then puts back the paint for new art, the active Fill or Stroke proxy, the last color
@@ -397,21 +440,33 @@ pub(super) fn doc_path_items(h: &super::Host, a: &[Data]) -> Answer {
}
fn items_doc(h: &super::Host, a: &[Data]) -> std::result::Result<Doc, HostError> {
if super::layers::is_scoped(a, "PathItems") {
return Err(HostError::Error("creating paths in a compound path is not available yet; move a path into it".into()));
}
doc_of(h, arg(a, 0), "PathItems")
}
/// `typename` of the paths of a document that is still open.
fn items_typename(h: &super::Host, a: &[Data]) -> Answer {
if super::layers::is_scoped(a, "PathItems") {
return super::layers::scoped_typename(h, a);
}
items_doc(h, a)?;
Ok(Data::String("PathItems".into()))
}
fn items_length(h: &super::Host, a: &[Data]) -> Answer {
if super::layers::is_scoped(a, "PathItems") {
return super::layers::scoped_length(h, a);
}
let doc = items_doc(h, a)?;
Ok(num(float(with_doc(h, doc, |_, st| path_items(h, st).map(|ids| ids.len()))? as u64)))
}
fn items_parent(h: &super::Host, a: &[Data]) -> Answer {
if super::layers::is_scoped(a, "PathItems") {
return super::layers::scoped_parent(h, a);
}
let doc = items_doc(h, a)?;
Ok(host_ref("Document", &[float(h.run), float(doc.uid)]))
}
@@ -420,6 +475,9 @@ fn items_parent(h: &super::Host, a: &[Data]) -> Answer {
/// number but not an array index, such as `-1` or `1.5`, reaches the indexer as a number and is
/// looked up as that name, giving `undefined` when no path has it.
fn items_at(h: &super::Host, a: &[Data]) -> Answer {
if super::layers::is_scoped(a, "PathItems") {
return super::layers::scoped_at(h, a);
}
let doc = items_doc(h, a)?;
match arg(a, 1) {
Data::String(_) => match items_by_name(h, a) {
@@ -443,6 +501,9 @@ fn item_at(h: &super::Host, doc: Doc, i: usize) -> Answer {
}
fn items_by_name(h: &super::Host, a: &[Data]) -> Answer {
if super::layers::is_scoped(a, "PathItems") {
return super::layers::scoped_by_name(h, a);
}
let doc = items_doc(h, a)?;
let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) };
items_named(h, doc, name)
@@ -459,6 +520,9 @@ fn items_named(h: &super::Host, doc: Doc, name: &str) -> Answer {
}
fn items_index(h: &super::Host, a: &[Data]) -> Answer {
if super::layers::is_scoped(a, "PathItems") {
return super::layers::scoped_index(h, a);
}
match arg(a, 1) {
Data::String(_) => items_by_name(h, a),
Data::Number(n) => {
@@ -477,9 +541,17 @@ fn items_index(h: &super::Host, a: &[Data]) -> Answer {
/// anything is deleted, as `PageItems.removeAll()` does, and so does an image the deletion would
/// leave first in an ordinary group named as a tracing.
fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer {
if super::layers::is_scoped(a, "PathItems") {
return super::layers::scoped_remove_all(h, a);
}
let doc = items_doc(h, a)?;
let (ids, refused, on_locked, tracing) = with_doc(h, doc, |_, st| {
let ids = path_items(h, st)?;
if h.session.borrow().menu.guides_locked
&& let Some(id) = ids.iter().find(|id| st.doc.node(**id).is_some_and(|n| matches!(n.kind, NodeKind::Path { guide: true, .. })))
{
return Err(HostError::Error(format!("Cannot edit PathItem {}: guides are locked", id.0)));
}
let refused: Vec<u64> = ids.iter().filter(|i| !editable(&st.doc, **i)).map(|i| i.0).take(20).collect();
let locks = st.doc.locked_artboards();
let on_locked: Vec<u64> = ids.iter().filter(|i| locks.holds_id(**i)).map(|i| i.0).take(20).collect();
@@ -503,10 +575,10 @@ fn items_remove_all(h: &super::Host, a: &[Data]) -> Answer {
Ok(Data::Undefined)
}
/// The id in the result of a command that made an object, read from the command's own result so
/// that an id above 2^53 stays exact.
fn made_id(r: &Value) -> std::result::Result<NodeId, HostError> {
r["id"].as_u64().map(NodeId).ok_or_else(|| HostError::Error("the path was not made".into()))
/// The id in the JSON result of a command that made an object, read exactly, as the text creators
/// read it.
fn made_id(r: &(Data, Value)) -> std::result::Result<NodeId, HostError> {
r.1.get("id").and_then(Value::as_u64).map(NodeId).ok_or_else(|| HostError::Error("the path was not made".into()))
}
/// Runs the command `id` that makes a path in `doc` on top of the active layer, the selection kept,
@@ -516,7 +588,8 @@ fn made_id(r: &Value) -> std::result::Result<NodeId, HostError> {
fn make(h: &super::Host, doc: Doc, id: &str, params: &Value, reversed: bool) -> Answer {
let made = keeping_paint(h, || {
on_doc(h, doc.uid, true, |h| {
let id = made_id(&drawing_normally(h, || command_value(h, id, params))?.1)?;
let parent = with_doc(h, doc, |_, st| st.current_layer().or_else(|| st.doc.default_layer()));
let id = made_id(&drawing_normally(h, parent, id, params)?)?;
if reversed {
command(h, "path.reverse", &json!({"ids": [id.0]}))?;
}
@@ -681,9 +754,10 @@ fn items_add(h: &super::Host, a: &[Data]) -> Answer {
let ap = h.session.borrow().new_art();
ap.fill_paint().is_none() && ap.stroke_paint().is_none()
};
let id = made_id(&drawing_normally(h, || command_value(h, "path.create", &json!({"d": ""})))?.1)?;
let parent = with_doc(h, doc, |_, st| st.current_layer().or_else(|| st.doc.default_layer()));
let id = made_id(&drawing_normally(h, parent, "path.create", &json!({"d": ""}))?)?;
if unpainted {
command(h, "paint.setStroke", &json!({"none": true, "ids": [id.0]}))?;
command(h, "paint.setStroke", &json!({"none": true, "ids": [id.0], "objectOnly": true}))?;
}
Ok(id)
})
@@ -697,8 +771,8 @@ fn items_add(h: &super::Host, a: &[Data]) -> Answer {
fn path_points(h: &super::Host, a: &[Data]) -> Answer {
let item = this_path(h, a)?;
let [high, low] = id_parts(item.id);
Ok(host_ref("PathPoints", &[float(h.run), float(item.doc.uid), high, low]))
let handle = with_doc(h, item.doc, |_, st| super::node_handle(h, st, item.id));
Ok(host_ref("PathPoints", &handle))
}
fn path_closed(h: &super::Host, a: &[Data]) -> Answer {
@@ -709,7 +783,13 @@ fn path_closed(h: &super::Host, a: &[Data]) -> Answer {
fn path_set_closed(h: &super::Host, a: &[Data]) -> Answer {
let closed = boolean(arg(a, 1), "closed")?;
let item = this_path(h, a)?;
edit_points(h, item, |subs| subs.iter_mut().for_each(|sp| sp.closed = closed))?;
edit_points(h, item, |subs| {
if subs.is_empty() && closed {
subs.push(SubPath::new(Vec::new(), closed));
} else {
subs.iter_mut().for_each(|sp| sp.closed = closed);
}
})?;
Ok(Data::Undefined)
}
@@ -816,8 +896,8 @@ fn path_set_entire(h: &super::Host, a: &[Data]) -> Answer {
let closed = read_points(h, item, |subs| !subs.is_empty() && subs.iter().all(|sp| sp.closed))?;
let c = h.dom.coords.get();
let anchors: Vec<Anchor> =
script.iter().map(|p| on_canvas(f.to_document(c, *p), "each point").map(Anchor::corner)).collect::<std::result::Result<_, _>>()?;
let subs = if anchors.is_empty() { Vec::new() } else { vec![SubPath::new(anchors, closed)] };
script.iter().map(|p| in_canvas(f.to_document(c, *p), "each point").map(Anchor::corner)).collect::<std::result::Result<_, _>>()?;
let subs = if anchors.is_empty() && !closed { Vec::new() } else { vec![SubPath::new(anchors, closed)] };
write_path(h, item, subs)?;
cut_points(h, item);
Ok(Data::Undefined)
@@ -905,10 +985,10 @@ fn new_art_params(h: &super::Host, item: Item, fill: bool) -> std::result::Resul
Ok(match linked {
true if *tint < 1.0 => json!({"swatch": name, "tint": f64::from(*tint) * 100.0}),
true => json!({"swatch": name}),
false => json!({"color": colors::param(color)}),
false => json!({"color": colors::param(color), "keepModel": true}),
})
}
Paint::Solid { color, .. } => Ok(json!({"color": colors::param(color)})),
Paint::Solid { color, .. } => Ok(json!({"color": colors::param(color), "keepModel": true})),
Paint::Gradient(g) => {
let mut g = g.clone();
if g.geom.is_some() || g.freeform.is_some() {
@@ -1181,8 +1261,8 @@ pub(super) fn set_stroke_weight(h: &super::Host, item: Item, weight: f64) -> std
fn points_path(h: &super::Host, a: &[Data]) -> std::result::Result<Item, HostError> {
let Some(handle) = handle_of(arg(a, 0), "PathPoints") else { return Err(HostError::Type("this is not a PathPoints".into())) };
let [run, uid, high, low] = handle.as_slice() else { return Err(HostError::Type("this is not a PathPoints".into())) };
let item = path_at(h, *run, *uid, *high, *low)?;
let [run, uid, high, low, reverts] = handle.as_slice() else { return Err(HostError::Type("this is not a PathPoints".into())) };
let item = path_at(h, *run, *uid, *high, *low, *reverts)?;
flush_other(h, item)?;
Ok(item)
}
@@ -1221,8 +1301,9 @@ fn points_parent(h: &super::Host, a: &[Data]) -> Answer {
}
fn point_ref(h: &super::Host, item: Item, i: usize) -> Data {
let [high, low] = id_parts(item.id);
host_ref("PathPoint", &[float(h.run), float(item.doc.uid), high, low, float(i as u64), float(point_cuts(h, item))])
let mut handle = with_doc(h, item.doc, |_, st| super::node_handle(h, st, item.id)).to_vec();
handle.extend([float(i as u64), float(point_cuts(h, item))]);
host_ref("PathPoint", &handle)
}
/// How many times the points read of `item` have gone stale, after [`see_points`] notes a change
@@ -1274,7 +1355,10 @@ fn see_points(h: &super::Host, key: (u64, u64), own: impl FnOnce() -> bool) {
POINT_LOOKS.with(|n| n.set(n.get() + 1));
let node = {
let s = h.session.borrow();
s.documents().iter().find(|d| d.uid == key.0).and_then(|st| node_arc(&st.doc, NodeId(key.1)).cloned())
s.documents().iter().find(|d| d.uid == key.0).and_then(|st| {
h.dom.point_docs.borrow_mut().entry(key.0).or_insert_with(|| st.doc.clone());
node_arc(&st.doc, NodeId(key.1)).cloned()
})
};
// A path that is gone makes its points stale, so that an undo that brings it back leaves them
// stale.
@@ -1297,53 +1381,47 @@ fn see_points(h: &super::Host, key: (u64, u64), own: impl FnOnce() -> bool) {
/// change that a later command reverses still makes the points stale. Paths under the object that
/// the object model is changing ([`super::State`]), or that object itself, take the change as the
/// object model's own, and their points stay valid. A document that is the one the run last looked
/// at is skipped, as are its paths. While the object model writes one path's points
/// ([`super::State`]'s `one_path`), only that path and tracked paths in its outermost enclosing
/// Objects on Path group are looked at in its document.
/// at is skipped, as are its paths.
pub(super) fn see_all_points(h: &super::Host) {
let keys: Vec<(u64, u64)> = {
let seen = h.dom.point_nodes.borrow();
if seen.values().all(|paths| paths.is_empty()) {
return;
}
let s = h.session.borrow();
let mut docs = h.dom.point_docs.borrow_mut();
let one = h.dom.one_path.get();
let seen = h.dom.point_nodes.borrow();
let mut keys = Vec::new();
// The documents that changed since the last look, kept as they are now.
for (uid, paths) in seen.iter().filter(|(_, paths)| !paths.is_empty()) {
// Editing a path in an Objects on Path group can move other paths in the group.
let mut moved = Vec::new();
match s.documents().iter().find(|d| d.uid == *uid) {
Some(st) if docs.get(uid).is_some_and(|d| Arc::ptr_eq(d, &st.doc)) => continue,
Some(st) => {
if let Some(item) = one.filter(|i| i.doc.uid == *uid) {
let d = &st.doc;
let group = d.ancestry(item.id).and_then(|a| {
a.into_iter().filter_map(|id| d.node(id)).find(|g| vectorcraft_doc::objects_on_path::is_objects_on_path(g))
});
if let Some(g) = group {
g.walk(&mut |n: &crate::doc::Node| {
if n.id != item.id && paths.contains_key(&n.id.0) {
moved.push((*uid, n.id.0));
}
});
}
}
docs.insert(*uid, st.doc.clone());
docs.retain(|uid, before| {
let after = s.documents().iter().find(|d| d.uid == *uid).map(|st| &st.doc);
if after.is_some_and(|after| Arc::ptr_eq(before, after)) {
return true;
}
// Editing a path in an Objects on Path group can move the other paths in the group, so
// the outermost such group is looked at in place of the path.
let mut todo: Vec<_> = match h.dom.editing.get().filter(|item| item.doc.uid == *uid) {
Some(item) => {
let group = before
.ancestry(item.id)
.and_then(|a| a.into_iter().find(|g| before.node(*g).is_some_and(vectorcraft_doc::objects_on_path::is_objects_on_path)));
node_arc(before, group.unwrap_or(item.id)).into_iter().collect()
}
None => {
docs.remove(uid);
None => before.layers.iter().collect(),
};
while let Some(node) = todo.pop() {
if after.and_then(|d| node_arc(d, node.id)).is_some_and(|n| Arc::ptr_eq(node, n)) {
continue;
}
if seen.get(uid).is_some_and(|paths| paths.contains_key(&node.id.0)) {
keys.push((*uid, node.id.0));
}
if let Some(children) = node.children() {
todo.extend(children);
}
}
match one {
Some(item) if item.doc.uid == *uid => {
keys.extend(paths.contains_key(&item.id.0).then_some((*uid, item.id.0)));
keys.append(&mut moved);
}
_ => keys.extend(paths.keys().map(|id| (*uid, *id))),
if let Some(after) = after {
*before = after.clone();
true
} else {
false
}
}
});
keys
};
let editing = h.dom.editing.get();
@@ -1425,8 +1503,8 @@ fn points_remove_all(h: &super::Host, a: &[Data]) -> Answer {
/// point of the path removed or replaced since `this` was read.
pub(super) fn this_point(h: &super::Host, a: &[Data]) -> std::result::Result<(Item, usize), HostError> {
let Some(handle) = handle_of(arg(a, 0), "PathPoint") else { return Err(HostError::Type("this is not a PathPoint".into())) };
let [run, uid, high, low, i, cuts] = handle.as_slice() else { return Err(HostError::Type("this is not a PathPoint".into())) };
let item = path_at(h, *run, *uid, *high, *low)?;
let [run, uid, high, low, reverts, i, cuts] = handle.as_slice() else { return Err(HostError::Type("this is not a PathPoint".into())) };
let item = path_at(h, *run, *uid, *high, *low, *reverts)?;
flush_other(h, item)?;
if whole(*cuts) != Some(point_cuts(h, item)) {
return Err(HostError::Error(STALE_POINT.into()));
@@ -1463,17 +1541,7 @@ fn assigned_point(h: &super::Host, a: &[Data], what: &str) -> std::result::Resul
let p = point(arg(a, 1), what)?;
let (item, _) = this_point(h, a)?;
let fr = with_doc(h, item.doc, |_, st| frame(st))?;
on_canvas(fr.to_document(h.dom.coords.get(), p), what)
}
/// `p`, a point a script gave in document coordinates, when it is on the canvas (within
/// [`crate::MAX_COORD`] of the origin); a `RangeError` otherwise.
fn on_canvas(p: Point, what: &str) -> std::result::Result<Point, HostError> {
if p.x.is_finite() && p.y.is_finite() && p.x.abs() <= crate::MAX_COORD && p.y.abs() <= crate::MAX_COORD {
Ok(p)
} else {
Err(HostError::Range(format!("{what} is outside the canvas")))
}
in_canvas(fr.to_document(h.dom.coords.get(), p), what)
}
fn pt_anchor(h: &super::Host, a: &[Data]) -> Answer {
@@ -1541,12 +1609,18 @@ fn anchor_selected(sel: &crate::doc::Selection, id: NodeId, held: bool, subs: &[
if held {
return true;
}
if !sel.contains(id) || sel.segments.contains_key(&id) {
if !sel.contains(id) {
return false;
}
match sel.partial(id) {
None => true,
Some(picked) => locate(subs, i).is_some_and(|r| picked.contains(&r)),
Some(picked) => locate(subs, i).is_some_and(|(s, j)| {
picked.contains(&(s, j))
&& !sel
.segments
.get(&id)
.is_some_and(|segments| segments.iter().any(|&(sub, at)| sub == s && (at == j || (at + 1) % subs[s].anchors.len() == j)))
}),
}
}
@@ -1558,12 +1632,19 @@ fn same_layout(a: &[SubPath], b: &[SubPath]) -> bool {
/// `selected`: `PathPointSelection.ANCHORPOINT` when the point is a selected anchor point
/// ([`anchor_selected`]), otherwise `PathPointSelection.NOSELECTION`. The point changes waiting in
/// [`super::State`] are written first only when they add or remove points of this path, since
/// the selection names anchors by their place in the document's path.
/// [`super::State`] are written first when they add or remove points of this path or invalidate
/// selected segments.
fn pt_selected(h: &super::Host, a: &[Data]) -> Answer {
let (item, i) = this_point(h, a)?;
let moved = match &*h.dom.pending.borrow() {
Some((waiting, subs)) if same_path(*waiting, item) => !read_path(h, item, |_, _, pd| same_layout(subs, &pd.subpaths))?,
Some((waiting, subs)) if same_path(*waiting, item) => read_path(h, item, |st, _, pd| {
!same_layout(subs, &pd.subpaths)
|| st
.selection
.segments
.get(&item.id)
.is_some_and(|segments| segments.iter().any(|&(s, i)| !subs.get(s).is_some_and(|sp| i < sp.segment_count())))
})?,
_ => false,
};
if moved {
@@ -1631,22 +1712,31 @@ fn path_selected_points(h: &super::Host, a: &[Data]) -> Answer {
let picked: Vec<usize> = read_path(h, item, |st, _, pd| {
let sel = &st.selection;
let held = held_selected(&st.doc, sel, item.id);
if !held && (!sel.contains(item.id) || sel.segments.contains_key(&item.id)) {
if !held && !sel.contains(item.id) {
return Vec::new();
}
let mut out = Vec::new();
let mut first = 0;
let segments = sel.segments.get(&item.id);
let ends: std::collections::BTreeSet<_> = segments
.into_iter()
.flatten()
.filter_map(|&(s, i)| pd.subpaths.get(s).filter(|sp| !sp.anchors.is_empty()).map(|sp| [(s, i), (s, (i + 1) % sp.anchors.len())]))
.flatten()
.collect();
let partial = sel.partial(item.id).filter(|_| !held);
let mut picked = Vec::new();
let mut offset = 0;
for (s, sp) in pd.subpaths.iter().enumerate() {
let n = sp.anchors.len();
out.extend((0..n).filter(|j| held || sel.partial(item.id).is_none_or(|p| p.contains(&(s, *j)))).map(|j| first + j));
first += n;
for j in 0..sp.anchors.len() {
if partial.is_none_or(|a| a.contains(&(s, j)) && !ends.contains(&(s, j))) {
picked.push(offset + j);
}
}
offset += sp.anchors.len();
}
out
picked
})?;
h.charge_call(picked.len() as u64)?;
let [high, low] = id_parts(item.id);
let cuts = float(point_cuts(h, item));
let points = picked.into_iter().map(|i| host_ref("PathPoint", &[float(h.run), float(item.doc.uid), high, low, float(i as u64), cuts])).collect();
let points = picked.into_iter().map(|i| point_ref(h, item, i)).collect();
Ok(Data::Array(points))
}
@@ -1704,10 +1794,13 @@ fn remove_point(h: &super::Host, item: Item, i: usize, selected: Option<crate::d
if !wait {
// The points are written first, and the selection is then set with selection
// commands, which the journal records with the edit.
// The current layer and the highlighted Layers rows are put back after the selection is set.
let (layer, rows) = with_doc(h, item.doc, |_, st| (st.active_layer, st.highlighted_rows()));
flush(h)?;
on_doc(h, item.doc.uid, false, |h| {
let doc = h.session.borrow().active().map(|st| st.doc.clone()).ok_or_else(|| HostError::Error(super::STALE_DOCUMENT.into()))?;
super::restore_selection(h, &doc, &sel)
super::restore_selection(h, &doc, &sel)?;
super::restore_layer(h, item.doc.uid, layer, &rows)
})?;
}
}
@@ -1796,7 +1889,7 @@ pub(super) fn path_item_members(l: &Link) -> Vec<Described> {
),
("strokeCap", property(l, path_stroke_cap, path_set_stroke_cap), typed("StrokeCap")),
("strokeJoin", property(l, path_stroke_join, path_set_stroke_join), typed("StrokeJoin")),
("strokeMiterLimit", property(l, path_miter, path_set_miter), typed("number")),
("strokeMiterLimit", property(l, path_miter, path_set_miter), MemberInfo { min: Some(1.0), max: Some(500.0), ..typed("number") }),
("strokeDashes", property(l, path_dashes, path_set_dashes), typed("Array")),
("strokeDashOffset", property(l, path_dash_offset, path_set_dash_offset), typed("number")),
("selectedPathPoints", get(l, path_selected_points), typed("Array")),
@@ -1818,8 +1911,9 @@ 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("Document")),
("parent", get(l, items_parent), typed("*")),
("index", method(l, items_index), returns("PathItem", &[("itemKey", "*")])),
("getByName", method(l, items_by_name), returns("PathItem", &[("name", "string")])),
("removeAll", method(l, items_remove_all), returns("undefined", &[])),
@@ -1877,13 +1971,38 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
#[cfg(test)]
mod tests {
use std::cell::Cell;
use super::*;
use crate::Session;
thread_local! {
pub(super) static LOCATE_STEPS: Cell<usize> = const { Cell::new(0) };
}
#[test]
fn selected_points_do_not_rescan_subpaths() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
let id = s.execute("shape.rectangle", &json!({"x": 0, "y": 0, "width": 10, "height": 10})).unwrap()["id"].clone();
let subpaths = vec![json!({"anchors": [{"x": 0, "y": 0}, {"x": 10, "y": 0}, {"x": 10, "y": 10}, {"x": 0, "y": 10}], "closed": true}); 128];
s.execute("path.setAnchors", &json!({"id": id, "subpaths": subpaths})).unwrap();
s.execute("select.anchors", &json!({"id": id, "anchors": [[0, 3], [127, 3]]})).unwrap();
s.execute("select.segments", &json!({"id": id, "segments": [[0, 0], [127, 1]], "mode": "add"})).unwrap();
LOCATE_STEPS.with(|steps| steps.set(0));
let out = s
.execute("script.run", &json!({"source": "vc.log(app.activeDocument.pathItems[0].selectedPathPoints.length);", "name": "t.js"}))
.unwrap();
assert_eq!(out["log"], json!([2]));
LOCATE_STEPS.with(|steps| assert!(steps.get() <= 512, "subpath visits: {}", steps.get()));
}
#[test]
fn a_made_id_above_two_to_the_53_stays_exact() {
assert_eq!(made_id(&json!({"id": 9_007_199_254_740_993_u64})), Ok(NodeId(9_007_199_254_740_993)));
assert_eq!(made_id(&json!({"id": 7})), Ok(NodeId(7)));
assert!(made_id(&json!({"id": 1.5})).is_err());
assert!(made_id(&json!({})).is_err());
let made = |v: Value| made_id(&(Data::Undefined, v));
assert_eq!(made(json!({"id": 9_007_199_254_740_993_u64})), Ok(NodeId(9_007_199_254_740_993)));
assert_eq!(made(json!({"id": 7})), Ok(NodeId(7)));
assert!(made(json!({"id": 1.5})).is_err());
assert!(made(json!({})).is_err());
}
}
+233 -59
View File
@@ -1,12 +1,16 @@
//! Type in the script object model: `document.textFrames`, each `TextFrame`, the `TextRange` of its
//! Type in the script object model: the `textFrames` of a document, a layer and a group, each `TextFrame`, the `TextRange` of its
//! text with the `characters`, `words` and `paragraphs` in it, their `characterAttributes` and
//! `paragraphAttributes`, and `app.textFonts`, as the help pages
//! <https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItems/>,
//! <https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/>,
//! <https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/> and
//! <https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/>,
//! <https://ai-scripting.docsforadobe.dev/jsobjref/CharacterAttributes/> and
//! <https://ai-scripting.docsforadobe.dev/jsobjref/TextFonts/> describe them.
//!
//! VectorCraft's own rules, which the help pages do not state:
//! - A layer's or group's `textFrames` list the type directly in it, topmost first. Their `add()`,
//! `pointText`, `areaText` and `pathText` put the new type on top of its contents, and a hidden
//! or locked layer or group throws.
//! - Offsets and lengths count UTF-16 code units, as a JavaScript string does, so
//! `frame.contents.length` is `frame.textRange.length`. An offset inside a surrogate pair moves
//! out to the whole character. One item of `characters` is one code point.
@@ -33,6 +37,8 @@
//! value; set on an empty range it changes nothing. A paragraph attribute reads the first
//! paragraph the range touches and sets every one of them. A text range has the members of
//! both its `characterAttributes` and its `paragraphAttributes`.
//! - `fillColor` and `strokeColor` take and give color objects as a path's do; a `NoColor` takes
//! the paint away. `strokeWeight` is 0 to 1000 points.
use std::cell::{Cell, RefCell};
use std::collections::{HashMap, VecDeque};
@@ -40,13 +46,14 @@ use std::rc::Rc;
use std::sync::{Arc, Weak};
use serde_json::{Value, json};
use vectorcraft_color::Paint;
use vectorcraft_doc::{CharStyle, Justify, TextKind, TextObject};
use vectorcraft_js::{Data, HostClass, HostError, HostFunction, HostItem, HostMember, MemberInfo, Realm, RunError, host_ref};
use super::{
Answer, Described, Doc, Host, Item, Link, NOT_FOUND, STALE_ITEM, all_editable, arg, boolean, class, command, doc_of, doc_ref, edit_item,
editable, float, frame, function, get, handle_of, id_parts, item_of, item_ref, method, named, num, number, on_doc, page_items, point, property,
returns, text, typed, typename_of, whole, with_doc,
Answer, Described, Doc, Host, Item, Link, NOT_FOUND, ON_LOCKED_ARTBOARD, STALE_ITEM, all_editable, arg, boolean, class, colors, command, doc_of,
doc_ref, edit_item, editable, float, frame, function, get, handle_of, id_parts, item_of, item_ref, method, named, num, number, on_doc,
page_items, point, property, returns, text, typed, typename_of, whole, with_doc,
};
use crate::{DocState, Document, NodeId, NodeKind};
@@ -59,6 +66,10 @@ pub const STALE_RANGE: &str = "Stale text range";
/// The most edits a frame keeps for moving its ranges; a range made before the oldest kept edit
/// is stale.
const MAX_EDITS: usize = 100_000;
/// The most bytes the offset tables of the frames' indexes hold in a run. Past it the tables of
/// the other frames are given up; their text, generations and edits stay, and each frame's tables
/// are made again when it is next read.
const INDEX_BUDGET: usize = 64 << 20;
/// A frame's text with the offsets of its characters, words and paragraphs, in UTF-16 units.
pub(super) struct Index {
@@ -102,6 +113,22 @@ impl Index {
Self { text, chars, bytes, words, paras }
}
/// The text alone, without its offset tables, for a frame whose tables were given up under
/// [`INDEX_BUDGET`]; [`observe`] makes them again before the index is read.
fn bare(text: String) -> Self {
Self { text, chars: Vec::new(), bytes: Vec::new(), words: Vec::new(), paras: Vec::new() }
}
fn is_bare(&self) -> bool {
self.chars.is_empty()
}
/// The bytes the offset tables hold.
fn table_bytes(&self) -> usize {
let pairs = self.words.capacity() + self.paras.capacity();
(self.chars.capacity() + self.bytes.capacity()) * size_of::<usize>() + pairs * size_of::<(usize, usize)>()
}
fn len(&self) -> usize {
self.chars.last().copied().unwrap_or(0)
}
@@ -202,10 +229,32 @@ pub(in crate::script) struct TextState {
made: Cell<u64>,
/// The span of each range object, by its number, whose `length` the script set.
resized: RefCell<HashMap<u64, (usize, usize, u64)>>,
/// The bytes the offset tables of the frames' indexes hold ([`INDEX_BUDGET`]).
table_bytes: Cell<usize>,
/// The styles the run's style objects name.
styles: styles::StyleState,
}
/// Puts `index` in the log of frame `key` and keeps the offset tables of all the frames within
/// [`INDEX_BUDGET`], giving up the tables of other frames first.
fn set_index(state: &TextState, frames: &mut HashMap<(u64, u64), Log>, key: (u64, u64), index: Index) {
let mut total = state.table_bytes.get() + index.table_bytes();
if let Some(l) = frames.get_mut(&key) {
total -= l.index.table_bytes();
l.index = Rc::new(index);
}
for (k, l) in frames.iter_mut() {
if total <= INDEX_BUDGET {
break;
}
if *k != key && !l.index.is_bare() {
total -= l.index.table_bytes();
l.index = Rc::new(Index::bare(l.index.text.clone()));
}
}
state.table_bytes.set(total);
}
fn text_of(st: &DocState, id: NodeId) -> Option<&TextObject> {
match &st.doc.node(id)?.kind {
NodeKind::Text(t) => Some(t),
@@ -231,29 +280,36 @@ fn observe(h: &Host, st: &DocState, id: NodeId) -> std::result::Result<(Rc<Index
let mut frames = h.dom.text.frames.borrow_mut();
let key = (st.uid, id.0);
let now = Arc::as_ptr(&st.doc);
match frames.get_mut(&key) {
Some(l) if std::ptr::eq(l.doc.as_ptr(), now) && l.reverts == st.reverts => {}
let fresh = match frames.get_mut(&key) {
Some(l) if std::ptr::eq(l.doc.as_ptr(), now) && l.reverts == st.reverts => None,
Some(l) => {
if l.reverts != st.reverts || !same_text(t, &l.index.text) {
let changed = l.reverts != st.reverts || !same_text(t, &l.index.text);
if changed {
l.stamp += 1;
l.floor = l.stamp;
l.edits.clear();
l.index = Rc::new(Index::new(t.plain_text()));
}
l.doc = Arc::downgrade(&st.doc);
l.reverts = st.reverts;
changed.then(|| t.plain_text())
}
None => {
let l = Log {
doc: Arc::downgrade(&st.doc),
reverts: st.reverts,
index: Rc::new(Index::new(t.plain_text())),
index: Rc::new(Index::bare(String::new())),
stamp: 0,
floor: 0,
edits: VecDeque::new(),
};
frames.insert(key, l);
Some(t.plain_text())
}
};
// Tables given up under the budget are made again from the text the log keeps.
let fresh = fresh.or_else(|| frames.get(&key).filter(|l| l.index.is_bare()).map(|l| l.index.text.clone()));
if let Some(text) = fresh {
set_index(&h.dom.text, &mut frames, key, Index::new(text));
}
let l = frames.get(&key).ok_or_else(|| HostError::Error(STALE_ITEM.into()))?;
Ok((l.index.clone(), l.stamp))
@@ -303,6 +359,27 @@ fn resolve(h: &Host, r: Span) -> std::result::Result<(Rc<Index>, usize, usize, u
})
}
/// Runs command `id` with `params` on the text frame of `item`. Throws `Cannot edit`, with nothing
/// changed, when the frame or a layer or group it is in is hidden or locked, or the frame is on a
/// locked artboard.
fn edit_text(h: &Host, item: Item, id: &str, params: &Value) -> std::result::Result<Data, HostError> {
refuse_protected(h, item, "TextFrame")?;
edit_item(h, item, id, params)
}
/// Throws `Cannot edit` for the `class` object of `item` when it or a layer or group it is in is
/// hidden or locked, or it is on a locked artboard.
fn refuse_protected(h: &Host, item: Item, class: &str) -> std::result::Result<(), HostError> {
let (ok, on_locked) = with_doc(h, item.doc, |_, st| (editable(&st.doc, item.id), super::on_locked_artboard(h, st, item.id)));
if !ok {
return Err(HostError::Error(format!("Cannot edit {class} {}: it, or a layer or group it is in, is hidden or locked", item.id.0)));
}
if on_locked {
return Err(HostError::Error(format!("Cannot edit {class} {}: it is on a locked artboard", item.id.0)));
}
Ok(())
}
/// Records an edit the model made to the frame: `removed` units at `at` replaced by `inserted`.
/// When the text is not what that edit gives, every earlier range goes stale.
fn record(h: &Host, item: Item, before: &Index, at: usize, removed: usize, inserted: &str) -> std::result::Result<(), HostError> {
@@ -323,9 +400,9 @@ fn record(h: &Host, item: Item, before: &Index, at: usize, removed: usize, inser
l.floor = l.stamp;
l.edits.clear();
}
l.index = Rc::new(Index::new(now));
l.doc = Arc::downgrade(&st.doc);
l.reverts = st.reverts;
set_index(&h.dom.text, &mut frames, (st.uid, item.id.0), Index::new(now));
Ok(())
})
}
@@ -453,7 +530,7 @@ fn write_contents(h: &Host, r: Span, value: &Data) -> Answer {
return Ok(Data::Undefined);
}
let (s, e) = (index.text[..a].encode_utf16().count(), index.text[..b].encode_utf16().count());
edit_item(h, r.item, "text.editRange", &json!({"id": r.item.id.0, "start": a, "end": b, "insert": insert}))?;
edit_text(h, r.item, "text.editRange", &json!({"id": r.item.id.0, "start": a, "end": b, "insert": insert}))?;
record(h, r.item, &index, s, e - s, &insert)?;
Ok(Data::Undefined)
}
@@ -547,6 +624,7 @@ fn new_ref(h: &Host, doc: Doc, id: Option<NodeId>) -> Answer {
/// `null` when the type has nothing to outline and the command removed it.
fn frame_outline(h: &Host, a: &[Data]) -> Answer {
let item = this_frame(h, a)?;
refuse_protected(h, item, "TextFrame")?;
let (_, r) = on_doc(h, item.doc.uid, true, |h| {
command(h, "select.set", &json!({"ids": [item.id.0]}))?;
super::command_value(h, "type.createOutlines", &json!({}))
@@ -568,6 +646,7 @@ fn convert(h: &Host, a: &[Data], to_area: bool) -> Answer {
Some(false) => return Err(HostError::Error(format!("the text frame is not {} type", if to_area { "point" } else { "area" }))),
Some(true) => {}
}
refuse_protected(h, item, "TextFrame")?;
let id = if to_area { "type.convertToAreaType" } else { "type.convertToPointType" };
let (_, r) = on_doc(h, item.doc.uid, true, |h| super::command_value(h, id, &json!({"ids": [item.id.0]})))?;
new_ref(h, item.doc, result_id(&r).or(Some(item.id)))
@@ -730,35 +809,44 @@ fn part_add(h: &Host, a: &[Data], before: bool) -> Answer {
let (r, part) = this_part(h, a)?;
let contents = contents_of(arg(a, 1))?;
let (index, s, e, _) = resolve(h, r)?;
let at = if before || matches!(arg(a, 2), Data::Undefined) {
// The place, and whether it is the end of a range, which rounds up to a character boundary.
let (at, after) = if before || matches!(arg(a, 2), Data::Undefined) {
let (items, spans) = part_spans(&index, part, s, e);
let span = |k: usize| match spans {
None => index.char_span(k),
Some(list) => list.get(k).copied(),
};
if before {
items.clone().next().and_then(span).map_or(s, |(x, _)| x)
(items.clone().next().and_then(span).map_or(s, |(x, _)| x), false)
} else {
items.clone().next_back().and_then(span).map_or(e, |(_, y)| y)
(items.clone().next_back().and_then(span).map_or(e, |(_, y)| y), true)
}
} else {
let rel = arg(a, 2);
let target = if handle_of(rel, "TextFrame").is_some() {
whole_span(h, item_of(h, rel)?)?.1
} else if handle_of(rel, "TextRange").is_some() {
span_of(h, rel, &["TextRange"])?
} else {
span_of(h, rel, &["TextRange"]).map_err(|_| HostError::Type("relativeObject must be a TextRange or a TextFrame".into()))?
// A range of a removed frame keeps its own error.
span_of(h, rel, &["TextRange"]).map_err(|e| match e {
HostError::Error(m) if m == STALE_RANGE => HostError::Error(m),
_ => HostError::Type("relativeObject must be a TextRange or a TextFrame".into()),
})?
};
if target.item.doc.uid != r.item.doc.uid || target.item.id != r.item.id {
return Err(HostError::Error("relativeObject must be text of the same text frame".into()));
}
let (_, ts, te, _) = resolve(h, target)?;
if text_placement(arg(a, 3))? { te } else { ts }
if text_placement(arg(a, 3))? { (te, true) } else { (ts, false) }
};
// A place inside a character (between the two halves of a surrogate pair) moves to its edge.
let b = index.byte(at, after);
let at = index.text[..b].encode_utf16().count();
if contents.is_empty() {
let (_, stamp) = with_doc(h, r.item.doc, |_, st| observe(h, st, r.item.id))?;
return Ok(range_ref(h, r.item, at, at, stamp, "TextRange"));
}
let b = index.byte(at, false);
let (prev, next) = (index.text[..b].chars().next_back(), index.text[b..].chars().next());
let (lead, trail) = match part {
Part::Characters => ("", ""),
@@ -774,7 +862,7 @@ fn part_add(h: &Host, a: &[Data], before: bool) -> Answer {
),
};
let insert = format!("{lead}{contents}{trail}");
edit_item(h, r.item, "text.editRange", &json!({"id": r.item.id.0, "start": b, "end": b, "insert": insert}))?;
edit_text(h, r.item, "text.editRange", &json!({"id": r.item.id.0, "start": b, "end": b, "insert": insert}))?;
record(h, r.item, &index, at, 0, &insert)?;
let (_, stamp) = with_doc(h, r.item.doc, |_, st| observe(h, st, r.item.id))?;
let start = at + lead.encode_utf16().count();
@@ -804,9 +892,12 @@ enum Attr {
Underline,
StrikeThrough,
TextFont,
FillColor,
StrokeColor,
StrokeWeight,
}
const ATTRS: [(&str, Attr); 11] = [
const ATTRS: [(&str, Attr); 14] = [
("size", Attr::Size),
("leading", Attr::Leading),
("autoLeading", Attr::AutoLeading),
@@ -818,6 +909,9 @@ const ATTRS: [(&str, Attr); 11] = [
("underline", Attr::Underline),
("strikeThrough", Attr::StrikeThrough),
("textFont", Attr::TextFont),
("fillColor", Attr::FillColor),
("strokeColor", Attr::StrokeColor),
("strokeWeight", Attr::StrokeWeight),
];
/// The styles of the characters in bytes `a..b`, effective as the Character panel shows them, with
@@ -920,9 +1014,18 @@ fn attr_value(h: &Host, attr: Attr, t: &TextObject, s: &CharStyle, para: usize)
Attr::Underline => Data::Bool(s.underline),
Attr::StrikeThrough => Data::Bool(s.strikethrough),
Attr::TextFont => font_ref(h, &s.font_family, &s.font_style),
Attr::FillColor => colors::of_paint(&s.fill),
Attr::StrokeColor => colors::of_paint(&s.stroke),
Attr::StrokeWeight => num(s.stroke_width * stroke_scale(t)),
}
}
/// Document points per text-space point of a character stroke, as `text.setRangeStyle` scales a
/// `strokeWidth` it is given.
fn stroke_scale(t: &TextObject) -> f64 {
vectorcraft_doc::Scaling::factor(t.xf).filter(|k| k.is_finite() && *k > 1e-12).unwrap_or(1.0)
}
/// The `text.setRangeStyle` parameter for `attr` set to `v`, and the value it reads as after.
fn attr_param(h: &Host, attr: Attr, name: &str, v: &Data, first: (&TextObject, &CharStyle, usize)) -> std::result::Result<(Value, Data), HostError> {
let finite = || number(v, name);
@@ -991,6 +1094,20 @@ fn attr_param(h: &Host, attr: Attr, name: &str, v: &Data, first: (&TextObject, &
let (family, style) = font_of(h, v)?;
(json!({"font": family, "style": style}), font_ref(h, &family, &style))
}
Attr::FillColor | Attr::StrokeColor => {
let color = colors::assigned(v, name)?;
let paint = color.map_or(Paint::None, Paint::solid);
let given = color.map_or_else(|| json!("none"), |c| colors::param(&c));
let key = if matches!(attr, Attr::FillColor) { "fill" } else { "stroke" };
(json!({ key: given }), colors::of_paint(&paint))
}
Attr::StrokeWeight => {
let n = finite()?;
if !(0.0..=1000.0).contains(&n) {
return Err(HostError::Range("strokeWeight must be from 0 to 1000 points".into()));
}
(json!({"strokeWidth": n}), num(n))
}
})
}
@@ -1024,7 +1141,8 @@ fn write_attr(h: &Host, a: &[Data], attr: Attr, name: &str) -> Answer {
let (param, wants) = attr_param(h, attr, name, arg(a, 1), (t, &first.0, first.1))?;
// A leading set on characters with auto leading fixes it even where auto gives that value.
let has = |st: &CharStyle, p: usize| (!matches!(attr, Attr::Leading) || st.leading.is_some()) && same(&attr_value(h, attr, t, st, p), &wants);
let unchanged = ba == bb || styles.iter().all(|(st, p)| has(st, *p));
// An empty range changes nothing, also one inside a character that `ba..bb` widens to it.
let unchanged = s == e || ba == bb || styles.iter().all(|(st, p)| has(st, *p));
let fixed = match (attr, &wants) {
(Attr::AutoLeading, Data::Bool(false)) if !unchanged => Some(auto_leading_spans(t, ba, bb)?),
_ => None,
@@ -1042,7 +1160,7 @@ fn write_attr(h: &Host, a: &[Data], attr: Attr, name: &str) -> Answer {
super::atomically(h, |h| {
for (start, end, leading) in &spans {
let p = json!({"id": r.item.id.0, "start": start, "end": end, "leading": leading});
edit_item(h, r.item, "text.setRangeStyle", &p)?;
edit_text(h, r.item, "text.setRangeStyle", &p)?;
}
Ok(())
})?;
@@ -1054,7 +1172,7 @@ fn write_attr(h: &Host, a: &[Data], attr: Attr, name: &str) -> Answer {
o.insert("start".into(), json!(ba));
o.insert("end".into(), json!(bb));
}
let answer = edit_item(h, r.item, "text.setRangeStyle", &p)?;
let answer = edit_text(h, r.item, "text.setRangeStyle", &p)?;
if let Attr::TextFont = attr {
let wants = |k: &str| p.get(k).and_then(Value::as_str).unwrap_or_default().to_string();
font_applied(h, r.item, (ba, bb), (&wants("font"), &wants("style")), &answer)?;
@@ -1216,7 +1334,7 @@ fn write_para(h: &Host, a: &[Data], attr: ParaAttr, name: &str) -> Answer {
o.insert("start".into(), json!(ba));
o.insert("end".into(), json!(bb));
}
edit_item(h, r.item, id, &p)?;
edit_text(h, r.item, id, &p)?;
Ok(Data::Undefined)
}
@@ -1250,32 +1368,46 @@ fn frame_ids(h: &Host, st: &DocState) -> std::result::Result<Rc<Vec<NodeId>>, Ho
Ok(ids)
}
/// The document and the layer or group (`None`: the whole document) a `TextFrames` lists.
fn frames_scope(h: &Host, a: &[Data]) -> std::result::Result<(Doc, Option<NodeId>), HostError> {
super::layers::text_scope(h, arg(a, 0))
}
fn frames_doc(h: &Host, a: &[Data]) -> std::result::Result<Doc, HostError> {
doc_of(h, arg(a, 0), "TextFrames")
Ok(frames_scope(h, a)?.0)
}
/// The type objects a `TextFrames` of `container` lists: the document's ([`frame_ids`]), or those
/// directly in a layer or group, topmost first.
fn listed(h: &Host, st: &DocState, container: Option<NodeId>) -> std::result::Result<Rc<Vec<NodeId>>, HostError> {
match container {
None => frame_ids(h, st),
Some(c) => super::layers::text_list(h, st, c),
}
}
fn frames_length(h: &Host, a: &[Data]) -> Answer {
let doc = frames_doc(h, a)?;
Ok(num(float(with_doc(h, doc, |_, st| frame_ids(h, st).map(|ids| ids.len()))? as u64)))
let (doc, c) = frames_scope(h, a)?;
Ok(num(float(with_doc(h, doc, |_, st| listed(h, st, c).map(|l| l.len()))? as u64)))
}
fn frames_parent(h: &Host, a: &[Data]) -> Answer {
let doc = frames_doc(h, a)?;
Ok(doc_ref(h, doc.uid))
let (doc, c) = frames_scope(h, a)?;
Ok(with_doc(h, doc, |_, st| c.map_or_else(|| doc_ref(h, st.uid), |c| item_ref(h, st, c))))
}
fn frames_at(h: &Host, a: &[Data]) -> Answer {
let doc = frames_doc(h, a)?;
let (doc, c) = frames_scope(h, a)?;
let Data::Number(n) = arg(a, 1) else { return Ok(Data::Undefined) };
let Some(i) = usize_of(*n) else { return Ok(Data::Undefined) };
with_doc(h, doc, |_, st| Ok(frame_ids(h, st)?.get(i).map_or(Data::Undefined, |id| item_ref(h, st, *id))))
with_doc(h, doc, |_, st| Ok(listed(h, st, c)?.get(i).map_or(Data::Undefined, |id| item_ref(h, st, *id))))
}
fn frames_by_name(h: &Host, a: &[Data]) -> Answer {
let doc = frames_doc(h, a)?;
let (doc, c) = frames_scope(h, a)?;
let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("give a name, as a string".into())) };
with_doc(h, doc, |_, st| {
let ids = frame_ids(h, st)?;
let ids = listed(h, st, c)?;
h.charge_call(ids.len() as u64)?;
let id = ids.iter().find(|i| st.doc.node(**i).and_then(|n| n.name.as_deref()) == Some(name.as_str()));
id.map(|id| item_ref(h, st, *id)).ok_or_else(|| HostError::Error(NOT_FOUND.into()))
@@ -1303,29 +1435,40 @@ fn vertical_of(d: &Data) -> std::result::Result<bool, HostError> {
}
}
/// Makes point type at `anchor` (script coordinates; `None`: the origin) with `text.create`.
fn point_text(h: &Host, doc: Doc, anchor: Option<[f64; 2]>, vertical: bool) -> Answer {
/// Makes point type at `anchor` (script coordinates; `None`: the origin) with `text.create`, on
/// top of the contents of `container` when there is one.
fn point_text(h: &Host, (doc, container): (Doc, Option<NodeId>), anchor: Option<[f64; 2]>, vertical: bool) -> Answer {
let at = with_doc(h, doc, |_, st| Ok::<_, HostError>(frame(st)?.to_document(h.dom.coords.get(), anchor.unwrap_or([0.0, 0.0]))))?;
let (_, r) =
on_doc(h, doc.uid, true, |h| super::command_value(h, "text.create", &json!({"x": at.x, "y": at.y, "text": "", "vertical": vertical})))?;
let mut params = json!({"x": at.x, "y": at.y, "text": "", "vertical": vertical});
if let Some(c) = container {
check_open(h, doc, c)?;
if let Some(o) = params.as_object_mut() {
o.insert("parent".into(), json!(c.0));
}
}
let (_, r) = on_doc(h, doc.uid, true, |h| super::command_value(h, "text.create", &params))?;
new_ref(h, doc, result_id(&r))
}
/// The error for a layer or group that takes no new type.
const SHUT_CONTAINER: &str = "the layer or group is hidden or locked";
/// `add()`: empty point type at the origin.
fn frames_add(h: &Host, a: &[Data]) -> Answer {
point_text(h, frames_doc(h, a)?, None, false)
point_text(h, frames_scope(h, a)?, None, false)
}
/// `pointText(anchor, orientation?)`.
fn frames_point_text(h: &Host, a: &[Data]) -> Answer {
let doc = frames_doc(h, a)?;
let scope = frames_scope(h, a)?;
let anchor = point(arg(a, 1), "anchor")?;
point_text(h, doc, Some(anchor), vertical_of(arg(a, 2))?)
point_text(h, scope, Some(anchor), vertical_of(arg(a, 2))?)
}
/// Turns the path `d` names into area type or type on a path with `text.createInPath`.
/// Turns the path `d` names into area type or type on a path with `text.createInPath`, and moves
/// it on top of the contents of the collection's layer or group when there is one.
fn in_path(h: &Host, a: &[Data], on_path: bool, rest: &[usize]) -> Answer {
let doc = frames_doc(h, a)?;
let (doc, container) = frames_scope(h, a)?;
if handle_of(arg(a, 1), "PathItem").is_none() {
return Err(HostError::Type("textPath must be a PathItem".into()));
}
@@ -1336,6 +1479,7 @@ fn in_path(h: &Host, a: &[Data], on_path: bool, rest: &[usize]) -> Answer {
if rest.iter().any(|i| !matches!(arg(a, *i), Data::Undefined)) {
return Err(HostError::Error("TextFrames: path positions are not available yet".into()));
}
refuse_protected(h, path, "PathItem")?;
let (orientation, base) = if on_path { (4, 5) } else { (2, 3) };
let vertical = vertical_of(arg(a, orientation))?;
let base = threads::base_frame(h, doc, arg(a, base), arg(a, base + 1))?;
@@ -1344,12 +1488,35 @@ fn in_path(h: &Host, a: &[Data], on_path: bool, rest: &[usize]) -> Answer {
}
let mode = if on_path { "onPath" } else { "area" };
let params = json!({"path": path.id.0, "mode": mode, "text": "", "vertical": vertical});
let (_, r) = on_doc(h, doc.uid, true, |h| super::command_value(h, "text.createInPath", &params))?;
let id = result_id(&r);
if let (Some((base, postfix)), Some(id)) = (base, id) {
threads::thread_new(h, base, id, postfix)?;
// Makes the type, threaded after or before the base frame when there is one.
let make = |h: &Host| -> std::result::Result<Option<NodeId>, HostError> {
let (_, r) = on_doc(h, doc.uid, true, |h| super::command_value(h, "text.createInPath", &params))?;
let id = result_id(&r);
if let (Some((base, postfix)), Some(id)) = (base, id) {
threads::thread_new(h, base, id, postfix)?;
}
Ok(id)
};
let Some(c) = container else {
return new_ref(h, doc, make(h)?);
};
check_open(h, doc, c)?;
// The path is moved as well as converted, so it must be one that `move` takes.
if !with_doc(h, doc, |_, st| editable(&st.doc, path.id)) {
return Err(HostError::Error(format!("Cannot move PathItem {}: it is hidden or locked", path.id.0)));
}
new_ref(h, doc, id)
super::refuse_protected_edit(h, path)?;
let id = super::atomically(h, |h| {
let id = make(h)?.ok_or_else(|| HostError::Error("the command made no object".into()))?;
super::place(h, doc, id, &super::Destination { parent: c, beside: None, how: super::Placement::Top })?;
Ok(id)
})?;
new_ref(h, doc, Some(id))
}
/// Refuses a hidden or locked layer or group as the place for new type.
fn check_open(h: &Host, doc: Doc, container: NodeId) -> std::result::Result<(), HostError> {
if with_doc(h, doc, |_, st| st.doc.is_editable(container)) { Ok(()) } else { Err(HostError::Error(SHUT_CONTAINER.into())) }
}
/// `areaText(textPath, orientation?, baseFrame?, postFix?)`.
@@ -1362,19 +1529,23 @@ fn frames_path_text(h: &Host, a: &[Data]) -> Answer {
in_path(h, a, true, &[2, 3])
}
/// `removeAll()`: deletes every type object in one command; a hidden or locked one, or one on a
/// locked artboard, stops it first, as `PageItems.removeAll()` does, and so does an image the
/// deletion would leave first in an ordinary group named as a tracing.
/// `removeAll()`: deletes every type object the collection lists in one command; a hidden or
/// locked one, or one on a locked artboard, stops it first, as `PageItems.removeAll()` does, and
/// so does an image the deletion would leave first in an ordinary group named as a tracing.
fn frames_remove_all(h: &Host, a: &[Data]) -> Answer {
let doc = frames_doc(h, a)?;
let (ids, refused, on_locked, tracing) = with_doc(h, doc, |_, st| {
let ids = frame_ids(h, st)?;
let (doc, c) = frames_scope(h, a)?;
let (ids, refused, on_locked, released, tracing) = with_doc(h, doc, |_, st| {
let ids = listed(h, st, c)?;
let ok = |id: &NodeId| editable(&st.doc, *id) && st.doc.node(*id).is_some_and(all_editable);
let refused: Vec<u64> = ids.iter().filter(|i| !ok(i)).map(|i| i.0).take(20).collect();
let locks = st.doc.locked_artboards();
let on_locked: Vec<u64> = ids.iter().filter(|i| locks.holds_id(**i)).map(|i| i.0).take(20).collect();
let tracing = super::clearing_makes_tracing(&st.doc, &ids);
Ok::<_, HostError>((ids, refused, on_locked, tracing))
// Type that clips a group or layer releases its mask, so the object above it is not made
// the clipping path.
let released = super::masks_cleared_by(&st.doc, &ids);
// So would deleting the type above an image in an ordinary group named as a tracing.
let tracing = super::release_makes_tracing(&st.doc, &released, &ids) || super::removal_makes_tracing(&st.doc, &ids);
Ok::<_, HostError>((ids, refused, on_locked, released, tracing))
})?;
if !refused.is_empty() {
let list = refused.iter().map(u64::to_string).collect::<Vec<_>>().join(", ");
@@ -1382,13 +1553,15 @@ fn frames_remove_all(h: &Host, a: &[Data]) -> Answer {
}
if !on_locked.is_empty() {
let list = on_locked.iter().map(u64::to_string).collect::<Vec<_>>().join(", ");
return Err(HostError::Error(format!("{}: {list}", super::ON_LOCKED_ARTBOARD)));
return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {list}")));
}
// A group named as a tracing, cleared or released with an image left first, would become one.
if tracing {
return Err(HostError::Error(super::NOT_A_TRACING.into()));
}
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<_>>()})))?;
let params = json!({"ids": ids.iter().map(|i| i.0).collect::<Vec<_>>()});
super::atomically(h, |h| on_doc(h, doc.uid, true, |h| super::clear_releasing(h, &released, &params)))?;
}
Ok(Data::Undefined)
}
@@ -1562,6 +1735,7 @@ fn attr_type(attr: Attr) -> &'static str {
match attr {
Attr::AutoLeading | Attr::Underline | Attr::StrikeThrough => "boolean",
Attr::TextFont => "TextFont",
Attr::FillColor | Attr::StrokeColor => "Color",
_ => "number",
}
}
@@ -1743,8 +1917,8 @@ pub(super) fn classes(l: &Link) -> Vec<HostClass> {
named(vec![
("typename", get(l, frames_typename), typed("string")),
("length", get(l, frames_length), typed("number")),
("parent", get(l, frames_parent), typed("Document")),
("index", method(l, frames_index), returns("number", &[("itemKey", "*")])),
("parent", get(l, frames_parent), typed("*")),
("index", method(l, frames_index), returns("TextFrame", &[("itemKey", "*")])),
("getByName", method(l, frames_by_name), returns("TextFrame", &[("name", "string")])),
("add", method(l, frames_add), returns("TextFrame", &[])),
("pointText", method(l, frames_point_text), returns("TextFrame", &[("anchor", "Array"), ("orientation", "TextOrientation")])),
+8 -1
View File
@@ -342,7 +342,8 @@ fn target_span(h: &Host, d: &Data) -> std::result::Result<Span, HostError> {
span_of(h, d, &TEXT)
}
/// `applyTo(textItem, clearingOverrides?)`.
/// `applyTo(textItem, clearingOverrides?)`. Throws `Cannot edit`, with nothing changed, when the
/// text frame is protected as for any other text edit.
fn style_apply_to(h: &Host, a: &[Data]) -> Answer {
let style = this_style(h, a)?;
let target = target_span(h, arg(a, 1))?;
@@ -355,6 +356,7 @@ fn style_apply_to(h: &Host, a: &[Data]) -> Answer {
return Err(HostError::Error("the text is in another document than the style".into()));
}
let (index, s, e, _) = resolve(h, target)?;
super::refuse_protected(h, target.item, "TextFrame")?;
h.charge_call(16 + (e - s) as u64)?;
let (start, end) = if style.para {
let (_, ba, bb) = para_range(&index, s, e);
@@ -429,6 +431,8 @@ fn char_value(h: &Host, attr: Attr, m: &Map<String, Value>) -> Data {
Some(family) => font_ref(h, family, m.get("font_style").and_then(Value::as_str).unwrap_or("Regular")),
None => Data::Undefined,
},
// A style's colors and stroke weight are not available yet (`char_members`).
Attr::FillColor | Attr::StrokeColor | Attr::StrokeWeight => Data::Undefined,
}
}
@@ -538,6 +542,9 @@ fn char_members(link: &Link) -> Vec<Described> {
ATTRS
.iter()
.map(|&(name, attr)| {
if matches!(attr, Attr::FillColor | Attr::StrokeColor | Attr::StrokeWeight) {
return super::super::later(link, "CharacterAttributes", name);
}
let data_type = match attr {
Attr::AutoLeading | Attr::Underline | Attr::StrikeThrough => "boolean",
Attr::TextFont => "TextFont",
+8 -1
View File
@@ -24,7 +24,8 @@
//! other value, and a scale of strokes and effects with positions left as they are, throws an
//! error that says so.
//! - A locked or hidden object, one inside a locked or hidden layer or group, a group that holds a
//! locked object, and an object on a locked artboard are refused with nothing changed, and so are
//! locked object, an object on a locked artboard and a guide while guides are locked are refused
//! with nothing changed, and so are
//! a scale of 0, a matrix whose determinant is 0 and a transformation that would take the object
//! past the canvas.
@@ -41,6 +42,9 @@ const ON_LOCKED_ARTBOARD: &str = "cannot transform objects on a locked artboard"
/// The error for a locked object.
const LOCKED: &str = "cannot transform locked objects";
/// The error for a guide while guides are locked.
const GUIDES_LOCKED: &str = "cannot transform a guide while guides are locked";
/// The error for a hidden object.
const HIDDEN: &str = "cannot transform hidden objects";
@@ -215,6 +219,9 @@ fn apply(h: &Host, item: Item, m: Matrix, about: Option<&Data>, opts: &Options,
if on_locked {
return Err(HostError::Error(format!("{ON_LOCKED_ARTBOARD}: {}", item.id.0)));
}
if h.session.borrow().menu.guides_locked && with_doc(h, item.doc, |_, st| crate::is_guide_path(&st.doc, item.id)) {
return Err(HostError::Error(format!("{GUIDES_LOCKED}: {}", item.id.0)));
}
// The identity acts the same about every point, so an object without bounds (an empty path)
// takes it too.
let o = match (about, bounds) {
+5 -1
View File
@@ -2431,7 +2431,7 @@ impl Session {
eval_strict: Cell::new(None),
dollar: dollar::RunState::new(&request.locale),
args: RefCell::new((Data::Undefined, 0)),
dom: dom::State::new(heap_bytes),
dom: dom::State::new(self.documents(), heap_bytes),
actions: request.actions,
active_artboards: self.docs.iter().map(|d| (d.uid, dom::active_artboard(d))).collect(),
artboard_picks,
@@ -2748,6 +2748,10 @@ impl Session {
"hostCalls": host.calls.get(),
});
host.more_written(&mut report);
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.
if host.copied.get()
&& self.clipboard_copied
+15
View File
@@ -70,6 +70,21 @@ fn balance_previews_and_commits_one_step() {
assert_eq!(fill_of(&s, a).to_hex(), "#808080");
}
/// An `objectOnly` paint during an open interaction keeps the remembered colors: the paint it would
/// leave waiting for the commit is not added to Recent Colors when the interaction commits.
#[test]
fn object_only_paint_in_an_interaction_keeps_recent_colors() {
let mut s = session();
let a = rect(&mut s, json!("#808080"));
s.recent_colors.clear();
let recent = (s.recent_colors.clone(), s.last_solid);
s.begin_interaction("Adjust Colors").unwrap();
s.execute("paint.setFill", &json!({"ids": [a.0], "color": "#ff0000", "objectOnly": true})).unwrap();
assert_eq!(fill_of(&s, a).to_hex(), "#ff0000");
s.commit_interaction().unwrap();
assert_eq!((s.recent_colors.clone(), s.last_solid), recent, "the recent colors are as they were");
}
/// Saturate needs its intensity: a call without one, or with one that is not a number, is an error
/// that changes nothing and records no undo step. A number outside −100..100 counts as its nearest end.
#[test]
+25
View File
@@ -1020,6 +1020,31 @@ fn moves_are_validated() {
assert_eq!(parent(&s, sub), None);
}
/// `node.move` keeps a clip group's clipping path at its bottom: the path does not leave the group
/// or move up in it, and a row moved to index 0 goes directly above it.
#[test]
fn node_move_keeps_a_clip_groups_clipping_path_at_the_bottom() {
let mut s = session();
let (a, b, c) = (rect(&mut s, 0.0), rect(&mut s, 30.0), rect(&mut s, 60.0));
let layer = parent(&s, a).unwrap();
run(&mut s, "select.set", json!({"ids": [a.0, b.0, c.0]}));
let g = id(&run(&mut s, "object.clippingMask.make", json!({})));
let before = children(&s, g);
let mask = before[0];
for p in [json!({"id": mask.0, "parent": layer.0, "index": 0}), json!({"id": mask.0, "parent": g.0, "index": 2})] {
let err = s.execute("node.move", &p).unwrap_err().to_string();
assert!(err.contains("clipping path stays at the bottom"), "{p}: {err}");
assert_eq!(children(&s, g), before, "{p}");
}
run(&mut s, "node.move", json!({"id": mask.0, "parent": g.0, "index": 0}));
assert_eq!(children(&s, g), before, "the clipping path stays where it is");
let d = rect(&mut s, 90.0);
run(&mut s, "node.move", json!({"id": d.0, "parent": g.0, "index": 0}));
assert_eq!(children(&s, g)[..2], [mask, d], "the row goes directly above the clipping path");
run(&mut s, "node.move", json!({"id": before[2].0, "parent": g.0, "index": 0}));
assert_eq!(children(&s, g)[..2], [mask, before[2]]);
}
/// The Layers panel's commands refuse a switch given as text or as another value that is not true
/// or false, and leave the document, the selection, the highlighted rows and the undo history as
/// they were; true, false and null still work.
+25 -1
View File
@@ -219,6 +219,8 @@ fn replayed_counts_keep_their_rounding_and_range_rules() {
("rows", 2.4, 2),
("rows", 0.6, 1),
("rows", 1000.4, 1000),
("rows", 1000.6, 1000),
("rows", 5000.0, 1000),
] {
let mut p = json!({"width": 10, "height": 10, "artboards": 4,
"artboardLayout": {"layout": "gridByColumn", "spacing": 0}});
@@ -236,8 +238,11 @@ fn replayed_counts_keep_their_rounding_and_range_rules() {
p["artboardLayout"][key] = json!(expected);
}
assert_eq!(boards(&s), boards(&new_doc(p)));
if key == "rows" {
assert_eq!(presets(&mut s, "Recent")[0]["artboardLayout"]["rows"], json!(expected), "{value}");
}
}
for layout in [json!({"columns": 0.6}), json!({"rows": 0.4}), json!({"rows": 1000.6})] {
for layout in [json!({"columns": 0.6}), json!({"rows": 0.4})] {
let mut p = json!({"artboardLayout": layout});
p["artboardLayout"]["layout"] = json!("gridByColumn");
let mut s = Session::new();
@@ -345,6 +350,25 @@ fn a_saved_preset_with_values_out_of_range_reads_in_range() {
assert_eq!(boards(&s).iter().map(|r| r.x0).collect::<Vec<_>>(), [0.0, 100.0, 200.0], "side by side, not overlapping");
}
/// A saved preset whose rows the preferences hold above the most `file.new` takes reads as that
/// most, so `file.new` takes the preset as `file.newPresets` lists it; no rows stay no rows.
#[test]
fn a_saved_preset_with_too_many_rows_reads_in_range() {
let mut s = Session::new();
let prefs = json!({
"newDocPresets": [
{"name": "Tall", "width": 10, "height": 10, "artboards": 4, "layout": "gridByColumn", "rows": 1001},
{"name": "Plain", "width": 10, "height": 10, "artboards": 4, "layout": "gridByColumn", "rows": 0},
],
});
s.apply_prefs(serde_json::from_value(prefs).unwrap());
let saved = presets(&mut s, "Saved");
assert_eq!(saved[0]["artboardLayout"]["rows"], json!(1000), "{}", saved[0]);
assert_eq!(saved[1]["artboardLayout"].get("rows"), None, "{}", saved[1]);
s.execute("file.new", &saved[0]).unwrap();
assert_eq!(boards(&s).len(), 4);
}
/// `file.new` and `artboard.new` take the same largest artboard side (the canvas less the largest
/// bleed on both sides) and refuse a side just past it, or of 0 or less, with an error that names
/// the limit in points and, when the document's units aren't points, in those units too.
+19
View File
@@ -479,6 +479,25 @@ fn paths_added_to_or_moved_in_an_aligned_compound_path_keep_it_aligned() {
assert!(halves(&pts), "slice: {pts:?}");
}
/// A path that `node.move` puts into a pixel-aligned compound path snaps with it, though neither
/// the path nor where it came from was pixel-aligned.
#[test]
fn a_path_node_move_puts_into_an_aligned_compound_path_snaps() {
let mut s = new_doc();
let a = path(&mut s, "M100 100 L110 100 L110 110 L100 110 Z", 1.0);
let b = path(&mut s, "M200 100 L210 100 L210 110 L200 110 Z", 1.0);
s.execute("select.set", &json!({"ids": [a, b]})).unwrap();
let c = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap();
s.execute("object.setPixelAligned", &json!({"ids": [c]})).unwrap();
let loose = path(&mut s, "M300.25 100 L310 100 L310 110 L300.25 110 Z", 1.0);
assert!(!aligned(&s, loose));
s.execute("node.move", &json!({"id": loose, "parent": c, "index": 99})).unwrap();
assert_eq!(s.doc().unwrap().doc.parent_of(NodeId(loose)), Some(NodeId(c)));
let pts = compound_points(&s, c);
assert_eq!(pts.len(), 12);
assert!(halves(&pts), "{pts:?}");
}
/// Art moved by Artboard Options with Move Artwork with Artboard, and the art copies of an
/// artboard copied with its art, stay on the pixel grid.
#[test]
+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]
File diff suppressed because it is too large. Load diff
+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);
}
+567
View File
@@ -50,6 +50,114 @@ fn node(s: &Session, id: NodeId) -> crate::doc::Node {
s.active().unwrap().doc.node(id).unwrap().clone()
}
#[test]
fn path_creation_replays_on_top_of_the_active_layer() {
for mode in ["behind", "inside", "isolation"] {
for create in ["add()", "rectangle(100, 10, 20, 30)", "roundedRectangle(100, 10, 20, 30)", "ellipse()", "polygon()", "star()"] {
let setup = || {
let (mut s, a, b) = doc();
if mode == "isolation" {
let group = s.execute("object.group", &json!({"ids": [a.0, b.0]})).unwrap()["id"].clone();
s.execute("object.isolate", &json!({"id": group})).unwrap();
} else {
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
s.execute("view.drawMode", &json!({"mode": mode})).unwrap();
}
s
};
let mut s = setup();
let start = s.journal.len();
log(&mut s, &format!("app.activeDocument.pathItems.{create};"));
let mut replay = setup();
for (id, params) in s.journal.since(start) {
replay.replay(id, params).unwrap();
}
assert_eq!(art(&replay), art(&s), "{mode}: {create}");
assert_eq!(replay.draw_mode, s.draw_mode);
assert_eq!(replay.active().unwrap().isolation, s.active().unwrap().isolation);
}
}
}
#[test]
fn path_paint_edits_replay_without_changing_new_art() {
let (mut s, a, _) = doc();
let start = s.journal.len();
log(
&mut s,
"var p = app.activeDocument.pathItems[0], c = new RGBColor(); c.red = 200; c.green = 10; c.blue = 30;\
p.fillColor = c; p.strokeColor = c; p.strokeWidth = 7;\
app.activeDocument.pathItems.rectangle(100, 200, 20, 30);",
);
let (mut replay, _, _) = doc();
for (id, params) in s.journal.since(start) {
replay.replay(id, params).unwrap();
}
assert_eq!(node(&replay, a).appearance, node(&s, a).appearance);
assert_eq!(art(&replay), art(&s));
assert_eq!(replay.paint, s.paint);
assert_eq!(replay.fill_active, s.fill_active);
assert_eq!(replay.recent_colors, s.recent_colors);
}
#[test]
fn mixed_anchor_and_segment_picks_keep_independent_anchors() {
for selected in ["ANCHORPOINT", "NOSELECTION"] {
let (mut s, a, _) = doc();
s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 0], [0, 3]]})).unwrap();
s.execute("select.segments", &json!({"id": a.0, "segments": [[0, 1]], "mode": "add"})).unwrap();
let out = log(
&mut s,
&format!(
"var p = app.activeDocument.pathItems[0]; vc.log(p.pathPoints[0].selected);\
vc.log(p.pathPoints[1].selected); vc.log(p.selectedPathPoints.length);\
p.pathPoints[{}].selected = PathPointSelection.{selected}; vc.log(p.selectedPathPoints.length);",
if selected == "ANCHORPOINT" { 1 } else { 3 }
),
);
assert_eq!(out[..3], [json!("PathPointSelection.ANCHORPOINT"), json!("PathPointSelection.NOSELECTION"), json!(2)]);
assert_eq!(out[3], json!(if selected == "ANCHORPOINT" { 3 } else { 1 }));
assert!(!s.active().unwrap().selection.segments.contains_key(&a));
assert_eq!(selected_anchors(&s, a), Some(if selected == "ANCHORPOINT" { vec![(0, 0), (0, 1), (0, 3)] } else { vec![(0, 0)] }));
}
}
#[test]
fn an_empty_path_keeps_closed_before_points_are_added() {
for add in ["p.pathPoints.add(); p.pathPoints.add();", "p.setEntirePath([[0, 0], [10, 0], [10, 10]]);", "p.setEntirePath([]);"] {
let (mut s, _, _) = doc();
let start = s.journal.len();
let out = log(
&mut s,
&format!("var p = app.activeDocument.pathItems.add(); p.closed = true; vc.log(p.closed); vc.run('select.none'); {add} vc.log(p.closed);"),
);
assert_eq!(out, [json!(true), json!(true)]);
let (mut replay, _, _) = doc();
for (id, params) in s.journal.since(start) {
replay.replay(id, params).unwrap();
}
assert_eq!(art(&replay), art(&s));
}
}
#[test]
fn enabling_path_paint_preserves_the_new_art_color_model() {
for fill in [true, false] {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300, "colorMode": "cmyk"})).unwrap();
let a = rect(&mut s, 10.0, 20.0, 30.0, 40.0);
let cmd = if fill { "paint.setFill" } else { "paint.setStroke" };
s.execute(cmd, &json!({"ids": [a.0], "none": true})).unwrap();
s.execute("select.none", &json!({})).unwrap();
s.execute(cmd, &json!({"color": "#12ab34", "keepModel": true})).unwrap();
let new_art = s.new_art();
let want = if fill { new_art.fill_paint() } else { new_art.stroke_paint() };
log(&mut s, if fill { "app.activeDocument.pathItems[0].filled = true;" } else { "app.activeDocument.pathItems[0].stroked = true;" });
let n = node(&s, a);
assert_eq!(if fill { n.appearance.fill_paint() } else { n.appearance.stroke_paint() }, want);
}
}
/// Each number of `v` rounded to 3 decimals, in place.
fn rounded(v: &Value) -> Value {
match v {
@@ -114,6 +222,23 @@ fn path_items_read_with_a_name_give_the_named_path() {
assert_eq!(out, vec![json!([true, "n", true, false, true]), json!(["Not found"])]);
}
#[test]
fn path_items_read_non_index_numbers_as_names() {
for name in ["-1", "1.5", "4294967295"] {
let (mut s, a, _) = doc();
s.execute("object.setProps", &json!({"ids": [a.0], "name": name})).unwrap();
let out = log(
&mut s,
&format!(
"var d = app.activeDocument; vc.log(d.pathItems['{name}'].name);\
vc.log(d.pathItems[{name}].name == d.pageItems[{name}].name);\
vc.log(d.pathItems[-2] === undefined); vc.log(d.pathItems[1].name == '{name}');"
),
);
assert_eq!(out, vec![json!(name), json!(true), json!(true), json!(false)]);
}
}
/// `pathItems` read with a name that is the text of a number but not an array index, such as `-1`
/// or `1.5`, gives the path of that name, and `undefined` when no path has it; `index` still takes
/// a number as a position, as in `pageItems`.
@@ -332,6 +457,354 @@ fn path_point_wrapper_goes_stale_after_remove() {
);
}
#[test]
fn removing_a_point_remaps_selection_and_clears_deleted_geometry() {
let (mut s, a, b) = doc();
s.execute("select.set", &json!({"ids": [b.0]})).unwrap();
let out = log(
&mut s,
"var p = app.activeDocument.pathItems[0]; p.pathPoints[1].selected = PathPointSelection.ANCHORPOINT;\
var anchor = p.pathPoints[1].anchor; p.pathPoints[0].remove();\
vc.log(p.selectedPathPoints.length); vc.log(p.selectedPathPoints[0].anchor.join() == anchor.join());\
vc.log(p.pathPoints[0].selected);",
);
assert_eq!(out, vec![json!(1), json!(true), json!("PathPointSelection.ANCHORPOINT")]);
assert_eq!(selected_anchors(&s, a), Some(vec![(0, 0)]));
assert!(s.active().unwrap().selection.contains(b));
log(&mut s, "app.activeDocument.pathItems[0].pathPoints[0].remove();");
assert!(!s.active().unwrap().selection.contains(a));
assert!(s.active().unwrap().selection.contains(b));
s.execute("select.segments", &json!({"id": a.0, "segments": [[0, 0]], "mode": "set"})).unwrap();
log(&mut s, "app.activeDocument.pathItems[0].pathPoints[0].remove();");
assert!(!s.active().unwrap().selection.contains(a));
assert!(!s.active().unwrap().selection.segments.contains_key(&a));
let (mut s, a, _) = doc();
s.execute("select.segments", &json!({"id": a.0, "segments": [[0, 2]], "mode": "set"})).unwrap();
log(&mut s, "app.activeDocument.pathItems[0].pathPoints[0].remove();");
assert_eq!(s.active().unwrap().selection.segments.get(&a).unwrap().iter().copied().collect::<Vec<_>>(), vec![(0, 1)]);
assert_eq!(selected_anchors(&s, a), Some(vec![(0, 1), (0, 2)]));
}
#[test]
fn removing_a_point_replays_selection_before_moving_anchors() {
for segments in [false, true] {
let setup = || {
let (mut s, a, _) = doc();
s.execute("select.anchors", &json!({"id": a.0, "anchors": [[0, 1], [0, 3]]})).unwrap();
if segments {
s.execute("select.segments", &json!({"id": a.0, "segments": [[0, 2]], "mode": "add"})).unwrap();
} else {
s.execute("select.key", &json!({"id": a.0, "anchor": [0, 1]})).unwrap();
}
s
};
let mut s = setup();
let start = s.journal.len();
log(&mut s, "app.activeDocument.pathItems[0].pathPoints[0].remove();");
let a = s.active().unwrap().selection.objects[0];
// The removed anchor's segments take their other ends with them unless a selected segment
// still ends there, so with segments the anchor after the removed one leaves the selection.
assert_eq!(selected_anchors(&s, a), Some(if segments { vec![(0, 1), (0, 2)] } else { vec![(0, 0), (0, 2)] }));
s.execute("path.moveAnchors", &json!({"dx": 7, "dy": 3})).unwrap();
let mut replay = setup();
for (id, params) in s.journal.since(start) {
replay.replay(id, params).unwrap();
}
assert_eq!(art(&replay), art(&s), "segments: {segments}");
assert_eq!(replay.active().unwrap().selection, s.active().unwrap().selection, "segments: {segments}");
}
}
#[test]
fn removing_the_last_selected_point_of_a_path_keeps_the_current_layer() {
let (mut s, _, b) = doc();
s.execute("layer.new", &json!({"name": "Top"})).unwrap();
let c = rect(&mut s, 200.0, 50.0, 40.0, 40.0);
s.execute("select.set", &json!({"ids": [b.0]})).unwrap();
s.execute("select.anchors", &json!({"id": c.0, "anchors": [[0, 1]], "mode": "add"})).unwrap();
let (layer, rows) = {
let st = s.active().unwrap();
(st.active_layer, st.highlighted_rows())
};
log(&mut s, "app.activeDocument.pathItems[0].pathPoints[1].remove();");
let st = s.active().unwrap();
assert!(!st.selection.contains(c) && st.selection.contains(b));
assert_eq!(st.active_layer, layer);
assert_eq!(st.highlighted_rows(), rows);
}
#[test]
fn emptying_an_unselected_path_keeps_the_targeted_layer() {
let (mut s, a, _) = doc();
let layer = NodeId(s.execute("layer.new", &json!({"name": "Empty"})).unwrap()["id"].as_u64().unwrap());
s.execute("layer.target", &json!({"id": layer.0})).unwrap();
assert!(!s.active().unwrap().selection.contains(a));
log(&mut s, "app.activeDocument.pathItems[0].pathPoints.removeAll();");
assert_eq!(s.active().unwrap().selection.target, Some(layer));
}
#[test]
fn point_selection_reads_flush_removed_closing_segments() {
for segments in [json!([[0, 3]]), json!([[0, 1], [0, 3]])] {
let (mut s, a, _) = doc();
s.execute("select.segments", &json!({"id": a.0, "segments": segments, "mode": "set"})).unwrap();
let out = log(
&mut s,
"var p = app.activeDocument.pathItems[0], first = p.pathPoints[0], last = p.pathPoints[3];\
p.closed = false; vc.log(first.selected); vc.log(last.selected); p.name;\
vc.log(first.selected); vc.log(last.selected); vc.log(p.pathPoints[1].selected);",
);
assert_eq!(out[..4], vec![json!("PathPointSelection.ANCHORPOINT"); 4]);
assert_eq!(out[4], json!("PathPointSelection.NOSELECTION"));
}
}
#[test]
fn opening_a_path_drops_deleted_segments_and_keeps_valid_selection() {
for flush in ["", "try { p.name; vc.log('flushed'); } catch (e) { vc.log(e.message); }"] {
for segments in [json!([[0, 3]]), json!([[0, 1], [0, 3]])] {
let (mut s, a, b) = doc();
s.execute("select.segments", &json!({"id": a.0, "segments": segments, "mode": "set"})).unwrap();
s.execute("select.add", &json!({"ids": [b.0]})).unwrap();
let anchors = selected_anchors(&s, a);
let steps = undo_steps(&s);
let out = log(&mut s, &format!("var p = app.activeDocument.pathItems[0]; p.closed = false; {flush}"));
assert_eq!(out, if flush.is_empty() { vec![] } else { vec![json!("flushed")] });
assert!(!node(&s, a).path_data().unwrap().subpaths[0].closed);
let selection = &s.active().unwrap().selection;
assert!(selection.contains(b));
assert_eq!(selected_anchors(&s, a), anchors);
let kept: Vec<_> = selection.segments.get(&a).into_iter().flatten().copied().collect();
assert_eq!(kept, if segments.as_array().unwrap().len() == 1 { vec![] } else { vec![(0, 1)] });
assert_eq!(undo_steps(&s), steps + 1);
s.execute("edit.undo", &json!({})).unwrap();
assert!(node(&s, a).path_data().unwrap().subpaths[0].closed);
}
}
}
#[test]
fn path_point_handles_are_stale_after_revert_even_when_geometry_is_unchanged() {
let (mut s, a, _) = doc();
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
let folder = vectorcraft_testkit::TempDir::new("script-dom-path-points-revert");
let path = folder.join("saved.vectorcraft");
s.execute("document.save", &json!({"path": path.to_string_lossy()})).unwrap();
for operation in ["pp.length", "pp.parent", "pp[0].anchor = [1, 2]", "pp.add()", "q.anchor", "q.anchor = [1, 2]", "picked.anchor = [1, 2]"] {
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
let before = node(&s, a);
let out = log(
&mut s,
&format!(
"var p = app.activeDocument.pathItems[0], pp = p.pathPoints, q = pp[0], picked = p.selectedPathPoints[0];\
p.name = 'changed'; vc.run('file.revert');\
try {{ {operation}; vc.log('ran'); }} catch (e) {{ vc.log(e.message); }}\
var fresh = app.activeDocument.pathItems[0]; vc.log(fresh.pathPoints.length);\
fresh.pathPoints[0].anchor = [11, 279]; vc.log(fresh.pathPoints[0].anchor);"
),
);
assert_eq!(out, vec![json!("Stale page item"), json!(4), json!([11, 279])], "{operation}");
assert_ne!(node(&s, a).path_data(), before.path_data());
s.execute("file.revert", &json!({})).unwrap();
}
}
#[test]
fn removing_a_subpaths_last_point_remaps_other_subpaths_and_the_key_anchor() {
let (mut s, a, _) = doc();
s.execute(
"path.setAnchors",
&json!({"id": a.0, "subpaths": [
{"anchors": [{"x": 0, "y": 0}]},
{"anchors": [{"x": 10, "y": 10}, {"x": 20, "y": 20}, {"x": 30, "y": 30}]}
]}),
)
.unwrap();
s.execute("select.anchorsMany", &json!({"items": [{"id": a.0, "anchors": [[0, 0], [1, 1], [1, 2]]}], "mode": "set"})).unwrap();
s.execute("select.key", &json!({"id": a.0, "anchor": [1, 2]})).unwrap();
log(&mut s, "app.activeDocument.pathItems[0].pathPoints[0].remove();");
assert_eq!(selected_anchors(&s, a), Some(vec![(0, 1), (0, 2)]));
assert_eq!(s.active().unwrap().selection.key_anchor, Some((a, (0, 2))));
}
#[test]
fn locked_guides_refuse_path_edits_and_bulk_removal() {
let (mut s, a, _) = doc();
log(&mut s, "app.activeDocument.pathItems[0].guides = true;");
s.set_guides_locked(true);
let (before, steps) = (art(&s), undo_steps(&s));
for edit in [
"p.pathPoints[0].anchor = [0, 0]",
"p.pathPoints[0].remove()",
"p.pathPoints.removeAll()",
"p.setEntirePath([[0, 0], [1, 1]])",
"p.closed = false",
"p.translate(1, 0)",
"p.filled = false",
"p.strokeWidth = 12",
"app.activeDocument.pathItems.removeAll()",
] {
let out =
log(&mut s, &format!("var p = app.activeDocument.pathItems[0]; try {{ {edit}; }} catch (e) {{ vc.log(e.name); vc.log(e.message); }}"));
assert_eq!(out.first(), Some(&json!("Error")), "{edit}: {out:?}");
assert!(out[1].as_str().unwrap().contains("guides are locked"), "{edit}: {out:?}");
assert_eq!((art(&s), undo_steps(&s)), (before.clone(), steps), "{edit}");
}
assert!(is_guide(&s, a));
s.set_guides_locked(false);
log(&mut s, "app.activeDocument.pathItems[0].translate(1, 0);");
assert_ne!(art(&s), before);
}
#[test]
fn document_path_creators_use_the_active_layer_during_isolation() {
for create in ["add()", "rectangle(100, 10, 20, 30)", "roundedRectangle(100, 10, 20, 30)", "ellipse()", "polygon()", "star()"] {
let (mut s, a, b) = doc();
let group = NodeId(s.execute("object.group", &json!({"ids": [a.0, b.0]})).unwrap()["id"].as_u64().unwrap());
s.execute("object.isolate", &json!({"id": group.0})).unwrap();
let layer = s.active().unwrap().active_layer.unwrap();
let before = node(&s, group);
let selection = s.active().unwrap().selection.clone();
let steps = undo_steps(&s);
log(&mut s, &format!("app.activeDocument.pathItems.{create};"));
let st = s.active().unwrap();
let made = st.doc.node(layer).unwrap().children().unwrap().last().unwrap();
assert!(matches!(made.kind, NodeKind::Path { .. }), "{create}");
assert_eq!(st.doc.parent_of(made.id), Some(layer), "{create}");
assert_eq!(node(&s, group), before, "{create}");
assert_eq!(st.isolation, Some(group), "{create}");
assert_eq!(st.selection, selection, "{create}");
assert_eq!(undo_steps(&s), steps + 1, "{create}");
}
}
#[test]
fn paint_writes_refuse_generated_graph_design_paths() {
for (kind, command) in [("column", "graph.column"), ("line", "graph.marker")] {
for unpainted in [false, true] {
let (mut s, a, _) = doc();
if unpainted {
s.execute("paint.setFill", &json!({"ids": [a.0], "none": true})).unwrap();
s.execute("paint.setStroke", &json!({"ids": [a.0], "none": true})).unwrap();
}
s.execute("graph.design", &json!({"new": "Square", "ids": [a.0]})).unwrap();
let graph = NodeId(
s.execute(
"graph.create",
&json!({
"type": kind, "x": 100, "y": 100, "width": 200, "height": 150, "csv": ",2024,2025\nQ1,3,2\nQ2,5,4"
}),
)
.unwrap()["id"]
.as_u64()
.unwrap(),
);
s.execute(command, &json!({"id": graph.0, "seriesIndexes": [0], "design": "Square"})).unwrap();
let graph_node = node(&s, graph);
let series = graph_node.children().unwrap().iter().find(|n| n.extras().series_index == Some(0)).unwrap();
let design = series.children().unwrap().iter().find(|n| matches!(n.kind, NodeKind::Group { .. })).unwrap();
let mut paths = Vec::new();
design.walk(&mut |n| {
if matches!(n.kind, NodeKind::Path { .. }) {
paths.push(n.id);
}
});
let path = paths[0];
s.execute("object.setProps", &json!({"ids": [path.0], "name": "generated"})).unwrap();
let (before, steps) = (art(&s), undo_steps(&s));
for edit in [
"p.fillColor = c",
"p.strokeColor = c",
"p.filled = !p.filled",
"p.stroked = !p.stroked",
"p.strokeWidth = 12",
"p.strokeCap = StrokeCap.ROUNDENDCAP",
"p.strokeJoin = StrokeJoin.BEVELENDJOIN",
"p.strokeMiterLimit = 22",
"p.strokeDashes = [3, 4]",
] {
let out = log(
&mut s,
&format!(
"var p = app.activeDocument.pathItems.getByName('generated'), c = new RGBColor(); c.red = 123;\
try {{ {edit}; }} catch (e) {{ vc.log(e.name); vc.log(e.message); }}"
),
);
assert_eq!(out.first(), Some(&json!("Error")), "{kind} {unpainted} {edit}: {out:?}");
assert!(out[1].as_str().unwrap().contains("did not change the path"), "{kind} {edit}: {out:?}");
assert_eq!((art(&s), undo_steps(&s)), (before.clone(), steps), "{kind} {edit}");
}
}
}
}
#[test]
fn overprint_writes_refuse_generated_graph_design_paths() {
for (kind, command) in [("column", "graph.column"), ("line", "graph.marker")] {
let (mut s, a, _) = doc();
s.execute("paint.setFill", &json!({"ids": [a.0], "color": "#ff0000"})).unwrap();
s.execute("paint.setStroke", &json!({"ids": [a.0], "color": "#000000"})).unwrap();
s.execute("graph.design", &json!({"new": "Square", "ids": [a.0]})).unwrap();
let graph = NodeId(
s.execute("graph.create", &json!({"type": kind, "x": 100, "y": 100, "width": 200, "height": 150, "csv": ",2024,2025\nQ1,3,2\nQ2,5,4"}))
.unwrap()["id"]
.as_u64()
.unwrap(),
);
s.execute(command, &json!({"id": graph.0, "seriesIndexes": [0], "design": "Square"})).unwrap();
let graph_node = node(&s, graph);
let series = graph_node.children().unwrap().iter().find(|n| n.extras().series_index == Some(0)).unwrap();
let design = series.children().unwrap().iter().find(|n| matches!(n.kind, NodeKind::Group { .. })).unwrap();
let mut paths = Vec::new();
design.walk(&mut |n| {
if matches!(n.kind, NodeKind::Path { .. }) {
paths.push(n.id);
}
});
s.execute("object.setProps", &json!({"ids": [paths[0].0], "name": "generated"})).unwrap();
let before = (art(&s), undo_steps(&s));
for property in ["fillOverprint", "strokeOverprint"] {
let out = log(
&mut s,
&format!(
"var p = app.activeDocument.pathItems.getByName('generated'), before = p.{property};\
try {{ p.{property} = !before; }} catch (e) {{ vc.log(e.message); }} vc.log(p.{property} == before);"
),
);
assert!(out[0].as_str().unwrap().contains("object.setOverprint did not change the path"), "{kind} {property}: {out:?}");
assert_eq!(out.get(1), Some(&json!(true)), "{kind} {property}");
assert_eq!((art(&s), undo_steps(&s)), before, "{kind} {property}");
}
}
}
#[test]
fn editing_many_observed_paths_keeps_own_handles_and_invalidates_external_changes() {
let (mut s, a, b) = doc();
for i in 0..100 {
rect(&mut s, f64::from(i), 10.0, 2.0, 2.0);
}
let out = log(
&mut s,
&format!(
"var ps = app.activeDocument.pathItems, paths = [], points = [], expected = [];\
for (var i = 0; i < ps.length; i++) {{ paths.push(ps[i]); points.push(ps[i].pathPoints[0]); }}\
for (var i = 0; i < paths.length; i++) {{ paths[i].translate(2, 0); expected.push(points[i].anchor.join()); }}\
var valid = true; for (var i = 0; i < points.length; i++) valid = valid && points[i].anchor.join() == expected[i]; vc.log(valid);\
vc.run('object.move', {{ids: [{a}], dx: 1, dy: 0}});\
try {{ points[100].anchor; }} catch (e) {{ vc.log(e.message); }}\
paths[0].translate(1, 0); vc.log(points[101].anchor.join() == expected[101]);\
vc.run('object.move', {{ids: [{b}], dx: 1, dy: 0}}); vc.run('edit.undo');\
try {{ points[101].anchor; }} catch (e) {{ vc.log(e.message); }}",
a = a.0,
b = b.0
),
);
assert_eq!(out, vec![json!(true), json!("Stale path point"), json!(true), json!("Stale path point")]);
}
#[test]
fn points_read_before_a_removal_or_replacement_go_stale() {
let (mut s, _, _) = doc();
@@ -1250,6 +1723,78 @@ fn locked_paths_and_wrong_objects_are_refused() {
assert!(e.contains("not a PathPoint"), "{e}");
}
/// A point edit of a path on a locked artboard throws `Cannot edit` and changes nothing.
#[test]
fn point_edits_of_a_path_on_a_locked_artboard_are_refused() {
let (mut s, _, _) = doc();
s.execute("artboard.setProps", &json!({"index": 0, "locked": true})).unwrap();
let before = art(&s);
let steps = undo_steps(&s);
for source in [
"app.activeDocument.pathItems[0].pathPoints[0].anchor = [1, 1];",
"app.activeDocument.pathItems[0].pathPoints[0].leftDirection = [1, 1];",
"app.activeDocument.pathItems[0].setEntirePath([[0, 0], [1, 1]]);",
] {
let e = failure(&mut s, source);
assert!(e.contains("Cannot edit PathItem") && e.contains("locked artboard"), "{source}: {e}");
}
assert_eq!(art(&s), before);
assert_eq!(undo_steps(&s), steps);
}
/// A point placed beyond the canvas throws when it is assigned, and the path keeps its points, so a
/// later member call does not lose an assignment that returned.
#[test]
fn a_point_beyond_the_canvas_throws_when_it_is_assigned() {
let (mut s, a, _) = doc();
let before = node(&s, a).path_data().unwrap().subpaths.clone();
let far = crate::MAX_COORD * 1.5;
for source in [
format!("app.activeDocument.pathItems[0].pathPoints[0].anchor = [{far}, 0];"),
format!("app.activeDocument.pathItems[0].pathPoints[0].rightDirection = [0, {far}];"),
format!("app.activeDocument.pathItems[0].setEntirePath([[0, 0], [{far}, 1]]);"),
] {
let e = failure(&mut s, &source);
assert!(e.contains("outside the canvas"), "{source}: {e}");
}
let out = log(
&mut s,
&format!(
"var p = app.activeDocument.pathItems[0], q = p.pathPoints[1];\
q.anchor = [45, 285];\
try {{ p.pathPoints[0].anchor = [{far}, 0]; }} catch (e) {{ vc.log('threw'); }}\
vc.log(q.anchor); vc.log(p.closed);"
),
);
assert_eq!(out, vec![json!("threw"), json!([45, 285]), json!(true)]);
let after = node(&s, a).path_data().unwrap().subpaths.clone();
assert_eq!(after[0].anchors[0], before[0].anchors[0], "the point assigned beyond the canvas stays");
assert_ne!(after[0].anchors[1], before[0].anchors[1], "the earlier assignment is written");
}
#[test]
fn transforms_refuse_moving_gradients_without_the_path() {
for transform in
["translate(5, 10, false, false, true, false)", "rotate(30, false, false, true, false)", "resize(150, 125, false, false, true, false)"]
{
let (mut s, a, b) = doc();
s.execute(
"paint.setFill",
&json!({"ids": [a.0], "gradient": {"kind": "linear", "stops": [{"offset": 0, "color": "#ff0000"}, {"offset": 1, "color": "#0000ff"}]}}),
)
.unwrap();
s.execute("select.set", &json!({"ids": [b.0]})).unwrap();
let before = (art(&s), s.active().unwrap().selection.clone(), undo_steps(&s));
let out = log(&mut s, &format!("try {{ app.activeDocument.pathItems[0].{transform}; }} catch (e) {{ vc.log(e.name); vc.log(e.message); }}"));
assert_eq!(out.first(), Some(&json!("Error")), "{transform}: {out:?}");
assert!(
out[1].as_str().unwrap().contains("Gradients different from") && out[1].as_str().unwrap().contains("not available yet"),
"{transform}: {out:?}"
);
assert_eq!((art(&s), s.active().unwrap().selection.clone(), undo_steps(&s)), before, "{transform}");
}
}
#[test]
fn rotate_positive_is_counterclockwise_and_transforms_move_and_scale() {
let mut s = Session::new();
@@ -1676,3 +2221,25 @@ fn assigning_guides_throws_in_both_directions_while_guides_are_locked() {
log(&mut s, "var ps = app.activeDocument.pathItems; ps[0].guides = true; ps[1].guides = false;");
assert_eq!((is_guide(&s, a), is_guide(&s, b), undo_steps(&s)), (true, false, steps), "a value the path has runs no command");
}
/// A point change made before a call that fails and is put back, here a new document whose
/// profile cannot be read, is kept.
#[test]
fn a_point_change_before_a_failed_new_document_is_kept() {
let dir = std::env::temp_dir().join(format!("vc-script-points-new-doc-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("Print.vectorcraft"), b"not a document").unwrap();
let (mut s, a, _) = doc();
s.attach_new_doc_profiles(dir.clone());
let before = node(&s, a).path_data().unwrap().subpaths.clone();
let out = log(
&mut s,
"app.activeDocument.pathItems[0].pathPoints[0].anchor = [5, 7];\
try { app.documents.addDocument('Print'); } catch (e) { vc.log('refused'); }",
);
let _ = std::fs::remove_dir_all(&dir);
assert_eq!(out, vec![json!("refused")]);
assert_eq!(s.documents().len(), 1);
assert_ne!(node(&s, a).path_data().unwrap().subpaths, before, "the point change is kept");
}
+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();
+97 -1
View File
@@ -1197,6 +1197,102 @@ fn an_image_cannot_be_left_first_in_a_group_named_as_a_tracing() {
let _ = std::fs::remove_dir_all(base);
}
/// Deleting the clipping path of a clip group named as a tracing releases its mask, so `remove()` and
/// `textFrames.removeAll()` refuse it when an image would be left first in the released group.
#[test]
fn removing_a_clipping_path_cannot_leave_an_image_first_in_a_group_named_as_a_tracing() {
let base = folder("release-trace-name");
let (mut s, _) = session(&base, false);
log(
&mut s,
&base,
"var d = app.activeDocument; d.selection = [d.rasterItems[0], d.pathItems.rectangle(10, 10, 20, 20)];\
vc.run('object.clippingMask.make'); d.pageItems[0].name = 'Image Trace';",
);
let before = vectorcraft_format::save(&s.active().unwrap().doc, false);
let steps = undo_steps(&s);
let out = log(
&mut s,
&base,
"var d = app.activeDocument, g = d.pageItems[0], m = '';\
try { d.pathItems[0].remove(); m = 'done'; } catch (e) { m = e.message; } vc.log(m); vc.log(g.clipped);",
);
assert_eq!(out, [json!("Only Image Trace can make a tracing"), json!(true)]);
assert_eq!(vectorcraft_format::save(&s.active().unwrap().doc, false), before);
assert_eq!(undo_steps(&s), steps);
let (mut s, _) = session(&base, false);
log(
&mut s,
&base,
"var d = app.activeDocument, t = d.textFrames.add(); t.contents = 'Clip';\
d.selection = [d.rasterItems[0], t]; vc.run('object.clippingMask.make'); d.pageItems[0].name = 'Image Trace';",
);
let before = vectorcraft_format::save(&s.active().unwrap().doc, false);
let steps = undo_steps(&s);
let out = log(
&mut s,
&base,
"var d = app.activeDocument, g = d.pageItems[0], m = '';\
try { g.textFrames.removeAll(); m = 'done'; } catch (e) { m = e.message; } vc.log(m); vc.log(g.textFrames.length);",
);
assert_eq!(out, [json!("Only Image Trace can make a tracing"), json!(1)]);
assert_eq!(vectorcraft_format::save(&s.active().unwrap().doc, false), before);
assert_eq!(undo_steps(&s), steps);
assert!(traces(&s).is_empty());
let _ = std::fs::remove_dir_all(base);
}
/// `textFrames.removeAll()` and `groupItems.removeAll()` on an ordinary group named as a tracing
/// refuse to leave an image first in it, before the document changes, and delete when another
/// object stays first.
#[test]
fn remove_all_cannot_leave_an_image_first_in_a_group_named_as_a_tracing() {
let base = folder("remove-all-trace-name");
let refused = json!("Only Image Trace can make a tracing");
for (under, call) in [
("var u = d.textFrames.add(); u.contents = 'Under';", "g.textFrames.removeAll();"),
("d.selection = [d.pathItems.rectangle(50, 50, 5, 5)]; vc.run('object.group'); var u = d.pageItems[0];", "g.groupItems.removeAll();"),
] {
let (mut s, _) = session(&base, false);
// The group holds the type or group at the bottom and the image above it.
log(
&mut s,
&base,
&format!(
"var d = app.activeDocument; var p = d.pathItems.rectangle(10, 10, 20, 20); d.selection = [p]; vc.run('object.group');\
var g = d.pageItems[0]; g.name = 'Image Trace'; {under} u.move(g, ElementPlacement.PLACEATEND);\
d.rasterItems[0].move(g, ElementPlacement.PLACEATBEGINNING); p.remove();"
),
);
let before = vectorcraft_format::save(&s.active().unwrap().doc, false);
let steps = undo_steps(&s);
let out = log(
&mut s,
&base,
&format!(
"var d = app.activeDocument, g = d.pageItems[0], m = ''; try {{ {call} m = 'done'; }} catch (e) {{ m = e.message; }} vc.log(m); vc.log(g.typename);"
),
);
assert_eq!(out, [refused.clone(), json!("GroupItem")], "{call}");
assert_eq!(vectorcraft_format::save(&s.active().unwrap().doc, false), before, "{call}");
assert_eq!(undo_steps(&s), steps, "{call}");
assert!(traces(&s).is_empty());
}
// With a rectangle left first, the type goes and the group stays an ordinary group.
let (mut s, _) = session(&base, false);
let out = log(
&mut s,
&base,
"var d = app.activeDocument; d.selection = [d.pathItems.rectangle(10, 10, 20, 20)]; vc.run('object.group');\
var g = d.pageItems[0]; g.name = 'Image Trace'; var t = d.textFrames.add(); t.contents = 'Over';\
t.move(g, ElementPlacement.PLACEATBEGINNING); d.rasterItems[0].move(g, ElementPlacement.PLACEATBEGINNING);\
g.textFrames.removeAll(); vc.log(g.textFrames.length); vc.log(g.pageItems.length); vc.log(g.typename);",
);
assert_eq!(out, [json!(0), json!(2), json!("GroupItem")]);
assert!(traces(&s).is_empty());
let _ = std::fs::remove_dir_all(base);
}
/// `releaseTracing()` keeps only the source image, so it refuses a tracing that holds an object
/// its trace did not make, before the document changes.
#[test]
@@ -1339,7 +1435,7 @@ fn retrace_keeps_the_tracing_note_and_tags() {
/// `pathItems.removeAll()` and `textFrames.removeAll()` refuse to leave an image at the bottom of an
/// ordinary group named as a tracing, before the document changes.
#[test]
fn remove_all_cannot_leave_an_image_first_in_a_group_named_as_a_tracing() {
fn path_and_type_remove_all_cannot_leave_an_image_first_in_a_group_named_as_a_tracing() {
let setup = |bottom: &str| {
format!(
"var d = app.activeDocument; d.selection = [{bottom}]; vc.run('object.group');\
+333 -4
View File
@@ -46,6 +46,17 @@ fn sizes(s: &Session, id: NodeId) -> Vec<(String, f64)> {
}
}
#[test]
fn character_color_attributes_reflect_as_color() {
let (mut s, _) = doc_with("color");
let out = log(
&mut s,
"var a = app.activeDocument.textFrames[0].textRange.characterAttributes;\
vc.log(a.reflect.find('fillColor').dataType); vc.log(a.reflect.find('strokeColor').dataType);",
);
assert_eq!(out, [json!("Color"), json!("Color")]);
}
#[test]
fn text_frames_add_point_area_and_path_type() {
let mut s = Session::new();
@@ -252,6 +263,131 @@ fn setting_the_value_a_range_has_records_no_undo_step() {
assert_eq!(undo_steps(&s), before);
}
fn paints(s: &Session, id: NodeId) -> Vec<(String, Paint, Paint, f64)> {
match &s.active().unwrap().doc.node(id).unwrap().kind {
NodeKind::Text(t) => t.runs.iter().map(|r| (r.text.clone(), r.style.fill.clone(), r.style.stroke.clone(), r.style.stroke_width)).collect(),
_ => panic!("not text"),
}
}
#[test]
fn character_attributes_paint_only_their_own_characters() {
let (mut s, id) = doc_with("abc");
let before = undo_steps(&s);
let out = log(
&mut s,
"var r = app.activeDocument.textFrames[0].textRange, b = r.characters[1].characterAttributes;\
var red = new RGBColor(); red.red = 255; b.fillColor = red;\
var k = new CMYKColor(); k.black = 100; b.strokeColor = k; b.strokeWeight = 2;\
vc.log([b.fillColor.typename, b.fillColor.red, b.strokeColor.typename, b.strokeColor.black, b.strokeWeight]);\
vc.log([r.characters[0].fillColor.red, r.characters[0].strokeColor.typename]);",
);
let n = |v: &Value| v.as_f64().unwrap_or(f64::NAN);
assert_eq!((out[0][0].as_str(), out[0][2].as_str()), (Some("RGBColor"), Some("CMYKColor")), "{out:?}");
assert_eq!((n(&out[0][1]), n(&out[0][3]), n(&out[0][4])), (255.0, 100.0, 2.0), "the paint reads back as given");
assert_ne!(n(&out[1][0]), 255.0, "the first character keeps its fill");
assert_eq!(out[1][1], json!("NoColor"), "the first character keeps no stroke");
let runs = paints(&s, id);
let b = runs.iter().find(|r| r.0 == "b").expect("b is a run of its own");
assert_eq!(b.1, Paint::solid(Color::rgb(1.0, 0.0, 0.0)));
assert_eq!(b.2, Paint::solid(Color::cmyk(0.0, 0.0, 0.0, 1.0)));
assert!(b.3 > 1.0);
assert!(runs.iter().filter(|r| r.0 != "b").all(|r| r.1 != b.1 && r.2 == Paint::None), "{runs:?}");
assert!(undo_steps(&s) > before);
let steps = undo_steps(&s);
log(&mut s, "var b = app.activeDocument.textFrames[0].textRange.characters[1]; b.fillColor = b.fillColor; b.strokeWeight = b.strokeWeight;");
assert_eq!(undo_steps(&s), steps, "setting the paint a range has records no undo step");
log(&mut s, "app.activeDocument.textFrames[0].textRange.characters[1].strokeColor = new NoColor();");
assert!(paints(&s, id).iter().all(|r| r.2 == Paint::None), "a NoColor takes the stroke away");
}
#[test]
fn stroke_weight_reads_back_in_document_points_on_scaled_type() {
let (mut s, id) = doc_with("abc");
s.execute("select.set", &json!({"ids": [id.0]})).unwrap();
s.execute("object.scale", &json!({"sx": 200, "sy": 200})).unwrap();
let out = log(&mut s, "var r = app.activeDocument.textFrames[0].textRange; r.strokeWeight = 2; vc.log(r.strokeWeight);");
assert!((out[0].as_f64().unwrap_or(f64::NAN) - 2.0).abs() < 1e-9, "{out:?}");
let stored = paints(&s, id)[0].3;
assert!(stored < 2.0, "the type's own scale draws the stored width wider: {stored}");
let steps = undo_steps(&s);
log(&mut s, "var r = app.activeDocument.textFrames[0].textRange; r.strokeWeight = r.strokeWeight;");
assert_eq!(undo_steps(&s), steps, "the weight read back is the weight it has");
}
#[test]
fn bad_text_paint_is_refused_without_a_change() {
let (mut s, id) = doc_with("abc");
let before = undo_steps(&s);
let runs = paints(&s, id);
for (src, want) in [
("r.fillColor = 'red';", "fillColor must be a color object"),
("var c = new RGBColor(); c.red = 300; r.strokeColor = c;", "RGBColor.red"),
("r.fillColor = new GradientColor();", "not available yet"),
("r.strokeWeight = -1;", "strokeWeight must be from 0 to 1000"),
("r.characterAttributes.strokeWeight = 'thick';", "strokeWeight must be a finite number"),
] {
let e = failure(&mut s, &format!("var r = app.activeDocument.textFrames[0].textRange; {src}"));
assert!(e.contains(want), "{src}: {e}");
}
assert_eq!(undo_steps(&s), before);
assert_eq!(paints(&s, id), runs);
}
#[test]
fn hidden_or_locked_type_is_not_edited() {
let state = |s: &Session, id: NodeId| match &s.active().unwrap().doc.node(id).unwrap().kind {
NodeKind::Text(t) => (paints(s, id), plain(s, id), sizes(s, id), t.para_at(0).justify),
_ => panic!("not text"),
};
for hide in ["t.locked = true;", "t.hidden = true;"] {
for edit in [
"r.characters[1].fillColor = red;",
"r.size = 30;",
"r.contents = 'xyz';",
"r.characters.add('!');",
"r.justification = Justification.CENTER;",
"var b = app.activeDocument.characterStyles.add('Big'); b.characterAttributes.size = 30; b.applyTo(r);",
"var b = app.activeDocument.characterStyles.add('Big'); b.characterAttributes.size = 30; b.applyTo(t);",
"var c = app.activeDocument.paragraphStyles.add('C'); c.paragraphAttributes.justification = Justification.CENTER; c.applyTo(r);",
] {
// Each case starts from a fresh frame, so the hidden cases test a frame that is only hidden.
let (mut s, id) = doc_with("abc");
let before = state(&s, id);
let e = failure(
&mut s,
&format!("var t = app.activeDocument.textFrames[0], r = t.textRange, red = new RGBColor(); red.red = 255; {hide} {edit}"),
);
assert!(e.contains("Cannot edit TextFrame"), "{hide} {edit}: {e}");
assert_eq!(state(&s, id), before, "{hide} {edit}");
}
}
}
#[test]
fn text_added_after_a_range_ending_inside_a_character_goes_after_that_character() {
let (mut s, id) = doc_with("abc");
let out = log(
&mut s,
"var t = app.activeDocument.textFrames[0]; t.contents = '\\uD83D\\uDE00X'; var r = t.textRange; r.length = 1;\
var x = t.characters.add('!', r); vc.log([x.contents, r.contents]);",
);
assert_eq!(plain(&s, id), "\u{1F600}!X");
// Setting `length` to 1 moves the end out to the end of the emoji, and text added at a range's
// end joins the range.
assert_eq!(out, vec![json!(["!", "\u{1F600}!"])]);
// An empty range there sits after the character too, and styling it changes nothing.
let runs = paints(&s, id);
let out = log(
&mut s,
"var t = app.activeDocument.textFrames[0]; var r = t.textRange; r.length = 1;\
var e = t.characters.add('', r), red = new RGBColor(); red.red = 255; e.fillColor = red; vc.log(e.length);",
);
assert_eq!(out, vec![json!(0)]);
assert_eq!(paints(&s, id), runs);
}
#[test]
fn a_leading_equal_to_the_auto_leading_turns_auto_leading_off() {
let (mut s, id) = doc_with("abc");
@@ -331,8 +467,13 @@ fn auto_leading_reads_the_paragraph_of_the_range_inside_one_run() {
fn a_font_that_missing_glyph_protection_keeps_off_some_characters_throws() {
let (from, to, c) = ("Source Sans 3", "JetBrains Mono", '\u{180}');
let db = vectorcraft_text::FontDb::global();
let covers = |f: &str| db.face(f, "Regular").is_some_and(|face| face.covers(c));
if !covers(from) || covers(to) {
// Both faces ship in assets/fonts: with the bundled fonts the test fails when either one is
// missing, and without them it is skipped. A lookup that falls back to another face counts
// as missing.
let regular = |family: &str| db.face(family, "Regular").filter(|f| f.family == family && f.style == "Regular");
let faces = regular(from).zip(regular(to));
assert!(faces.is_some() || !cfg!(feature = "bundled-fonts"), "{from} Regular or {to} Regular is not available");
if !faces.is_some_and(|(source, dest)| source.covers(c) && !dest.covers(c)) {
return; // Installed fonts of these names cover other characters.
}
let mut s = Session::new();
@@ -465,7 +606,7 @@ fn text_fonts_list_and_assign_fonts_by_name() {
&format!(
"var f = app.textFonts, m = '';\
try {{ f.getByName('No Such Font Anywhere'); }} catch (e) {{ m = e.message; }} vc.log(m);\
try {{ f.index('No Such Font Anywhere'); }} catch (e) {{ m = e.message; }} vc.log(m);\
m = ''; try {{ f.index('No Such Font Anywhere'); }} catch (e) {{ m = e.message; }} vc.log(m);\
vc.log(f.length > 0); var r = app.activeDocument.textFrames[0].textRange, k = f[{pos}];\
vc.log([k.family, k.style]); r.textFont = k; vc.log(r.textFont.family === k.family && r.textFont.style === k.style);\
vc.log(f.getByName(k.family + ' ' + k.style).family === k.family); vc.log(f[f.length] === undefined);"
@@ -547,7 +688,7 @@ fn collections_of_text_add_words_characters_and_paragraphs() {
}
// Empty contents add nothing; bad arguments throw before anything changes.
let (mut s, id) = doc_with("ab");
s.execute("text.create", &json!({"x": 20, "y": 200, "text": "other", "size": 12})).unwrap();
let other = NodeId(s.execute("text.create", &json!({"x": 20, "y": 200, "text": "other", "size": 12})).unwrap()["id"].as_u64().unwrap());
let before = undo_steps(&s);
// `textFrames` lists the topmost first, so the newer "other" is [0].
let out = log(&mut s, "var n = app.activeDocument.textFrames[0].words.add(''); vc.log([n.length, n.start]);");
@@ -558,12 +699,86 @@ fn collections_of_text_add_words_characters_and_paragraphs() {
("t.words.add('x', t.words[0], ElementPlacement.INSIDE)", "insertionLocation must be"),
("t.words.add('x', app.activeDocument.textFrames[1])", "same text frame"),
("t.words.add('x', 5)", "relativeObject must be a TextRange or a TextFrame"),
// A range of a frame that is gone stays stale rather than of the wrong type.
(
"var o = app.activeDocument.textFrames[1].characters[0]; app.activeDocument.textFrames[1].remove(); t.words.add('x', o)",
"Stale text range",
),
] {
let e = failure(&mut s, &format!("var t = app.activeDocument.textFrames[0]; {call};"));
assert!(e.contains(want), "{call}: {e}");
}
assert_eq!(undo_steps(&s), before);
assert_eq!(plain(&s, other), "other");
assert_eq!(plain(&s, id), "ab");
// A range of a frame that was removed is stale, not of the wrong class.
let e = failure(&mut s, "var f = app.activeDocument.textFrames, b = f[0], a = f[1], r = b.textRange; b.remove(); a.characters.add('x', r);");
assert!(e.contains("Stale text range"), "{e}");
assert_eq!(plain(&s, id), "ab");
}
/// Type on a locked artboard, and a hidden or locked path given to `areaText` or `pathText`, are
/// not changed.
#[test]
fn protected_type_and_paths_are_not_converted_or_edited() {
let (mut s, id) = doc_with("abc");
s.edit("Lock Artboard", |d, _| {
d.artboards[0].locked = true;
Ok(())
})
.unwrap();
let steps = undo_steps(&s);
for edit in ["t.contents = 'xyz';", "t.textRange.size = 30;", "t.createOutline();", "t.convertPointObjectToAreaObject();"] {
let e = failure(&mut s, &format!("var t = app.activeDocument.textFrames[0]; {edit}"));
assert!(e.contains("Cannot edit TextFrame") && e.contains("locked artboard"), "{edit}: {e}");
}
assert_eq!(plain(&s, id), "abc");
assert_eq!(undo_steps(&s), steps);
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
s.execute("path.create", &json!({"anchors": [{"x": 20, "y": 200}, {"x": 300, "y": 220}], "closed": false})).unwrap();
for (hide, call) in [("p.locked = true;", "areaText(p)"), ("p.hidden = true;", "pathText(p)")] {
let e = failure(&mut s, &format!("var d = app.activeDocument, p = d.pathItems[0]; {hide} d.textFrames.{call};"));
assert!(e.contains("Cannot edit PathItem"), "{call}: {e}");
assert_eq!(log(&mut s, "var d = app.activeDocument; vc.log([d.pathItems.length, d.textFrames.length]);"), vec![json!([1, 0])]);
}
}
/// Type on a locked artboard stays: `removeAll()` throws and deletes nothing, as
/// `pathItems.removeAll()` does.
#[test]
fn text_frames_remove_all_refuses_type_on_a_locked_artboard() {
let (mut s, id) = doc_with("ab");
let lock = |s: &mut Session, locked: bool| {
s.edit("Lock Artboard", |d, _| {
d.artboards[0].locked = locked;
Ok(())
})
.unwrap();
};
lock(&mut s, true);
let steps = undo_steps(&s);
let e = failure(&mut s, "app.activeDocument.textFrames.removeAll();");
assert!(e.contains("cannot delete objects on a locked artboard") && e.contains(&id.0.to_string()), "{e}");
assert_eq!(plain(&s, id), "ab");
assert_eq!(undo_steps(&s), steps);
lock(&mut s, false);
log(&mut s, "app.activeDocument.textFrames.removeAll();");
assert_eq!(log(&mut s, "vc.log(app.activeDocument.textFrames.length);"), vec![json!(0)]);
}
/// Text added after a range that ends inside a character goes after the whole character, and the
/// range returned holds the added text.
#[test]
fn text_added_after_half_a_character_goes_after_it() {
let (mut s, id) = doc_with("a\u{1F600}b");
let out = log(
&mut s,
"var t = app.activeDocument.textFrames[0], r = t.characters[0]; r.length = 2;\
var x = t.characters.add('X', r, ElementPlacement.PLACEAFTER); vc.log([x.start, x.contents]);",
);
assert_eq!(out, vec![json!([3, "X"])]);
assert_eq!(plain(&s, id), "a\u{1F600}Xb");
}
#[test]
@@ -640,6 +855,120 @@ fn type_made_with_a_large_id_is_the_new_type() {
assert_eq!(plain(&s, NodeId(big)), "");
}
/// A script that builds a layer `base` holding type `back`, a group `g` (type `g-text` and a
/// group `gg` holding type `gg-text`) and type `front`, a sublayer `sub` of it holding type
/// `sub-text`, and a layer `other` holding type `other-text`, which it leaves current.
const NESTED_TYPE: &str = "var d = app.activeDocument, L0 = d.layers[0]; L0.name = 'base';\
function put(c, name, y) { var t = c.textFrames.pointText([20, y]); t.contents = name; t.name = name; return t; }\
put(L0, 'back', 20); var g = L0.groupItems.add(); g.name = 'g'; put(g, 'g-text', 40);\
var gg = g.groupItems.add(); gg.name = 'gg'; put(gg, 'gg-text', 60); put(L0, 'front', 80);\
var sub = L0.layers.add(); sub.name = 'sub'; put(sub, 'sub-text', 100);\
var L1 = d.layers.add(); L1.name = 'other'; put(L1, 'other-text', 120); d.activeLayer = L1;\
function names(c) { var a = []; for (var i = 0; i < c.length; i++) a.push(c[i].name); return a.join(','); }";
#[test]
fn a_layers_and_a_groups_text_frames_list_only_their_own_type() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
let out = log(
&mut s,
&format!(
"{NESTED_TYPE} vc.log([names(L0.textFrames), names(g.textFrames), names(sub.textFrames), names(L1.textFrames)]);\
vc.log([L0.textFrames.typename, L0.textFrames.parent.name, g.textFrames.parent.typename, g.textFrames.parent.name]);\
vc.log([L0.textFrames.getByName('front').name, L0.textFrames.index(1).name, L0.textFrames[2] === undefined]);\
vc.log(d.textFrames.length);"
),
);
assert_eq!(out[0], json!(["front,back", "g-text", "sub-text", "other-text"]));
assert_eq!(out[1], json!(["TextFrames", "base", "GroupItem", "g"]));
assert_eq!(out[2], json!(["front", "back", true]));
assert_eq!(out[3], json!(6));
// Type inside the layer's group or sublayer is not the layer's own.
let e = failure(&mut s, &format!("{NESTED_TYPE} L0.textFrames.getByName('gg-text');"));
assert!(e.contains("Not found"), "{e}");
}
#[test]
fn text_frames_of_a_layer_or_group_put_new_type_in_it() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
s.execute("shape.rectangle", &json!({"x": 200, "y": 10, "width": 100, "height": 50})).unwrap();
let before = undo_steps(&s);
// The rectangle is in the first layer, which becomes `base`; `other` is current while the
// collections of `base` and `g` add type.
let out = log(
&mut s,
&format!(
"var rect = app.activeDocument.pageItems[0]; {NESTED_TYPE}\
var t = L0.textFrames.add(); t.name = 'added';\
vc.log([t.layer.name, L0.pageItems[0].name, t.kind, d.activeLayer.name]);\
var gt = g.textFrames.add(); gt.name = 'g-added'; vc.log([gt.parent.name, g.pageItems[0].name]);\
var at = g.textFrames.areaText(rect); at.name = 'area'; vc.log([at.parent.name, g.pageItems[0].name, at.kind]);\
g.textFrames.removeAll(); vc.log([names(g.pageItems), names(L0.textFrames)]);"
),
);
assert_eq!(out[0], json!(["base", "added", "TextType.POINTTEXT", "other"]));
assert_eq!(out[1], json!(["g", "g-added"]));
assert_eq!(out[2], json!(["g", "area", "TextType.AREATEXT"]));
// removeAll takes the group's own type and leaves the type inside its group.
assert_eq!(out[3], json!(["gg", "added,front,back"]));
assert_eq!(undo_steps(&s), before + 1);
// A locked layer and a hidden group take no new type, and the run changes nothing.
let before = undo_steps(&s);
let e = failure(&mut s, &format!("{NESTED_TYPE} L0.locked = true; L0.textFrames.add();"));
assert!(e.contains("hidden or locked"), "{e}");
let e = failure(&mut s, &format!("{NESTED_TYPE} g.hidden = true; g.textFrames.pointText([5, 5]);"));
assert!(e.contains("hidden or locked"), "{e}");
assert_eq!(undo_steps(&s), before);
}
/// `textFrames.removeAll()` on type that clips a group releases the mask, so the object above the
/// type stays an ordinary member and is not made the clipping path.
#[test]
fn text_frames_remove_all_releases_a_mask_the_type_clips() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
let a = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 100, "height": 50})).unwrap()["id"].as_u64().unwrap();
let b = s.execute("shape.rectangle", &json!({"x": 20, "y": 20, "width": 100, "height": 50})).unwrap()["id"].as_u64().unwrap();
let t = s.execute("text.create", &json!({"x": 20, "y": 100, "text": "clip", "size": 12})).unwrap()["id"].as_u64().unwrap();
s.execute("select.set", &json!({"ids": [a, b, t]})).unwrap();
let g = NodeId(s.execute("object.clippingMask.make", &json!({})).unwrap()["id"].as_u64().unwrap());
s.execute("select.none", &json!({})).unwrap();
let first = |s: &Session| s.active().unwrap().doc.node(g).unwrap().children().unwrap().first().map(|c| c.id);
assert_eq!(first(&s), Some(NodeId(t)), "the type is the clipping path");
let steps = undo_steps(&s);
let out = log(&mut s, "app.activeDocument.textFrames.removeAll(); vc.log(app.activeDocument.groupItems[0].clipped);");
assert_eq!(out, [json!(false)]);
let st = s.active().unwrap();
assert!(!st.doc.node(g).unwrap().clips());
assert_eq!(st.doc.node(g).unwrap().children().unwrap().len(), 2);
// The run is one undo step, and undoing it puts back both the type and its mask.
assert_eq!(undo_steps(&s), steps + 1);
s.execute("edit.undo", &json!({})).unwrap();
assert!(s.active().unwrap().doc.node(g).unwrap().clips());
assert_eq!(first(&s), Some(NodeId(t)));
}
#[test]
fn text_create_puts_type_in_the_layer_or_group_it_names() {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 400, "height": 300})).unwrap();
let group = s.execute("object.newGroup", &json!({})).unwrap()["id"].as_u64().unwrap();
let rect = s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 20, "height": 20})).unwrap()["id"].as_u64().unwrap();
// A new layer is current, and a locked one takes no type.
let locked = s.execute("layer.new", &json!({})).unwrap()["id"].as_u64().map(NodeId).unwrap();
s.execute("layer.setProps", &json!({"id": locked.0, "locked": true})).unwrap();
let before = undo_steps(&s);
for bad in [json!("1"), json!(rect), json!(9999), json!(locked.0)] {
assert!(s.execute("text.create", &json!({"x": 5, "y": 5, "text": "a", "parent": bad})).is_err(), "{bad}");
}
assert_eq!(undo_steps(&s), before);
let id = s.execute("text.create", &json!({"x": 5, "y": 5, "text": "a", "parent": group})).unwrap()["id"].as_u64().unwrap();
let d = &s.active().unwrap().doc;
assert_eq!(d.parent_of(NodeId(id)), Some(NodeId(group)));
assert_eq!(undo_steps(&s), before + 1);
}
#[test]
fn text_members_refuse_objects_of_other_classes() {
let (mut s, _) = doc_with("abc");
@@ -96,10 +96,11 @@ const INSIDE: &[(&str, &str)] = &[
),
(
"",
"activeDocument activeDocument= app Application BlendModes CoordinateSystem Document DocumentArtboardLayout DocumentColorSpace \
DocumentPreset DocumentPresetType DocumentPreviewMode DocumentRasterResolution DocumentTransparencyGrid documents \
Documents ElementPlacement Layer PageItem PageItems PathItem PathItems PathPoint PathPointSelection PathPoints PlacedItem \
PlacedItems PluginItem PointType PolarityValues Preferences RasterItem RasterItems RulerUnits ScreenMode selection \
"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 \
selection= StrokeCap StrokeJoin Tag Tags TracingObject TracingOptions Transformation View Views ZOrderMethod",
),
("Application.", "prototype"),
@@ -128,14 +129,14 @@ const INSIDE: &[(&str, &str)] = &[
("Document.", "prototype"),
(
"Document.prototype.",
"activeLayer activeLayer= artboards artboards= characterStyles close constructor convertCoordinate \
"activeLayer activeLayer= artboards characterStyles close compoundPathItems constructor convertCoordinate \
defaultFillColor defaultFillColor= defaultFillOverprint defaultFillOverprint= defaultFilled defaultFilled= \
defaultStrokeCap defaultStrokeCap= defaultStrokeColor defaultStrokeColor= defaultStrokeDashOffset \
defaultStrokeDashOffset= defaultStrokeDashes defaultStrokeDashes= defaultStrokeJoin defaultStrokeJoin= \
defaultStrokeMiterLimit defaultStrokeMiterLimit= defaultStrokeOverprint defaultStrokeOverprint= \
defaultStrokeWidth defaultStrokeWidth= defaultStroked defaultStroked= documentColorSpace fullName groupItems \
groupItems= height layers layers= name pageItems paragraphStyles parent path pathItems placedItems rasterItems \
rulerOrigin rulerOrigin= rulerUnits saved saved= scaleFactor selection selection= stories swatches swatches= \
height layers name pageItems paragraphStyles parent path pathItems placedItems rasterItems rulerOrigin \
rulerOrigin= rulerUnits saved saved= scaleFactor selection selection= stories swatches swatches= \
symbols symbols= tags textFrames toString typename views width",
),
("Views.", "prototype"),
@@ -143,15 +144,48 @@ const INSIDE: &[(&str, &str)] = &[
("View.", "prototype"),
("View.prototype.", "bounds centerPoint centerPoint= constructor parent screenMode screenMode= toString typename zoom zoom="),
("Layer.", "prototype"),
("Layer.prototype.", "constructor name toString typename"),
(
"Layer.prototype.",
"artworkKnockout artworkKnockout= blendingMode blendingMode= color color= compoundPathItems constructor \
dimPlacedImages dimPlacedImages= groupItems hasSelectedArtwork hasSelectedArtwork= isIsolated layers locked \
locked= move name name= opacity opacity= pageItems parent pathItems pathItems= placedItems placedItems= preview \
preview= printable printable= rasterItems rasterItems= remove sliced sliced= symbolItems symbolItems= textFrames \
toString typename visible visible= zOrder zOrderPosition",
),
("Layers.", "prototype"),
("Layers.prototype.", "add constructor getByName index length parent removeAll toString typename"),
("GroupItem.", "prototype"),
(
"GroupItem.prototype.",
"clipped clipped= compoundPathItems constructor groupItems pageItems pathItems pathItems= placedItems placedItems= \
rasterItems rasterItems= symbolItems symbolItems= textFrames",
),
("GroupItems.", "prototype"),
("GroupItems.prototype.", "add constructor createFromFile createFromFile= getByName index length parent removeAll toString typename"),
("CompoundPathItem.", "prototype"),
("CompoundPathItem.prototype.", "constructor pathItems"),
("CompoundPathItems.", "prototype"),
("CompoundPathItems.prototype.", "add constructor getByName index length parent removeAll toString typename"),
("Artboard.", "prototype"),
(
"Artboard.prototype.",
"artboardRect artboardRect= constructor name name= parent remove rulerOrigin rulerOrigin= rulerPAR rulerPAR= \
showCenter showCenter= showCrossHairs showCrossHairs= showSafeAreas showSafeAreas= toString typename",
),
("Artboards.", "prototype"),
(
"Artboards.prototype.",
"add constructor getActiveArtboardIndex getByName index insert length parent remove setActiveArtboardIndex \
toString typename",
),
("PageItems.", "prototype"),
("PageItems.prototype.", "constructor getByName index length parent removeAll toString typename"),
("PageItem.", "prototype"),
(
"PageItem.prototype.",
"artworkKnockout artworkKnockout= blendingMode blendingMode= bringInPerspective bringInPerspective= constructor \
controlBounds duplicate editable geometricBounds height height= hidden hidden= isIsolated isIsolated= layer layer= \
left left= locked locked= move name name= note note= opacity opacity= parent pixelAligned pixelAligned= position \
controlBounds duplicate editable geometricBounds height height= hidden hidden= isIsolated isIsolated= layer left \
left= locked locked= move name name= note note= opacity opacity= parent pixelAligned pixelAligned= position \
position= remove resize rotate selected selected= sliced sliced= tags toString top top= transform translate \
typename uRL uRL= uuid uuid= visibilityVariable visibilityVariable= visibleBounds \
width width= wrapInside wrapInside= wrapOffset wrapOffset= wrapped wrapped= zOrder zOrderPosition",
@@ -188,7 +222,10 @@ const INSIDE: &[(&str, &str)] = &[
viewVector=",
),
("PathItems.", "prototype"),
("PathItems.prototype.", "add constructor ellipse getByName index length parent polygon rectangle removeAll roundedRectangle star typename"),
(
"PathItems.prototype.",
"add constructor ellipse getByName index length parent polygon rectangle removeAll roundedRectangle star toString typename",
),
("PathItem.", "prototype"),
(
"PathItem.prototype.",
@@ -413,12 +450,14 @@ const INSIDE: &[(&str, &str)] = &[
"TextRange.prototype.",
"autoLeading autoLeading= baselineShift baselineShift= changeCaseTo changeCaseTo= characterAttributes characterOffset \
characterOffset= characterStyles characters constructor contents contents= deSelect deSelect= \
duplicate duplicate= end end= firstLineIndent firstLineIndent= getLocalCharOverridesJSON getLocalCharOverridesJSON= \
duplicate duplicate= end end= fillColor fillColor= firstLineIndent firstLineIndent= getLocalCharOverridesJSON \
getLocalCharOverridesJSON= \
getLocalParaOverridesJSON getLocalParaOverridesJSON= getParagraphLength getTextRunLength horizontalScale \
horizontalScale= insertionPoints insertionPoints= justification justification= kerning kerning= leading leading= \
leftIndent leftIndent= length length= lines lines= move move= paragraphAttributes paragraphStyles \
paragraphs parent remove rightIndent rightIndent= rotation rotation= select select= size size= spaceAfter spaceAfter= \
spaceBefore spaceBefore= start start= story strikeThrough strikeThrough= textFont textFont= textRanges \
spaceBefore spaceBefore= start start= story strikeThrough strikeThrough= strokeColor strokeColor= \
strokeWeight strokeWeight= textFont textFont= textRanges \
textRanges= textSelection textSelection= tracking tracking= typename underline underline= verticalScale \
verticalScale= words",
),
@@ -431,9 +470,9 @@ const INSIDE: &[(&str, &str)] = &[
("CharacterAttributes.", "prototype"),
(
"CharacterAttributes.prototype.",
"autoLeading autoLeading= baselineShift baselineShift= constructor horizontalScale horizontalScale= leading leading= \
rotation rotation= size size= strikeThrough strikeThrough= textFont textFont= tracking tracking= typename underline \
underline= verticalScale verticalScale=",
"autoLeading autoLeading= baselineShift baselineShift= constructor fillColor fillColor= horizontalScale horizontalScale= \
leading leading= rotation rotation= size size= strikeThrough strikeThrough= strokeColor strokeColor= strokeWeight \
strokeWeight= textFont textFont= tracking tracking= typename underline underline= verticalScale verticalScale=",
),
("ParagraphAttributes.", "prototype"),
(
@@ -448,9 +487,9 @@ const INSIDE: &[(&str, &str)] = &[
("CharacterStyleAttributes.", "prototype"),
(
"CharacterStyleAttributes.prototype.",
"autoLeading autoLeading= baselineShift baselineShift= constructor horizontalScale horizontalScale= leading leading= \
rotation rotation= size size= strikeThrough strikeThrough= textFont textFont= tracking tracking= typename underline \
underline= verticalScale verticalScale=",
"autoLeading autoLeading= baselineShift baselineShift= constructor fillColor fillColor= horizontalScale horizontalScale= \
leading leading= rotation rotation= size size= strikeThrough strikeThrough= strokeColor strokeColor= strokeWeight \
strokeWeight= textFont textFont= tracking tracking= typename underline underline= verticalScale verticalScale=",
),
("ParagraphStyles.", "prototype"),
("ParagraphStyles.prototype.", "add constructor getByName index length parent removeAll typename"),
@@ -486,12 +525,12 @@ const INSIDE: &[(&str, &str)] = &[
"StoryRange.prototype.",
"autoLeading autoLeading= baselineShift baselineShift= changeCaseTo changeCaseTo= characterAttributes \
characterAttributes= characterOffset characterOffset= characterStyles characterStyles= characters constructor \
contents contents= deSelect deSelect= duplicate duplicate= end end= getLocalCharOverridesJSON \
contents contents= deSelect deSelect= duplicate duplicate= end end= fillColor fillColor= getLocalCharOverridesJSON \
getLocalCharOverridesJSON= getLocalParaOverridesJSON getLocalParaOverridesJSON= getParagraphLength getTextRunLength \
getTextRunLength= horizontalScale horizontalScale= insertionPoints insertionPoints= kerning kerning= leading leading= \
length length= lines lines= move move= paragraphAttributes paragraphAttributes= paragraphStyles paragraphStyles= \
paragraphs parent remove rotation rotation= select select= size size= start start= story strikeThrough \
strikeThrough= textFont textFont= textRanges textRanges= textSelection textSelection= tracking tracking= typename \
strikeThrough= strokeColor strokeColor= strokeWeight strokeWeight= textFont textFont= textRanges textRanges= textSelection textSelection= tracking tracking= typename \
underline underline= verticalScale verticalScale= words",
),
("StoryCharacters.", "prototype"),
@@ -520,12 +559,10 @@ const INSIDE: &[(&str, &str)] = &[
];
/// The classes the host adds with nothing but a prototype and its constructor: the page item types
/// other than `PathItem`, `PlacedItem` and `RasterItem`, the color classes and the save and export
/// option classes.
const BARE_CLASSES: &str = "BlendItem CMYKColor CompoundPathItem EnvelopeItem GradientColor GraphItem GrayColor GroupItem \
IntertwineItem LabColor MeshItem NoColor PatternColor PlacedDocumentItem RGBColor RepeatItem SpotColor SymbolItem \
cmykColor EPSSaveOptions ExportOptionsAutoCAD ExportOptionsJPEG ExportOptionsPNG24 ExportOptionsSVG IllustratorSaveOptions \
PDFSaveOptions";
/// 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";
/// 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
@@ -997,6 +997,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",
+60
View File
@@ -560,3 +560,63 @@ fn rgb_numbers_stand_in_editor_documents_only() {
assert!(near(color(true), Color::rgb(0.2, 0.6, 0.4)), "{:?}", color(true));
assert!(!near(color(false), Color::rgb(0.2, 0.6, 0.4)), "{:?}", color(false));
}
/// The space the scan of a page holding colour spaces `spaces` finds for a Gold Separation (tint
/// transform [`GOLD_TINT`]).
fn gold_space(spaces: &str) -> Space {
use craft::pdf::interpret::Function;
use craft::pdf::syntax::object::{FromBytes, Object};
let key = format!("{:?}", Function::new(&Object::from_bytes(GOLD_TINT.as_bytes()).unwrap()).unwrap());
let pdf = craft::pdf::syntax::Pdf::new(pdf(&[page_with(spaces, &[])], None)).unwrap();
Colors::new(&pdf, vec![]).space_of(&format!("ColorSpace(Separation(Separation {{ tint_transform: {key} }}))"), 1, None)
}
const GOLD_TINT: &str = "<< /FunctionType 2 /Domain [0 1] /C0 [0 0 0 0] /C1 [0 0 1 0] /N 1 >>";
/// The scan for ink spaces looks 32 levels into an object and no deeper.
#[test]
fn ink_spaces_nested_past_the_scan_depth_are_not_found() {
let gold = format!("[/Separation /Gold /DeviceCMYK {GOLD_TINT}]");
let nested = |levels: usize| format!("/A {}{gold}{}", "[".repeat(levels), "]".repeat(levels));
assert_eq!(gold_space(&nested(20)), Space::Inks(0));
assert_eq!(gold_space(&nested(40)), Space::Other);
}
/// The scan keeps 4,096 ink spaces: a space after that many others is not found.
#[test]
fn ink_spaces_past_the_scan_count_are_not_found() {
let filler = "<< /FunctionType 2 /Domain [0 1] /C0 [0 0 0 0] /C1 [0 1 0 0] /N 1 >>";
let spaces = |n: usize| -> String {
let fillers: String = (0..n).map(|i| format!("[/Separation /Ink{i} /DeviceCMYK {filler}]")).collect();
format!("/A [{fillers}[/Separation /Gold /DeviceCMYK {GOLD_TINT}]]")
};
assert_eq!(gold_space(&spaces(4095)), Space::Inks(4095));
assert_eq!(gold_space(&spaces(4096)), Space::Other);
}
/// A one-ink image of more pixels than a CMYK image may have is refused before its samples are
/// decoded; the same samples read at a smaller size are not.
#[test]
fn one_ink_images_past_the_pixel_cap_are_refused() {
use std::io::Write;
let side = 8193u32;
let row = (side as usize).div_ceil(8);
let mut z = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::best());
z.write_all(&vec![0u8; row * side as usize]).unwrap();
let hex: String = z.finish().unwrap().iter().map(|b| format!("{b:02x}")).collect();
let image = format!(
"<< /Type /XObject /Subtype /Image /Width {side} /Height {side} /BitsPerComponent 1 /ColorSpace [/Separation /Gold /DeviceCMYK {GOLD_TINT}] /Filter [/ASCIIHexDecode /FlateDecode] /Length {} >>\nstream\n{hex}>\nendstream",
hex.len() + 1
);
let file = craft::pdf::syntax::Pdf::new(pdf_with(&[PdfPage::new(10.0, 10.0, "")], &[&image], None)).unwrap();
let st = file
.objects()
.into_iter()
.find_map(|o| match o {
craft::pdf::syntax::object::Object::Stream(s) if s.dict().contains_key(b"Width") => Some(s),
_ => None,
})
.unwrap();
assert_eq!(crate::import_image::tint_gray(&st, side, side).map(|g| g.len()), Err(crate::import_image::UNREAD_TINTS));
assert_eq!(crate::import_image::tint_gray(&st, 16, 2), Ok(vec![255; 32]));
}
+47
View File
@@ -370,6 +370,53 @@ fn tiling_patterns_become_pattern_swatches() {
assert_eq!(colors, vec![Color::rgb(1.0, 0.0, 0.0), Color::rgb(0.0, 0.0, 1.0)]);
}
/// Links in the chains of nested patterns and soft masks below: more than are read.
const CHAIN: usize = 12;
/// The warnings of opening a page drawing `content` with `resources`, plus `objects`.
fn warnings_of(objects: &[String], resources: &str, content: &str) -> Vec<String> {
let extra: Vec<&str> = objects.iter().map(String::as_str).collect();
open_with(&one_page(content, resources, &extra), |_| {}).warnings
}
/// Tiling patterns whose cells fill with the next pattern are read only so many levels deep: a
/// chain of them opens, with a warning.
#[test]
fn patterns_nested_too_deeply_stop_with_a_warning() {
let first = first_extra(1);
let cells: Vec<String> = (0..CHAIN)
.map(|i| {
let (resources, content) = if i + 1 < CHAIN {
(format!("/Pattern << /P0 {} 0 R >>", first + i + 1), "/Pattern cs /P0 scn 0 0 5 5 re f")
} else {
(String::new(), "1 0 0 rg 0 0 5 5 re f")
};
let cell = "/PatternType 1 /PaintType 1 /TilingType 1 /BBox [0 0 10 10] /XStep 10 /YStep 10";
stream(&format!("{cell} /Resources << {resources} >>"), content)
})
.collect();
let w = warnings_of(&cells, &format!("/Pattern << /P0 {first} 0 R >>"), "/Pattern cs /P0 scn 0 0 100 100 re f");
assert!(w.iter().any(|w| w.contains("tiling patterns nested too deeply")), "{w:?}");
}
/// Soft masks whose groups draw through the next mask are read only so many levels deep: a chain
/// of them opens, with a warning.
#[test]
fn soft_masks_nested_too_deeply_stop_with_a_warning() {
let first = first_extra(1);
let mask = |i: usize| format!("/ExtGState << /GS0 << /SMask << /Type /Mask /S /Luminosity /G {} 0 R >> >> >>", first + i);
let groups: Vec<String> = (0..CHAIN)
.map(|i| {
let (resources, content) =
if i + 1 < CHAIN { (mask(i + 1), "/GS0 gs 1 1 1 rg 0 0 100 100 re f") } else { (String::new(), "1 1 1 rg 0 0 100 100 re f") };
let group = "/Type /XObject /Subtype /Form /BBox [0 0 100 100] /Group << /S /Transparency /CS /DeviceRGB >>";
stream(&format!("{group} /Resources << {resources} >>"), content)
})
.collect();
let w = warnings_of(&groups, &mask(0), "/GS0 gs 1 0 0 rg 0 0 100 100 re f");
assert!(w.iter().any(|w| w.contains("soft masks nested too deeply")), "{w:?}");
}
// ---------- text ----------
const HELVETICA: &str =
+47
View File
@@ -506,3 +506,50 @@ fn art_deep_in_tags_inside_a_layer_reaches_it() {
let shapes = d.layers.iter().find(|l| l.name.as_deref() == Some("Shapes")).unwrap();
assert_eq!(colors(shapes), [Color::rgb(1.0, 0.0, 0.0)]);
}
/// Art marked with a membership dictionary is skipped by its policy over its groups, by the page's
/// walk as by the interpreter, so each shown path keeps the ink the walk found it painted in: with
/// "Shapes" on and "Hidden" off, AllOn and AllOff over both are hidden, AnyOff and the default
/// AnyOn show. Groups named by a single reference, not an array, count the same: AllOff over
/// "Hidden" alone shows and AllOff over "Shapes" alone is hidden.
#[test]
fn membership_dictionaries_show_art_by_their_policy() {
let (objs, catalog, [a, b]) = groups(1, "/OFF [{B}]");
let both = format!("[{a} 0 R {b} 0 R]");
let runs = [
("AllOn", format!("{both} /P /AllOn")),
("AnyOff", format!("{both} /P /AnyOff")),
("AllOff", format!("{both} /P /AllOff")),
("AnyOn", both.clone()),
("OffAlone", format!("{b} 0 R /P /AllOff")),
("OnAlone", format!("{a} 0 R /P /AllOff")),
];
let memberships: Vec<String> = runs.iter().map(|(_, m)| format!("<< /Type /OCMD /OCGs {m} >>")).collect();
let first = first_extra(1) + 2;
// Every ink has the same tint transform: only the walk tells the interpreter's paths apart.
let tint = "<< /FunctionType 2 /Domain [0 1] /C0 [0 0 0 0] /C1 [0 0 1 0] /N 1 >>";
let mut content = String::new();
let (mut props, mut spaces) = (String::new(), String::new());
for (i, (ink, _)) in runs.iter().enumerate() {
content += &format!("/OC /M{i} BDC /CS{i} cs 1 scn {} 10 5 5 re f EMC ", 10 * i);
props += &format!("/M{i} {} 0 R ", first + i);
spaces += &format!("/CS{i} [/Separation /{ink} /DeviceCMYK {tint}] ");
}
let page = PdfPage { resources: format!("/Properties << {props}>> /ColorSpace << {spaces}>>"), ..PdfPage::new(100.0, 100.0, &content) };
let mut extra: Vec<&str> = vec![&objs[0], &objs[1]];
extra.extend(memberships.iter().map(String::as_str));
let options = ImportOptions { layers: false, ..Default::default() };
let r = import_with_report(&pdf_with_catalog(&[page], &extra, &catalog, None), &options).unwrap();
assert_eq!(names(&r.document), ["Page 1"]);
let inks: Vec<Option<String>> = r.document.layers[0]
.children()
.unwrap()
.iter()
.map(|n| match n.appearance.fill().map(|f| &f.paint) {
Some(vectorcraft_color::Paint::Solid { swatch, .. }) => swatch.clone(),
_ => None,
})
.collect();
let shown = ["AnyOff", "AnyOn", "OffAlone"].map(|s| Some(s.to_string()));
assert_eq!(inks, shown, "{:?}", r.warnings);
}
+34
View File
@@ -190,6 +190,40 @@ mod alias_tests {
assert!(!sys.misses.contains(&'\u{E000}'), "an unsearched character is not a remembered miss");
}
/// The file search for a character no loaded font covers skips font files over 40 MiB
/// without reading them, and loads the same font at its own length.
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn the_file_search_skips_font_files_over_40_mib() {
use crate::{FileFontInfo, FileGlyph, build_file_font};
use kurbo::Shape;
let pua = '\u{E123}';
let info = FileFontInfo { family: "Fallback Size Limit Regression".into(), style: "Regular".into(), ..Default::default() };
let glyph = FileGlyph { ch: pua, outline: kurbo::Rect::new(0.0, 0.0, 500.0, 700.0).to_path(0.1), advance: 600.0 };
let font = build_file_font(&info, &[glyph]).unwrap();
// Removes the folder when dropped, so a panic part way through does not leave the 41 MiB file behind.
struct TempDir(std::path::PathBuf);
impl Drop for TempDir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
let search = |name: &str, bytes: &[u8]| {
let dir = TempDir(std::env::temp_dir().join(format!("vc-fallback-size-{}-{name}", std::process::id())));
let _ = std::fs::remove_dir_all(&dir.0);
std::fs::create_dir(&dir.0).unwrap();
std::fs::write(dir.0.join("Pua.ttf"), bytes).unwrap();
let db = FontDb::with_font_dirs(vec![dir.0.clone()]);
let found = db.system_fallback(pua);
std::fs::remove_dir_all(&dir.0).unwrap();
found
};
assert!(search("small", &font), "a font at its own length is loaded");
let mut padded = font.clone();
padded.resize(41 << 20, 0);
assert!(!search("padded", &padded), "the same font padded to 41 MiB is skipped");
}
#[test]
fn a_collection_lists_at_most_max_faces() {
let mut font = name_font(&[(3, 0x0409, 1, "Fam"), (3, 0x0409, 2, "Regular")]);
+71 -1
View File
@@ -793,7 +793,77 @@ pub(super) fn on_path(cx: &mut Ctx<'_>, paras: &[Range<usize>], t: &TextObject,
#[cfg(test)]
mod tests {
use super::longest_start_tried;
use super::{Affine, ArcPath, BezPath, GlyphBend, PathEl, Point, bend_outline, longest_start_tried};
use vectorcraft_geom::{Rect, shapes};
/// A glyph-sized rectangle in pen space, `w` wide and `h` tall, standing on the baseline.
fn block(w: f64, h: f64) -> BezPath {
let mut p = BezPath::new();
p.move_to((0.0, 0.0));
p.line_to((w, 0.0));
p.line_to((w, h));
p.line_to((0.0, h));
p.close_path();
p
}
fn end_points(path: &BezPath) -> Vec<Point> {
path.elements()
.iter()
.filter_map(|el| match *el {
PathEl::MoveTo(p) | PathEl::LineTo(p) | PathEl::QuadTo(_, p) | PathEl::CurveTo(_, _, p) => Some(p),
PathEl::ClosePath => None,
})
.collect()
}
/// Bent along a circle, a rectangle's baseline edge follows the circle and its other edge
/// follows a circle `h` farther along the path's normal; its corners stay at the ends of its
/// step along the path. Moving it off the path (`rise`) moves both edges by the same amount.
#[test]
fn an_outline_bent_along_a_circle_follows_it() {
let (center, r) = (Point::new(100.0, 100.0), 100.0);
let ap = ArcPath::new(&shapes::ellipse(Rect::new(0.0, 0.0, 200.0, 200.0)));
let (w, h, s) = (40.0, 20.0, 30.0);
let (p0, d0) = ap.at(s);
let (p1, _) = ap.at(s + w);
// Which way the path's normal points: away from the center (+1) or towards it (-1).
let side = (kurbo::Vec2::new(-d0.y, d0.x).dot(p0 - center)).signum();
let at_radius = |p: Point, radius: f64| center + (p - center) * (radius / r);
for rise in [0.0, 5.0] {
let bend = GlyphBend { s, step: w, advance: w, rise };
let bent = bend_outline(&block(w, h), Affine::IDENTITY, &ap, &bend).expect("a turning path bends the outline");
let points = end_points(&bent);
let (base, top) = (r + side * rise, r + side * (rise + h));
let corners = [at_radius(p0, base), at_radius(p1, base), at_radius(p1, top), at_radius(p0, top)];
for c in corners {
assert!(points.iter().any(|p| p.distance(c) < 0.1), "rise {rise}: no point near the corner {c:?} in {points:?}");
}
// The edges are cut into pieces that stay between the two circles; a straight chord
// between the corners would pass inside the inner one.
assert!(points.len() > 8, "rise {rise}: {} points", points.len());
let (inner, outer) = (base.min(top), base.max(top));
for p in &points {
let d = p.distance(center);
assert!(d > inner - 0.1 && d < outer + 0.1, "rise {rise}: {p:?} lies {d} from the center, outside {inner}..{outer}");
}
let on_base = points.iter().filter(|p| (p.distance(center) - base).abs() < 0.1).count();
assert!(on_base > 2, "rise {rise}: only {on_base} points on the baseline circle");
}
}
/// A path that does not turn under the glyph, and a glyph with no advance, leave the outline
/// as it is.
#[test]
fn an_outline_on_a_straight_path_is_not_bent() {
let line = ArcPath::new(&shapes::line(Point::new(0.0, 0.0), Point::new(300.0, 0.0)));
let bend = GlyphBend { s: 30.0, step: 40.0, advance: 40.0, rise: 0.0 };
assert!(bend_outline(&block(40.0, 20.0), Affine::IDENTITY, &line, &bend).is_none());
let circle = ArcPath::new(&shapes::ellipse(Rect::new(0.0, 0.0, 200.0, 200.0)));
assert!(bend_outline(&block(40.0, 20.0), Affine::IDENTITY, &circle, &bend).is_some());
let no_advance = GlyphBend { advance: 0.0, ..bend };
assert!(bend_outline(&block(40.0, 20.0), Affine::IDENTITY, &circle, &no_advance).is_none());
}
/// The longest start that fits is found among the ones tried; past the tries, a binary search
/// finds one that fits, with as many more tries as halvings of the rest.
+5 -3
View File
@@ -647,14 +647,16 @@ pub(crate) fn preferred_text_as(app: &VectorcraftApp) -> TextAs {
/// or `.ait` file opens as it says: Outlines would open it from its PDF content, without its
/// editing data. So does an open with `linkPages`, which refuses Outlines: a linked page shows the
/// file's own text.
pub(crate) fn with_preferred_text_as(app: &VectorcraftApp, name: &str, bytes: &[u8], p: &Value) -> Value {
pub(crate) fn with_preferred_text_as(app: &VectorcraftApp, name: &str, bytes: &[u8], mut p: Value) -> Value {
let given = p.get("textAs").is_some_and(|v| !v.is_null());
let linked = p.get("linkPages").and_then(Value::as_bool) == Some(true);
let options = p.is_object() || p.is_null();
if given || linked || !options || preferred_text_as(app) == TextAs::Text || fileio::detect(name, bytes).map(|f| f.id) != Some("pdf") {
return p.clone();
return p;
}
if !p.is_object() {
p = json!({});
}
let mut p = if p.is_object() { p.clone() } else { json!({}) };
p["textAs"] = json!(TextAs::Outlines.id());
p
}
+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>) {
@@ -1316,6 +1330,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(()),
@@ -553,7 +553,7 @@ fn a_pdf_opened_without_the_dialog_takes_the_pdf_text_preference() {
io::open_document(&mut app, "one.pdf", &one, None, &json!({"textAs": "text"})).unwrap();
opened(&mut app);
assert_eq!(type_objects(&app), 1, "an open that gives textAs keeps it");
let p = import_pdf::with_preferred_text_as(&app, "one.ai", &one, &serde_json::Value::Null);
let p = import_pdf::with_preferred_text_as(&app, "one.ai", &one, serde_json::Value::Null);
assert!(p.is_null(), "a .ai file opens as it says: {p}");
// In the dialog too, a .ai file starts from Editable, and its choice is not kept for PDFs.
assert!(import_pdf::offer(&mut app, "two.ai", &two_pages(false, None), None, None));
+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"] {
+4 -3
View File
@@ -150,9 +150,10 @@ pub fn opens_as(name: &str) -> Option<OpensAs> {
/// Open a document through the engine loader with the `document.open` options in `p` →
/// `document.open`'s result, or `{dialog}` when Edit › Color Settings asks about its profile first
/// ([`dialogs::profile_mismatch::open_or_ask`]): the document then opens, and goes on the recent
/// files, once the question is answered. A PDF opens with the `pdfTextAs` preference unless `p`
/// gives `textAs` ([`dialogs::import_pdf::with_preferred_text_as`]).
/// files, once the question is answered. PDF font and Text As preferences supply missing options;
/// explicit `embeddedFonts` and `textAs` choices keep their precedence.
pub fn open_document(app: &mut VectorcraftApp, name: &str, bytes: &[u8], path: Option<String>, p: &Value) -> Result<Value, String> {
let p = app.session.prefs.with_pdf_font_choice(p);
let p = &dialogs::import_pdf::with_preferred_text_as(app, name, bytes, p);
let update_links = app.session.prefs.update_links == "automatically";
let low_res_proxy_eps = app.session.prefs.low_res_proxy_eps;
@@ -680,7 +681,7 @@ fn open_file_with(app: &mut VectorcraftApp, path: &str, background: bool, p: &Va
note_recent(app, path);
return Ok(Value::Null);
}
let params = crate::dialogs::import_pdf::with_preferred_text_as(app, path, &bytes, &Value::Null);
let params = crate::dialogs::import_pdf::with_preferred_text_as(app, path, &bytes, Value::Null);
return Ok(crate::opening::start_with(app, path, bytes, params));
}
let r = open_bytes_with(app, path, &bytes, Some(path.to_string()), p)?;
+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",
+69
View File
@@ -4,6 +4,75 @@ use super::*;
use crate::Services;
use crate::tests::picks::{cancel_dialog, close_shown, draw_dialogs, open_dialogs, show_question};
/// #9286: both real open consumers apply the same preference/explicit-option precedence and bind
/// the carried program to rendered text, rather than merely storing the requested option.
#[test]
fn synchronous_and_background_pdf_open_honor_embedded_font_preferences_and_overrides() {
use std::fmt::Write as _;
use vectorcraft_doc::{FILE_FONT_MIME, NodeKind};
use vectorcraft_testkit::pdf::{PdfPage, first_extra, pdf_with};
use vectorcraft_text::{FileFontInfo, FileGlyph, build_file_font};
let mut glyph = FileGlyph { ch: 'x', outline: Default::default(), advance: 600.0 };
glyph.outline.move_to((0.0, 0.0));
glyph.outline.line_to((500.0, 0.0));
glyph.outline.line_to((500.0, 700.0));
glyph.outline.line_to((0.0, 700.0));
glyph.outline.close_path();
let info = FileFontInfo { family: "VectorCraftUIOpenPreference".into(), style: "Regular".into(), ..Default::default() };
let font_bytes = build_file_font(&info, &[glyph]).unwrap();
let mut hex = String::with_capacity(font_bytes.len() * 2);
for b in font_bytes {
write!(hex, "{b:02x}").unwrap();
}
let n = first_extra(1);
let page = PdfPage { resources: format!("/Font << /F1 {n} 0 R >>"), ..PdfPage::new(100.0, 100.0, "BT /F1 24 Tf 10 40 Td (x) Tj ET") };
let font = format!(
"<< /Type /Font /Subtype /TrueType /BaseFont /ABCDEF+VectorCraftUIOpenPreference /FirstChar 120 /LastChar 120 /Widths [600] /Encoding /WinAnsiEncoding /FontDescriptor {} 0 R >>",
n + 1
);
let descriptor = format!(
"<< /Type /FontDescriptor /FontName /ABCDEF+VectorCraftUIOpenPreference /Flags 34 /FontBBox [0 -200 500 900] /ItalicAngle 0 /Ascent 900 /Descent -200 /CapHeight 700 /StemV 80 /FontFile2 {} 0 R >>",
n + 2
);
let program = format!("<< /Length {} /Filter /ASCIIHexDecode >>\nstream\n{hex}>\nendstream", hex.len() + 1);
let bytes = pdf_with(&[page], &[&font, &descriptor, &program], None);
for background in [false, true] {
for (preference, explicit, expected) in [(false, None, false), (true, None, true), (false, Some(true), true), (true, Some(false), false)] {
let mut app = crate::testing::windowed(VectorcraftApp::new(Session::new(), Services::default()));
app.session.prefs.pdf_import_embedded_fonts = preference;
let mut params = json!({"textAs": "text"});
if let Some(value) = explicit {
params["embeddedFonts"] = json!(value);
}
if background {
start_with(&mut app, "embedded-preference.pdf", bytes.clone(), params);
open_ready(&mut app);
} else {
crate::io::open_document(&mut app, "embedded-preference.pdf", &bytes, None, &params).unwrap();
}
let doc = &app.session.doc().unwrap().doc;
let db = vectorcraft_text::FontDb::global();
let mut text_count = 0;
let mut carries_font = false;
doc.walk(|node| {
if let NodeKind::Text(text) = &node.kind {
assert_eq!(text.plain_text(), "x", "imported text content");
text_count += 1;
carries_font |= vectorcraft_text::layout(db, text).glyphs.iter().any(|glyph| db.is_file_font(glyph.font_id));
}
});
assert_eq!(text_count, 1, "text survives: background={background}, preference={preference}, explicit={explicit:?}");
assert_eq!(carries_font, expected, "rendered font: background={background}, preference={preference}, explicit={explicit:?}");
assert_eq!(
doc.images.values().any(|blob| blob.mime == FILE_FONT_MIME),
expected,
"owned font program: background={background}, preference={preference}, explicit={explicit:?}"
);
}
}
}
#[test]
fn long_operation_busy_while_a_file_opens_or_a_background_save_runs() {
let mut app = VectorcraftApp::new(Session::new(), Services::default());
@@ -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);
+24
View File
@@ -60,6 +60,7 @@ pub fn poll(app: &mut VectorcraftApp) {
script_run::forget::<GrowthQuestion>(app);
script_run::settle_close(app);
script_window::sync(app);
let boards = result.as_ref().ok().and_then(|r| r["activeArtboards"].as_array().cloned()).unwrap_or_default();
match result {
// The commands it ran are journaled now: a recording they no longer fit in names its limit.
Ok(report) => {
@@ -88,6 +89,29 @@ pub fn poll(app: &mut VectorcraftApp) {
}
startup_failures(app);
app.sync_views();
show_artboards(app, &boards);
}
/// Makes each artboard a run's `setActiveArtboardIndex` chose the active one of its document's view
/// (`activeArtboards` in the run's report: `{document, artboard}`, both indexes). The end of a run
/// starts the tool afresh, so the Artboard tool then takes the active document's active artboard as
/// its only selected one, as choosing it in the Artboards panel does.
fn show_artboards(app: &mut VectorcraftApp, boards: &[serde_json::Value]) {
for b in boards {
let index = |k: &str| b[k].as_u64().and_then(|i| usize::try_from(i).ok());
let (Some(doc), Some(board)) = (index("document"), index("artboard")) else { continue };
let count = app.session.documents().get(doc).map_or(0, |d| d.doc.artboards.len());
if let Some(view) = app.views.get_mut(doc)
&& board < count
{
view.artboard = board;
}
}
if app.session.tool_id() == "artboard"
&& let Some(n) = app.session.active().map(|d| d.doc.artboards.len()).filter(|n| *n > 0)
{
crate::panels::artboards::select(app, crate::panels::artboards::selected(app, n));
}
}
/// The running script reads each drawn window in `Document.views`, with its last drawn area.
+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
+30
View File
@@ -217,6 +217,36 @@ fn stop_puts_the_document_back_and_says_so() {
assert_eq!(app.ui.status, "The script was stopped and its changes were undone");
}
#[test]
fn set_active_artboard_index_shows_the_artboard_in_the_view() {
let mut app = app();
app.session.prefs.show_external_script_warning = false;
app.run("artboard.new", json!({"x": 1000, "y": 0, "width": 100, "height": 100})).unwrap();
app.views[0].artboard = 0;
let source = "app.activeDocument.artboards.setActiveArtboardIndex(1);";
menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": source })).unwrap().unwrap();
finish(&mut app);
assert_eq!(app.views[0].artboard, 1);
}
#[test]
fn the_artboard_tool_follows_the_artboard_a_script_makes_active() {
let mut app = app();
app.session.prefs.show_external_script_warning = false;
app.run("artboard.new", json!({"x": 1000, "y": 0, "width": 100, "height": 100})).unwrap();
app.run("artboard.new", json!({"x": 2000, "y": 0, "width": 100, "height": 100})).unwrap();
app.select_tool("artboard");
crate::panels::artboards::select(&mut app, 2);
// A run starts the tool afresh; it keeps the view's active artboard, then the one the script chose.
for (source, active) in [("vc.log(1);", 2), ("app.activeDocument.artboards.setActiveArtboardIndex(1);", 1)] {
menus::run_ui_command(&mut app, "ui.runScript", &json!({ "source": source })).unwrap().unwrap();
finish(&mut app);
assert_eq!(app.views[0].artboard, active, "{source}");
assert_eq!(app.session.tool_options()["active"], json!(active), "{source}");
assert_eq!(app.session.tool_options()["selected"], json!([active]), "{source}");
}
}
#[test]
fn a_canceled_pick_does_not_take_a_dropped_script() {
let mut app = app();
+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();
+4
View File
@@ -363,6 +363,10 @@ The app decides which cursors exist; whoever draws them works from the list. For
doesn't run. `cargo xtask ci` runs the same two as its `test` and `doctests` steps.
- The test build leaves out the examples (`--lib --bins --tests`); clippy (`--all-targets`) still
checks them.
- PDF open consumers compose the embedded-font preference before Text As without cloning the
composed options again; explicit options win in both synchronous and background opens.
`opening::tests::synchronous_and_background_pdf_open_honor_embedded_font_preferences_and_overrides`
exercises both paths with a generated embedded font and checks rendered font ownership (#9286).
- Each crate has one integration-test binary: its test files are modules of `tests/it/main.rs`. Run
one file's tests with `cargo nextest run -p vectorcraft-svg --test it roundtrip::` (or `cargo test`
with the same arguments). A new test file gets a `mod` line in `main.rs`.
+7 -5
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,11 +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 (layers, artboards, 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 and its page items, 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`.
+187 -37
View File
@@ -621,7 +621,7 @@ change nothing; an omitted or null `id` keeps the default. Commands that need an
`path` keys of `appearance.transfer`, `appearance.copyFrom`, `layer.move`, the `livePaint.*` commands and
`text.createInPath`) refuse a value that is not a non-negative integer with "`id` must be a whole number", naming the
key, and report a key left out or null as missing. The optional `group` of `livePaint.fill` and `parent` of
`node.move` are refused the same way when given; left out, they keep their defaults. `livePaint.info` reads `id` when
`node.move` and `text.create` are refused the same way when given; left out, they keep their defaults. `livePaint.info` reads `id` when
`group` is left out or null, and reports a missing group only when both are left out. A command that needs a number
(`x` of `shape.rectangle`, `pos` of `guide.add`, `index`, `x` and `y` of the `object.mesh.*` and
`object.envelope.setMeshPoint` point commands, and the others like them) refuses a value that is not a number with
@@ -636,7 +636,7 @@ left out or null; `appearance.setActiveItem` reads a null `index` as clearing th
whole number from 1 to 1000, such as `2.4`, `0` or `1001`, and opens no document. A null `artboards` keeps the
default or the preset's count; a null `columns` or `rows` is an error. A `file.new` step replayed from a journal or
played from the Actions panel keeps the earlier rules: `artboards` is rounded and kept within 1 to 1000, a `columns` of
1 or more is rounded and kept to at most 1000, and a `rows` is rounded and must then be from 1 to 1000.
1 or more is rounded and kept to at most 1000, and a `rows` is rounded, must then be 1 or more, and is kept to at most 1000.
A command that leaves out an object selected inside a
selected group also leaves it out when `ids` list it together with a group that holds it. Every command that takes
`ids` (or `slices`, for the slice commands) refuses a list with an entry that is not a non-negative integer, or a value
@@ -3122,8 +3122,8 @@ through `$`:
100), `blendingMode` (the object's own blend mode as a `BlendModes` value such as `"BlendModes.MULTIPLY"`
(https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/), set with `object.setProps`; `COLORBLEND` and `SATURATIONBLEND` are the Color and Saturation modes, and any other value
throws `blendingMode needs a BlendModes value`), `position`, `left`, `top`, `width`, `height`, `geometricBounds`, `visibleBounds`, `controlBounds` (the
visible bounds with the anchors and Bézier handles of the object's paths, and of the shown paths in its groups and
compound paths; a clip group's come from its clipping path; in a document in the back, type
visible bounds with the anchors and direction handles of the shown paths in the item; a clip group or clipping
layer takes in only its clipping path's; in a document in the back, type
not measured yet is measured first, as the switch to that document would measure it; a valid
`position`, `left`, `top`, `width` or `height` equal to the value an object that holds no type, symbol instance
or placed document already has is not applied, and its document stays in the back), `editable` (false for an
@@ -3133,13 +3133,16 @@ through `$`:
`transform` (https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/). `move` runs `node.move` unless the object is
already in the place it names. `duplicate` runs `edit.duplicate`, and with a relative object it then runs `node.move`
on the copy the same way; without one, the copy stays where `edit.duplicate` puts it. The relative object is a page item or a layer of the same
document; `ElementPlacement.INSIDE` and `PLACEATBEGINNING` (the default) put the object on top of a layer's or a
group's contents, `PLACEATEND` under them, `PLACEBEFORE` directly above the relative object and `PLACEAFTER`
directly below it. A move that leaves the object where it is runs no command. The clipping path of a clip group or clipping layer stays at its bottom: `PLACEATEND` puts the
document; `ElementPlacement.INSIDE` and `PLACEATBEGINNING` (the default) put the object on top of a layer's, a
group's or a compound path's contents, `PLACEATEND` under them (a compound path takes only paths), `PLACEBEFORE`
directly above the relative object and `PLACEAFTER` directly below it. A move that leaves the object where it is runs no command. The clipping path of a clip group or clipping layer stays at its bottom: `PLACEATEND` puts the
object directly above the clipping path, and `PLACEAFTER` with the clipping path as the relative object throws
`an object cannot go below a clipping mask` and moves or copies nothing (VectorCraft's own rule). The one exception
is `mask.move(mask, ElementPlacement.PLACEAFTER)` on the clipping path itself, which succeeds and leaves the
document unchanged; `mask.duplicate(mask, ElementPlacement.PLACEAFTER)` still throws. Moving a tracing's visible,
`an object cannot go below a clipping mask` and moves or copies nothing (VectorCraft's own rule). The exceptions
are `mask.move(mask, ElementPlacement.PLACEAFTER)` on the clipping path itself, `mask.move(art,
ElementPlacement.PLACEAFTER)` with the object directly above it and `mask.move(group, ElementPlacement.PLACEATEND)`
with its own clip group, which succeed and leave the document unchanged;
`mask.duplicate(mask, ElementPlacement.PLACEAFTER)` still throws. Any other place for the clipping path, such as
`INSIDE` or `PLACEATBEGINNING` of its own clip group, throws the `node.move` error below and moves nothing. Moving a tracing's visible,
unlocked source image (`TracingObject.sourceArt`) out of its tracing throws `a tracing's source image cannot leave
its tracing` and changes nothing; a hidden source image (the default) throws `Cannot move`. Moving or duplicating
an image to the bottom of an ordinary group named `Image Trace` throws `Only Image Trace can make a tracing` before
@@ -3216,10 +3219,12 @@ 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
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`
@@ -3229,11 +3234,24 @@ 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 objects also become stale after their document is reverted. `remove()` on an object that
`Stale page item`. Layer objects also become stale after their document is reverted, and so do the `pageItems`,
`groupItems` and `compoundPathItems` of a layer or group, the `pathItems` of a compound path (`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`
and delete nothing. Setting `width` or `height` scales the object along
and delete nothing. `remove()`, the document's `pageItems.removeAll()` and any `textFrames.removeAll()` that
delete the clipping path of a clip group or clipping layer also release that clipping mask in the same undo step,
so the object above the clipping path does not become the new clipping path; a deletion that leaves the clipping
path keeps the mask. When the released group is named `Image Trace` and an image would be left at its bottom, they
throw `Only Image Trace can make a tracing` and delete nothing. `textFrames.removeAll()` and the `removeAll()` of a
group's `pageItems`, `groupItems` or `compoundPathItems` throw the same error and delete nothing when they would
leave an image at the bottom of an ordinary group named `Image Trace`. The `removeAll()` of a layer's or group's
`pageItems`, and of any `groupItems` or `compoundPathItems`, does not release a mask: it throws as described
above. Setting `width` or `height` scales the object along
the page's axes, so a rotated object then reads back the size that was set. `index` and `getByName` throw
`Not found`; and
`app.activeDocument` with no document open throws `No active document`. `Document.selection` takes one page item,
@@ -3249,7 +3267,7 @@ through `$`:
`..`, a network path, a NUL character or more than 4,096 bytes throws an error. `app.redraw()` returns `undefined`
and does not change the documents or add an undo step. In the app, the documents are drawn as they were before the
run until the run ends, with or without the call. Some members the Application,
Document and PageItem pages list, such as `Document.layers`, `PageItem.isIsolated`, `PageItem.bringInPerspective` and
Document and PageItem pages list, such as `Document.swatches`, `PageItem.isIsolated`, `PageItem.bringInPerspective` and
`app.beep`, throw an error that says they are not available yet when they are read or assigned.
`hasOwnProperty` and `propertyIsEnumerable` are false for those members and true for every other member of an
object's class, so `item.hasOwnProperty("opacity")` is true on a page item, and `for (k in item)` lists the
@@ -3259,6 +3277,93 @@ through `$`:
strict-mode code, which throws a `TypeError`. On a collection it throws `Not found`, except for the text of a number that is not an array index, as described above. Other members
those pages list, such as `app.version` and `Document.save()`, and the members of the pages of the page-item kinds
themselves that this page does not describe are not defined yet and read as `undefined`.
- A document also has `layers`, `activeLayer`, `groupItems`, `compoundPathItems` and `artboards`.
`layers` (https://ai-scripting.docsforadobe.dev/jsobjref/Layers/) and a layer's own `layers` have `length`, `[i]`,
`index(key)`, `getByName(name)`, `add()` and `removeAll()`. On the document, `add()` runs `layer.new` and makes a
layer above every top-level layer; on a layer it runs `layer.newSublayer` and makes a sublayer on top of that
layer's contents. The new layer becomes the current one. `removeAll()` runs `layer.delete`; on the document's
layers it throws, since a document keeps at least one layer. Assigning a layer to `activeLayer` runs
`layer.setCurrent`. A `Layer` (https://ai-scripting.docsforadobe.dev/jsobjref/Layer/) has `typename`, `name`,
`visible`, `locked`, `printable`, `preview`, `dimPlacedImages`, `opacity` (0 to 100), `color`, `parent`,
`layers`, `pageItems`, `groupItems`, `compoundPathItems`, `zOrderPosition`, `hasSelectedArtwork`, `isIsolated`,
`move(relativeObject, insertionLocation?)`, `remove()` and `zOrder(method)`. Its properties run
`layer.setProps`, and `opacity` runs `object.setProps`. `opacity` reads rounded to 4 decimals; assigning the number it
reads, or one that stores as the same opacity, runs no command. `move` and `zOrder` run `node.move`; a layer goes into
another layer, to the top level of the document, or directly above or below another layer. Every page item has
`layer`, the layer it is in. A `GroupItem` (https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/) also has
`clipped`, `pageItems`, `groupItems` and `compoundPathItems`, and a `CompoundPathItem`
(https://ai-scripting.docsforadobe.dev/jsobjref/CompoundPathItem/) has `pathItems`. `groupItems`
(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` and returns
the new artboard), `insert(artboardRect, index)` (runs `artboard.new`, then `artboard.reorder` when `index` is not
the index the new artboard got, so an index that appends runs no `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
properties run `artboard.setProps`, and `rulerOrigin` runs `document.setRulerOrigin`. One document always keeps
one artboard.
VectorCraft's own rules: `layers` lists layers top first, as the Layers panel shows them. A layer's or group's
`pageItems`, `groupItems` and `compoundPathItems`, and a compound path's `pathItems`, list the objects directly in
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, and a compound
path's `pathItems` are `PathItems` objects with `length`, `[i]`, `index`, `getByName`, `removeAll` and string conversion.
Their path creation methods throw an error; a script can move existing paths into the 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; 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. 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. 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. 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.
`artboards.add` and `insert` stop at 100 artboards in a document, the limit `Documents.add` uses. An artboard's rectangle is
`[left, top, right, bottom]` in script coordinates, with its right side right of its left side, its bottom below
its top, each side from 1 to 3,999,856 points and every edge at most 4,000,000 points from the document origin.
Artboard names are trimmed, an empty name gives the artboard its default name (`Artboard N` for the Nth artboard),
and two artboards may have the same name. `add` and `insert` name the new artboard `Artboard N`, with N the first number from one past the artboard count that no other artboard's
name uses. `rulerOrigin` is `[x, y]` from the artboard's top-left corner with Y down.
`setActiveArtboardIndex` changes the view's active artboard with no undo step, and `script.run`'s report lists the
change in `activeArtboards` (`[{document, artboard}]`, both indexes, with each document's active artboard as the
run leaves it). The report also lists a document whose active artboard has another index when the run ends because
artboards were inserted, removed or reordered before it, and a document the run opened in which an artboard was
chosen. The chosen artboard stays active when another is inserted before it, even if it was already the active
one. An index outside the list throws a
`RangeError`. A layer that was deleted throws `Stale layer`, and an artboard that was deleted throws
`Stale artboard`. `Layer.pathItems`, `blendingMode`, `artworkKnockout` and `sliced`, `GroupItem.pathItems` and
`GroupItems.createFromFile` throw an error that says they are not available yet. `GroupItems.createFromFile` on a
collection whose document, layer or group was deleted throws `Stale page item` or `Stale document` first.
- `object.newGroup {parent?, index?, compound?}` adds an empty group to a shown, unlocked layer or group (`parent`;
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, where the path
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, and a pixel-aligned compound path snaps a path it takes to the pixel grid. `node.move` leaves the
clipping path of a clip group or clipping layer at its bottom: it refuses to move the clipping path until the mask
is released, and puts a row given index 0 there directly above the clipping path.
- `app.preferences` (https://ai-scripting.docsforadobe.dev/jsobjref/Preferences/) has `getBooleanPreference(key)`,
`getIntegerPreference(key)`, `getRealPreference(key)`, `getStringPreference(key)`, the four matching `set…(key,
value)` and `removePreference(key)`. The key `ShowExternalJSXWarning` is the preference `showExternalScriptWarning`.
@@ -3279,7 +3384,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
@@ -3288,7 +3394,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
@@ -3419,8 +3527,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()`
@@ -3553,14 +3662,19 @@ through `$`:
radius = 50, innerRadius = 20, points = 5, reversed?)`, which run `shape.rectangle`, `path.create`,
`shape.ellipse`, `shape.polygon` and `shape.star` (and `path.reverse` for `reversed`) and paint the new path as new
art is painted. `add()` and the shape creators put the new path on top of the active layer whatever the drawing
mode, which stays as it was. A `PathItem` (https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/) adds to the page item
mode, which stays as it was. These creation commands take `onLayer: layerId` to draw normally on that layer and
record this placement for replay. A null `onLayer` draws normally on the active layer.
A `PathItem` (https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/) adds to the page item
members `pathPoints`, `closed`, `evenodd`, `area` (negative for a path that runs counterclockwise), `length`,
`guides`, `clipping`, `selectedPathPoints`, `setEntirePath(points)`, `filled`, `fillColor`, `fillOverprint`,
`stroked`, `strokeColor`, `strokeOverprint`, `strokeWidth`, `strokeCap`, `strokeJoin`, `strokeMiterLimit` (1 to
500), `strokeDashes` and `strokeDashOffset`, and takes the page item transforms above. The
geometry changes through `path.setAnchors`, the fill and stroke through `paint.setFill` and `paint.setStroke`, the
stroke options through `stroke.set`, the fill rule through `path.setFillRule`, overprint through
`object.setOverprint`. Changes to the
`object.setOverprint`.
Script path paint and stroke edits pass `objectOnly: true` with explicit `ids` to keep new-art paint, the active proxy
and remembered colors during execution and replay. `paint.setFill`, `paint.setStroke` and `stroke.set` accept
this option with `ids` or `id`; it cannot be combined with `defaultsOnly: true`. Changes to the
points of a path (`closed`, `setEntirePath`, `pathPoints` and each `PathPoint`) are written together with one
`path.setAnchors` before the script uses any other member or command, edits the points of another path, or reads
the points of another path in the same Objects on Path group, and when the script ends;
@@ -3582,7 +3696,8 @@ through `$`:
the fill or stroke. The enumerations `PointType`, `PathPointSelection`, `StrokeCap`, `StrokeJoin`, `PolarityValues`
and `Transformation` hold strings such as `"StrokeCap.ROUNDENDCAP"`.
VectorCraft's own rules: a point's index counts across the path's subpaths; `closed` is true when every subpath is
closed, and assigning it opens or closes them all; `setEntirePath` takes at most 100,000 points and gives corner
closed, and assigning it opens or closes them all. An empty path keeps an assigned closure state for its first
subpath. `setEntirePath` takes at most 100,000 points and gives corner
points with no handles, keeping the path closed when it was; moving `anchor` leaves its handles where they are, and
`pointType` changes only the type; `PathPoints.add()` adds a corner point at the last point, or at `[0, 0]`; a point
whose index is past the end of its path throws `Stale path point`, and so does a point read before the script removed
@@ -3593,7 +3708,8 @@ through `$`:
Path group moves a path inside that group. Its existing `PathPoint` handles throw `Stale path point`.
Read those points again from `pathPoints`. Reading a path's points first writes any waiting point changes of
another path in the same Objects on Path group. Every point of a path selected as a whole is a selected anchor point,
and the endpoints of selected segments are not; a path in a selected group or compound path is selected as a whole.
and the endpoints of selected segments are not. Independently selected anchors remain selected alongside segment
picks. A path in a selected group or compound path is selected as a whole.
Direction handles are not selected on their own, so assigning `LEFTDIRECTION`, `RIGHTDIRECTION` or `LEFTRIGHTPOINT`
to `selected` throws an error that says it is not available yet, and so does assigning `NOSELECTION` to a point of a
path in a selected group or compound path. Selecting a point of a path with selected segments replaces that path's
@@ -3609,7 +3725,7 @@ through `$`:
was. Reading `fillColor` or `strokeColor` gives a new object each time, a `GradientColor`, `SpotColor` or `PatternColor` among them (a color linked to a
global or spot swatch reads as a `SpotColor` with its `tint`); assigning one of those throws an error that says it is not available yet. `filled = true` on a path without a fill gives it the fill new
art gets (a color, gradient or pattern), or black when new art has none, and `stroked = true` does the same with the
stroke; a new-art gradient goes on the bounds of the path, or of the compound path or compound shape whose paint
stroke. A copied solid new-art color keeps its color model. A new-art gradient goes on the bounds of the path, or of the compound path or compound shape whose paint
it shows, and a new-art pattern with a placement of its own, or one missing from the document, throws an error.
`fillOverprint` and `strokeOverprint` read and change the top fill or stroke only. Sizes and
radii are finite and not negative, `sides` is a whole number from 3 to 1000, `points` one from 2 to 1000,
@@ -3617,13 +3733,15 @@ through `$`:
64 lengths that are not all 0 (`[]` or `{}` for a solid line), and `rotateAbout` and `scaleAbout` default to
`Transformation.CENTER`. A transform that leaves the path where it is, such as `rotate(360)` or
`resize(100, 100)`, checks its arguments and runs no command, on a path with no points too. The transforms take one setting for fill and stroke patterns, so `changeFillPatterns` and
`changeStrokePattern` given as different values throw an error, and `changeFillGradients` false and `ellipse` with
`inscribed` true throw an error that says they are not available yet. A change to the geometry or paint of a path
`changeStrokePattern` given as different values throw an error, and `changeFillGradients` different from
`changePositions` and `ellipse` with `inscribed` true throw an error that says they are not available yet. A change to the geometry or paint of a path
that is hidden or locked, that is in a hidden or locked layer or group, or that is on a locked artboard throws
`Cannot edit` with nothing changed. `pathItems.removeAll()` deletes nothing and throws an error when any path is
hidden or locked or is inside a hidden or locked layer, group, compound path or other object (`cannot delete hidden or locked paths`), and otherwise
when any path is on a locked artboard (`cannot delete objects on a locked artboard`), each followed by a colon and
the ids of up to 20 of those paths. A path in a compound path or compound shape reads the fill, stroke and overprint of that compound path or
the ids of up to 20 of those paths. A point given to `setEntirePath` or assigned to
`anchor`, `leftDirection` or `rightDirection` whose x or y is more than 4,000,000 pt from the origin throws a range
error when it is given, and the path keeps its points. A path in a compound path or compound shape reads the fill, stroke and overprint of that compound path or
shape, which the paint commands paint in its place. A change to a path's paint or stroke leaves the paint for new
art, the active Fill or Stroke proxy and Recent Colors as they were. `transform`, `polarity` and the gradient stops
are not available yet.
@@ -3648,7 +3766,17 @@ through `$`:
with `text.create`; `areaText(path, orientation?)` and `pathText(path, startTValue?, endTValue?, orientation?)` turn
a `PathItem` into area type or type on a path with `text.createInPath`, the orientation being a `TextOrientation`
value; a `startTValue` or `endTValue` that is given throws an error that says it is not available yet, and
`baseFrame` and `postFix` thread the new frame as the threaded-type paragraph below describes. A `TextFrame`
`baseFrame` and `postFix` thread the new frame as the threaded-type paragraph below describes. A `Layer` and a
`GroupItem` have `textFrames` with the same members. VectorCraft's own rules for
them: they list the type objects directly in the layer or group, topmost first, and their `add()`, `pointText`,
`areaText` and `pathText` put the new type on top of the layer's or group's contents, whatever the current layer.
Point type goes there with `text.create`'s `parent`, which takes a shown, unlocked layer or group and ignores the
drawing mode, and area type and type on a path go there with `node.move`, in the same undo step. A hidden or
locked layer or group throws an error and changes nothing. `removeAll()` deletes every type object the collection
lists with `edit.clear` in one step; when one is hidden or locked, in a hidden or locked layer or group, or on a
locked artboard (`cannot delete objects on a locked artboard`), it throws an error and deletes nothing. A text edit,
`createOutline()` or a conversion of such a type object, and `areaText` or `pathText` given such a path, throw
`Cannot edit` with nothing changed. A `TextFrame`
(https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/) is a page item with `kind` (`TextType.POINTTEXT`,
`AREATEXT` or `PATHTEXT`), `contents`, `orientation`, `textRange`, `characters`, `words`, `paragraphs`,
`createOutline()` (Type › Create Outlines, giving the group of outlines, or `null` when the type has nothing to
@@ -3663,8 +3791,11 @@ through `$`:
`add(contents, relativeObject?, insertionLocation?)` and `addBefore(contents)`, which insert the text and give its
range, as one `text.editRange`. Character attributes are `size` (0.1 to 1296 pt), `leading` (0.1 to
5000 pt), `autoLeading`, `tracking` (-1000 to 10000), `baselineShift` (-1296 to 1296 pt), `horizontalScale` and
`verticalScale` (1 to 10000 percent), `rotation` (-360 to 360 degrees), `underline`, `strikeThrough` and `textFont`,
set with `text.setRangeStyle`; sizes are document points, as the Character panel shows them. Paragraph attributes are
`verticalScale` (1 to 10000 percent), `rotation` (-360 to 360 degrees), `underline`, `strikeThrough`, `textFont`,
`fillColor` and `strokeColor` (color objects, as a path takes them; a `NoColor` takes the paint away) and
`strokeWeight` (0 to 1000 pt) (https://ai-scripting.docsforadobe.dev/jsobjref/CharacterAttributes/), set with
`text.setRangeStyle`; sizes are document points, as the Character panel shows them. Reflection reports
`fillColor` and `strokeColor` as `Color`. Paragraph attributes are
`justification` (a `Justification` value, set with `text.setStyle`; the Auto alignment new type has reads as `LEFT`,
or `RIGHT` in a right-to-left paragraph, and setting a value replaces it), `firstLineIndent`, `leftIndent`, `rightIndent`,
`spaceBefore` and `spaceAfter` (-1296 to 1296 pt, set with `text.setFormat`). `app.textFonts`
@@ -3723,7 +3854,8 @@ through `$`:
style's old value. `applyTo` takes a text range, a text frame or its characters, words or paragraphs, in the
style's document; a character style on an empty range inside text changes nothing, on empty text it styles the
text typed or set later, and a paragraph style styles every paragraph the text touches. `clearingOverrides` left
out is false. A range lists each style once, in the order
out is false. `applyTo` on a frame that is hidden or locked, in a hidden or locked layer or group, or on a locked
artboard throws `Cannot edit` with nothing changed. A range lists each style once, in the order
its text first uses it, the Normal style standing for text in no other style, and its lists cannot add or remove
styles. The Normal styles cannot be renamed or removed. A style object keeps naming its style after a rename made
through `name`; after the style is removed, renamed another way or its document closed or reverted, it throws
@@ -3787,9 +3919,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
@@ -4881,6 +5017,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
@@ -8166,7 +8303,8 @@ and `layerRows`, the rows highlighted in the panel.
bottom layer's into the empty space under the list) places them, unless objects are copied with a top-level layer
that is the target, which would put them inside it (#8237). Dragging the
selected-art square is `layer.move` with the selected objects. `node.move {id, parent?, index}` is the low-level
form with the same nesting rules; unlike `layer.move`, it also moves a row into a locked layer or group. A row that
form with the same nesting rules; unlike `layer.move`, it also moves a row into a locked layer or group, and it puts
a path into a shown, unlocked compound path (see `object.newGroup` for the paint the path keeps or takes). A row that
either command puts into a Live Paint group from elsewhere (inside it, or above or below one of its rows) joins the
group's paths as `livePaint.merge` adds them, in one "Merge Live Paint" undo step, and the group is selected and
listed in `layer.move`'s `ids` in its place; paths, compound paths, groups of them and Live Paint groups can join,
@@ -11009,10 +11147,13 @@ 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)).
Replaying a saved `file.new` command rounds legacy fractional row counts and caps them at 1000. New calls still
require whole row counts from 1 to 1000.
`file.newPresets {category?}` lists the categories and presets (Recent: the last sizes used; Saved: the user's presets,
kept in the preferences by `file.newPresets.save` and removed by `file.newPresets.delete`). A listed preset can be
passed straight back to `file.new`. Print presets and sizes without `units` start in `unitsGeneral`; screen presets
@@ -13426,7 +13567,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.
+2 -2
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.
@@ -209,7 +209,7 @@ Gujarati interface follow-up (2026-11-14): the catalog and zero/one plural rule
| M10 | Brushes, symbols, patterns, Repeat | 🟡 pattern swatches (5 tile types, Pattern Options, editing mode, SVG `<pattern>`/PDF export) and live Repeat (radial/grid/mirror) done; interactive selected mirror axis implemented (focused and native checks passed; full CI blocked by an unrelated text test); symbol libraries done (Window › Symbol Libraries, six generated libraries (Basic Shapes, UI Frames, Map Markers, Inventory Icons, Skill Icons, Weather Icons), User Defined, Other Library…, Save Symbols); brush libraries done (Window › Brush Libraries, fifteen generated libraries including Tech Circuit, Decorative, Engraving, Arrows, Stipple, Pressure Sensitive, Ink and Wash, Bristle Brushes and Dry Media, User Defined, Other Library…, Save Brushes); symbol editing shows draggable 9-slice guides (#5280), with guides outside the artwork still unsupported; brushes/symbols in progress | 23–37 |
| M11 | Artboards & views (selected-set deletion shared by Artboards menu, trash and Properties, retaining artboard 1 when all are selected; Artboard deletion keys keep the first of an all-selected set and protect artwork; history prunes invalid indices while preserving valid multiselection (history tests and full workspace CI pass); click-to-fit objects with the Artboard tool (#1227), artboard escape routing and document setup modal handoff done; artboard panel/tool with Move Artwork for X/Y fields and Artboard Options, Trim View (hiding the guides and the grid while it is on, #8363), middle-button pan, print tiling and the status bar's artboard navigator with synchronized Artboard tool selection done; Window › Arrange › Tile and Consolidate All Windows done; multiple windows, presentation polish) (cached canvas reprojection preserves scale during resize, rotation and DPI changes; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged) (cached canvas dimensions match the renderer limit before cache-key creation, view construction and worker submission; regression-tested; estimates unchanged); status-bar pointer coordinates follow the active ruler origin and General units | 🟡; Artboard Options shares existing presets and orientation controls and can fit artwork without moving it; artwork fitting includes all drawn document art across artboards and off-board; artwork bounds are cached by active document and revision, and selection uses the shared bounds cache across artboards | 15–25 |
| M12 | Advanced color & art (CMYK/ICC, separations, Gradient Mesh, Live Paint, Image Trace, Graphs) | 🟡 Gradient Mesh, Live Paint, Image Trace (junction-returning pieces retain their positioned boundaries; a simpler contour walk with identical output; an edge's sub-pixel shift is the same from either side; notches read only their own piece; collapsed loops keep few segments; large images trace with a warning; Auto Color keeps rare distinct colours; quick presets trace at once and the Image Trace button opens the adjustment controls; Properties reopens them; tiny fitted contours retain islands and holes; Create Strokes: exact crop EDT, Guo–Hall thinning and maximal-disc graph simplification; 15 presets, the 14 documented ones each with an enhanced version; Ignore Color (manual picker and canvas eyedropper from original pixels, no canvas View change, missed pixels keep the pick armed, Preview/Undo retained; #8068), Shapes, Auto Grouping and Gradients options; measured in `image-trace-quality.md`; closed outlines retain their interior after straightening; the Flat Logo mode places edges to a fraction of a pixel, restores sharp corners, snaps lines and circles, and refuses gradients; live trace result bounds and selection highlights exclude the retained bitmap except in source-image views), Recolor Artwork, colour management (ICC, soft proofing, separations preview), Graphs (all 9 tools, Graph Data/Type, group-selected series colours persist through regenerate/save/open) done; Graph Design and Marker designs, Transpose and Switch x/y, `\|` label line breaks, the pie options, drop shadows, the legend across the top, overlapping widths, First Row/Column in Front, filled lines, kept label formatting and the Graph Data worksheet done; graph Column designs pending; Vector Halftone Preview keeps the selection box without drawing dot selection marks (#6369); Live Paint Bucket fills faces crossed in one drag (#6373) Sampler-owned release/Zoom regression source uses the native canvas and covers ordinary navigation, dock rejection, accepted sampling, unchanged non-view state and no idle replay (#8744; all 25 cases passed in the e8f96d6 CI preview). | 6–10 |
| M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 MCP `add_text` exposes existing vertical point, area and path type; `script.run` and File › Scripts › Other Script… run JavaScript files, and Window › Script Console shows their output; scripts have `app`, the open documents, new documents, each document's selection and its page items, its text frames, text ranges and their attributes, its character and paragraph styles, the installed fonts, its stories and threaded frames, and its linked and embedded images (`PlacedItem` and `RasterItem`), and save, export, open and close documents with `Document.saveAs`, `Document.exportFile`, `app.open` and `Document.close`; the rest of the script document model (layers, artboards, paths, text lines and the other classes) and batch work remain | 18–27 |
| M13 | Automation (Actions ✅ record/playback, persisted; variables, scripting, batch) | 🟡 MCP `add_text` exposes existing vertical point, area and path type; `script.run` and File › Scripts › Other Script… run JavaScript files, and Window › Script Console shows their output; scripts have `app`, the open documents, new documents, each document's selection and its page items, its layers, groups, compound paths and artboards, its text frames, text ranges and their attributes, its character and paragraph styles, the installed fonts, its stories and threaded frames, and its linked and embedded images (`PlacedItem` and `RasterItem`), save, export, open and close documents with `Document.saveAs`, `Document.exportFile`, `app.open` and `Document.close`, and `Document.pathItems` makes paths and reads and changes their points, colors, stroke options and transforms; layer opacity reads rounded to 4 decimals, and assigning the read number or one that stores as the same opacity runs no command; the rest of the script document model (the `pathItems` of layers and groups, text lines, gradient stops and the other classes) and batch work remain | 18–27 |
| M14 | 1.0 polish (Properties Quick Actions follow the whole selection: Ungroup for any group, Isolate Group for one group, Unite only for selections of at least two objects, each a non-guide path or a compound path, G12, `panels::properties::tests::two_groups_offer_ungroup_without_isolate_group`, `one_group_offers_ungroup_and_isolate_group`, `several_paths_offer_group_clipping_mask_and_unite`; Asset Export tile context menus implemented for G12; preferences, shortcut editor, workspaces, accessibility, packaging for all OSes) (status messages and readouts use stable responsive allocations sized for localized labels and ordinary coordinates; sample widths cached by language/unit/DPI; regression-tested and contributor-confirmed 2026-10-19; estimates unchanged); Tools toolbar Search opens the existing tool-aware command palette (#8758) | 🟡 Icon-strip flyouts resize on their free edges and retain sizes (#5713); interim macOS cursor delivery (#2292) uses existing artwork and host-owned AppKit cursors; headless coverage only, native menu/focus/handback and display validation pending. Dock groups collapse to their tabs by a double-click on a tab (UI.8); Preferences › General › Constrain Angle acts for the arrow keys, Shift drags and new objects (#394, 2026-10-21); numeric-field pointer selection and focus regression-tested (#1326; a release more than 1 pt from the press keeps the caret, a tap within 1 pt selects all, #6659); RPM runtime capabilities and glibc floor checked (#1275; real-distro install/start-up pending), Eyedropper cursor with precise-setting checks (#1269), Preferences, shortcut editor (chords with Shift and a punctuation key fire as typed; other apps' text shortcut sets imported), workspaces (each keeps its layout changes until Reset <name>, UI.7), Window › Help Bar shown or hidden apart from the status bar and kept in saved workspaces, panels docked by dragging into any dock group (as tabs or a top/bottom split) or into the icon column, and closed from a dock tab's context menu (UI.6), a custom title bar on Windows/Linux with a Home button, content-sized dialogs, menus that scroll when longer than the window and macOS native menu dismissal done (M14.8), History row context menus (New Document from State, Step to This State, Clear History; G12, #8845), and native macOS save sheets with a Format menu (#866); titled PDF exports set `DisplayDocTitle` for viewers and accessibility checkers (#3646) and give the document language as the catalog's `/Lang` (#3644); accessibility and broader Windows/Linux packaging/QA pending; floating tab groups collapse into the side icon rail and opened rail panels fold back into it (#5925, in part), with pointer and native-window regression coverage; estimates unchanged; numeric spinner arrows keep repeating while held with the mouse (#6307); Swatches item context menus tested in all five views and rendered layouts inspected; Linux full CI passed, Windows engine baseline limitations documented (G12); Graphic Styles item context menus in thumbnail and list views with Options, Duplicate, Delete, Redefine, Break Link (#8755); Appearance panel row context menus for strokes, fills, effects, and root object row (Duplicate, Delete, Hide/Show, Edit Effect…, Clear Appearance, Reduce to Basic Appearance) with secondary click row selection (#8809); Character Styles and Paragraph Styles item context menus (panels::text_styles::tests::right_click_context_menu_*); Window > Toolbars > Compact Tools offers optional denser main Tools spacing in one or two columns, with the existing layout still the default (#7234) | 18–28 |
| — | Interaction fidelity pass (every tool's modifiers, Properties panel per context, isolation, nuance; width-point creation and adjoining adjustment regression-tested; dialog layout reviewed) | ⬜ (new ruler-guide Alt orientation implemented; existing-guide Escape cancellation regression-tested; broader pass remains) | 60–90 |
| — | Hardening at scale (big-file corpus, fuzzing, cross-platform + browser QA) | 🟡 PngSuite integrity and bounded fetching verified (#1729); real-world corpus/manual QA remain | 50–80 |
+7 -6
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.
@@ -1115,26 +1115,27 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
- The control server writes each reply through a 64 KiB buffer. On Windows 11 it sends the 17 MB `document.inspect` reply of a document with 50,000 objects on one layer to a client over loopback in 0.09 s instead of 34 s.
- Scripts: File › Scripts › Other Script… and `script.run` run a JavaScript file against the open documents as one transaction with one undo step for each changed document. A failed or stopped run puts every document back. `crates/engine/src/tests/script_run.rs`.
- Scripts: 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: `Document.pathItems` lists the paths and makes rectangles, rounded rectangles, ellipses, polygons, stars and empty paths with the defaults the help page https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/ gives; each path's points, closed state, fill rule, area, length, guide state, selected points, fill and stroke colors, stroke options and transforms read and change as https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/ and https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/ describe them, and `RGBColor`, `CMYKColor`, `GrayColor`, `LabColor` and `NoColor` make colors (`docs/mcp.md`). `pathItems["name"]` reads a path by name as `pageItems` does, and `removeAll()` deletes nothing and throws when any path is on a locked artboard. A path takes the page item transforms, and `resize` also sets its stroke weight to a `changeLineWidths` percent from 0 to 100000 (at most 1000 points; a member of a compound sets the compound's stroke); gradients move with positions, so a `changeFillGradients` different from `changePositions` throws an error, as do `changeFillPatterns` and `changeStrokePattern` given as different values (`docs/mcp.md` lists these limits). Gradient stops are not there yet. A `PathPoint` of a path in an Objects on Path group goes stale when an edit of another path in the group moves it. `crates/engine/src/tests/script_dom_paths.rs`.
- Scripts: `app.preferences` reads, stores and removes values by key with the type they were set as, keeps them across runs and restarts, and turns the warning before a picked script on with the key `ShowExternalJSXWarning`, and off only after the person answers Yes to a confirm (https://ai-scripting.docsforadobe.dev/jsobjref/Preferences/; the confirm is VectorCraft's own rule); `app` makes, joins, inverts and compares `Matrix` records (https://ai-scripting.docsforadobe.dev/jsobjref/Matrix/), rounding each joined value once from its exact sum of products and deciding whether an inverted value overflows from its exact quotient, and runs Copy, Cut and Paste on the active document inside the run's transaction (https://ai-scripting.docsforadobe.dev/jsobjref/Application/). `crates/engine/src/tests/script_dom_prefs.rs`.
- Scripts: `Document.pathItems` lists the paths and makes rectangles, rounded rectangles, ellipses, polygons, stars and empty paths with the defaults the help page https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/ gives; each path's points, closed state, fill rule, area, length, guide state, selected points, fill and stroke colors, stroke options and transforms read and change as https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/ and https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/ describe them, and `RGBColor`, `CMYKColor`, `GrayColor`, `LabColor` and `NoColor` make colors (`docs/mcp.md`). `pathItems["name"]` reads a path by name as `pageItems` does, and `removeAll()` deletes nothing and throws when any path is hidden or locked or is on a locked artboard. A path takes the page item transforms, and `resize` also sets its stroke weight to a `changeLineWidths` percent from 0 to 100000 (at most 1000 points; a member of a compound sets the compound's stroke); gradients move with positions, so a `changeFillGradients` different from `changePositions` throws an error, as do `changeFillPatterns` and `changeStrokePattern` given as different values (`docs/mcp.md` lists these limits). Gradient stops are not there yet. A `PathPoint` of a path in an Objects on Path group goes stale when an edit of another path in the group moves it. `crates/engine/src/tests/script_dom_paths.rs`.
- Scripts: `Document.placedItems` and `Document.rasterItems` list a document's linked and embedded images; `placedItems.add()` with a `File` assigned to `file` places an image linked, and `PlacedItem.relink(file)` and `embed()` relink and embed it, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PlacedItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PlacedItem/, https://ai-scripting.docsforadobe.dev/jsobjref/RasterItems/ and https://ai-scripting.docsforadobe.dev/jsobjref/RasterItem/ describe them. A raster item's bits per channel, channels, color space and transparency come from its encoded pixels' header. Only files the script may read, of at most 256 MiB and holding an image, are placed or relinked. Rasterizing and capturing are not there yet. `crates/engine/src/tests/script_dom_images.rs`.
- Scripts: `PlacedItem.trace()` and `RasterItem.trace()` make an Image Trace object and return it as a `PluginItem` whose `tracing` gives its path, anchor and color counts, the source image's resolution, `expandTracing()`, `releaseTracing()` and its `TracingOptions`; assigning an option or loading a preset traces it again, except that the view options (`viewRaster` and `viewVector`) only change the view, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PluginItem/, https://ai-scripting.docsforadobe.dev/jsobjref/TracingObject/ and https://ai-scripting.docsforadobe.dev/jsobjref/TracingOptions/ describe them. Tracing again keeps the tracing's note, tags and URL. 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, or deleting paths or type with `removeAll()` so that an image is left at its bottom, 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`.
- Scripts: `app.undo()` and `app.redo()` undo and redo the edits the run made, and each document open before and after the run that it changed gets one undo step. `crates/engine/src/tests/script_dom.rs`.
- Scripts: `document.textFrames` makes point type, area type and type on a path, and each text frame gives its kind, its contents, its text as text ranges with their characters, words and paragraphs (which can add text), their character attributes (size, leading, tracking, baseline shift, scales, rotation, underline, strikethrough, font) and paragraph attributes (alignment, indents, space before and after), outlines and point and area conversion; `app.textFonts` lists the fonts, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItems/, https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/, https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/ and https://ai-scripting.docsforadobe.dev/jsobjref/TextFonts/ describe them (`docs/mcp.md`). Offsets count UTF-16 units, VectorCraft's own rule. Lines, tab stops and colors are not there yet. `crates/engine/src/tests/script_text.rs`.
- Scripts: `document.textFrames` makes point type, area type and type on a path, and each text frame gives its kind, its contents, its text as text ranges with their characters, words and paragraphs (which can add text), their character attributes (size, leading, tracking, baseline shift, scales, rotation, underline, strikethrough, font, fill and stroke colors, stroke weight) and paragraph attributes (alignment, indents, space before and after), outlines and point and area conversion; `app.textFonts` lists the fonts, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItems/, https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/, https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/, https://ai-scripting.docsforadobe.dev/jsobjref/CharacterAttributes/ and https://ai-scripting.docsforadobe.dev/jsobjref/TextFonts/ describe them (`docs/mcp.md`). Offsets count UTF-16 units, VectorCraft's own rule. Lines, tab stops are not there yet. `crates/engine/src/tests/script_text.rs`.
- 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; compound paths expose `PathItems` objects and reject unsupported path creation. 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. The `textFrames` of a layer or group list the type directly in it and put new type on top of its contents (VectorCraft's own rule), as https://ai-scripting.docsforadobe.dev/jsobjref/Layer/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ list them. `crates/engine/src/tests/script_dom.rs`, `crates/engine/src/tests/script_text.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`. `Document.layers`, `Document.activeLayer` and the other classes this list does not name 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 |