mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-04 13:02:50 -05:00
Merge main into feat/scripts-scriptui-palettes
This commit is contained in:
commit
d8caffae61
48 files changed
+4981
-212
No files matched your search
@@ -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);
|
||||
|
||||
@@ -602,6 +602,8 @@ pub struct SaveJob {
|
||||
stamped: Option<i64>,
|
||||
/// The artboards also saved to files of their own (`separateArtboards`).
|
||||
boards: Vec<usize>,
|
||||
/// The client did not give the path: a file the file access refuses before anything is
|
||||
/// written is named as [`super::access::naming_in_error`] names it ([`SaveJob::naming_refusals`]).
|
||||
redact_paths: bool,
|
||||
}
|
||||
|
||||
@@ -972,6 +974,14 @@ impl SaveJob {
|
||||
&self.plan
|
||||
}
|
||||
|
||||
/// The job for a save whose path the client did not give: a file the file access refuses
|
||||
/// before anything is written is named in the error as the request being served may see it
|
||||
/// ([`super::access::naming_in_error`]).
|
||||
pub(crate) fn naming_refusals(mut self) -> Self {
|
||||
self.redact_paths = true;
|
||||
self
|
||||
}
|
||||
|
||||
/// The document when the job was made (what counts as saved once the file is written).
|
||||
pub(crate) fn snapshot(&self) -> &Arc<Document> {
|
||||
&self.snapshot
|
||||
@@ -1245,10 +1255,10 @@ pub fn save_with(s: &mut Session, plan: SavePlan, write: impl FnMut(&str, &[u8])
|
||||
/// A save command: plan, then write with the file system (a native file as it is encoded).
|
||||
pub(crate) fn save(s: &mut Session, mode: SaveMode, p: &Value) -> Result<Value> {
|
||||
let plan = save_plan(s, mode, p)?;
|
||||
let mut job = save_job(s, plan)?;
|
||||
let uid = s.doc()?.uid;
|
||||
let given = str_param(p, "path").is_some_and(|g| !g.is_empty());
|
||||
job.redact_paths = !given;
|
||||
let job = save_job(s, plan)?;
|
||||
let job = if given { job } else { job.naming_refusals() };
|
||||
let uid = s.doc()?.uid;
|
||||
// Without a path, the files written are the document's own file and those beside it.
|
||||
let mut write = |path: &str, fill: &mut dyn FnMut(&mut dyn std::io::Write) -> std::io::Result<()>| {
|
||||
super::write_save_file_with(path, fill).map_err(|e| if given { e } else { super::access::naming_in_error(e, path) })
|
||||
|
||||
@@ -71,9 +71,163 @@ fn export(s: &mut Session, p: Value) -> (Vec<u8>, Vec<String>) {
|
||||
(bytes, v["warnings"].as_array().unwrap().iter().map(|w| w.as_str().unwrap().to_string()).collect())
|
||||
}
|
||||
|
||||
/// The transparency `pdf` has, in its dictionaries.
|
||||
/// Whether `b` ends a PDF token: white space or a delimiter.
|
||||
fn ends_token(b: u8) -> bool {
|
||||
b.is_ascii_whitespace() || b"()<>[]{}/%".contains(&b)
|
||||
}
|
||||
|
||||
/// The offset of object `number generation` in the cross-reference tables of `pdf`, starting at the
|
||||
/// `startxref` at `startxref` and following `/Prev`.
|
||||
fn xref_offset(pdf: &[u8], number: usize, generation: usize, startxref: usize) -> Option<usize> {
|
||||
let mut offset = String::from_utf8_lossy(&pdf[startxref + b"startxref".len()..]).split_ascii_whitespace().next()?.parse::<usize>().ok()?;
|
||||
let mut visited = vec![];
|
||||
loop {
|
||||
if visited.contains(&offset) {
|
||||
return None;
|
||||
}
|
||||
visited.push(offset);
|
||||
let table = String::from_utf8_lossy(pdf.get(offset..)?);
|
||||
let mut words = table.split_ascii_whitespace();
|
||||
if words.next()? != "xref" {
|
||||
return None;
|
||||
}
|
||||
loop {
|
||||
let first = words.next()?;
|
||||
if first == "trailer" {
|
||||
break;
|
||||
}
|
||||
let first = first.parse::<usize>().ok()?;
|
||||
let count = words.next()?.parse::<usize>().ok()?;
|
||||
for index in 0..count {
|
||||
let at = words.next()?.parse::<usize>().ok()?;
|
||||
let entry_generation = words.next()?.parse::<usize>().ok()?;
|
||||
let status = words.next()?;
|
||||
if first.checked_add(index)? == number {
|
||||
return (status == "n" && entry_generation == generation).then_some(at);
|
||||
}
|
||||
}
|
||||
}
|
||||
let trailer = table.split_once("trailer")?.1.split_once(">>")?.0;
|
||||
let mut words = trailer.split(|c: char| c.is_ascii_whitespace() || "/<>[]".contains(c)).filter(|w| !w.is_empty());
|
||||
words.find(|&w| w == "Prev")?;
|
||||
offset = words.next()?.parse().ok()?;
|
||||
}
|
||||
}
|
||||
|
||||
/// The `/Length` of the stream dictionary that ends `text`, read from the outermost dictionary
|
||||
/// after the object's `obj` keyword. The keyword counts only at the start of `text` or after white
|
||||
/// space, so a name such as `/Tag/obj` is not taken for it. An indirect length is read from its
|
||||
/// object in `pdf`. `None` when it is missing or cannot be read.
|
||||
fn stream_length(text: &[u8], pdf: &[u8]) -> Option<usize> {
|
||||
let from = text
|
||||
.windows(3)
|
||||
.enumerate()
|
||||
.rev()
|
||||
.find(|&(at, w)| w == b"obj" && (at == 0 || matches!(text[at - 1], b'\0' | b'\t' | b'\n' | b'\x0c' | b'\r' | b' ')))
|
||||
.map_or(0, |(at, _)| at + 3);
|
||||
let dict = &text[from..];
|
||||
let mut i = dict.windows(2).position(|w| w == b"<<")? + 2;
|
||||
let mut depth = 1usize;
|
||||
let mut length = None;
|
||||
while i < dict.len() && depth > 0 {
|
||||
let rest = &dict[i..];
|
||||
if rest.starts_with(b"<<") {
|
||||
depth += 1;
|
||||
i += 2;
|
||||
} else if rest.starts_with(b">>") {
|
||||
depth -= 1;
|
||||
i += 2;
|
||||
} else if rest[0] == b'<' {
|
||||
// A hex string.
|
||||
i += rest.iter().position(|&b| b == b'>').map_or(rest.len(), |at| at + 1);
|
||||
} else if depth == 1 && rest.starts_with(b"/Length") && rest.get(7).is_none_or(|&b| ends_token(b)) {
|
||||
let value = String::from_utf8_lossy(&rest[7..]);
|
||||
let words: Vec<&str> = value.split(|c: char| c.is_ascii_whitespace() || "/<>[]".contains(c)).filter(|w| !w.is_empty()).take(3).collect();
|
||||
length = match words[..] {
|
||||
// `n g R` is an indirect length: the integer in object `n g`.
|
||||
[n, g, "R", ..] => {
|
||||
let header = format!("{n} {g} obj");
|
||||
let read_length = |at: usize| {
|
||||
let body = String::from_utf8_lossy(&pdf[at + header.len()..]);
|
||||
match body.split_ascii_whitespace().take(2).collect::<Vec<_>>()[..] {
|
||||
[n, "endobj"] => n.parse::<usize>().ok(),
|
||||
_ => None,
|
||||
}
|
||||
};
|
||||
if let Some(startxref) = pdf.windows(b"startxref".len()).rposition(|w| w == b"startxref") {
|
||||
let at =
|
||||
xref_offset(pdf, n.parse().ok()?, g.parse().ok()?, startxref).expect("stream /Length reference is missing from xref");
|
||||
let object = pdf.get(at..).expect("stream /Length xref offset is outside the file");
|
||||
assert!(object.starts_with(header.as_bytes()), "stream /Length xref offset has a different object");
|
||||
read_length(at)
|
||||
} else {
|
||||
pdf.windows(header.len())
|
||||
.enumerate()
|
||||
// An object header starts a line, and the length object holds one integer.
|
||||
.filter(|&(at, w)| w == header.as_bytes() && (at == 0 || matches!(pdf[at - 1], b'\r' | b'\n')))
|
||||
.find_map(|(at, _)| read_length(at))
|
||||
}
|
||||
}
|
||||
[n, ..] => n.parse::<usize>().ok(),
|
||||
[] => None,
|
||||
};
|
||||
i += 7;
|
||||
} else {
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
length
|
||||
}
|
||||
|
||||
/// The transparency `pdf` has, in its dictionaries. Stream data and literal strings are left out:
|
||||
/// the file ID, in the trailer and in the XMP stream, is base64 that changes with the export time
|
||||
/// and can spell `/BM`.
|
||||
fn transparency(pdf: &[u8]) -> Vec<&'static str> {
|
||||
let text = String::from_utf8_lossy(pdf);
|
||||
let mut text = Vec::with_capacity(pdf.len());
|
||||
let mut i = 0;
|
||||
while i < pdf.len() {
|
||||
let rest = &pdf[i..];
|
||||
// A keyword follows white space or a dictionary's `>>`; after `/` it is part of a name.
|
||||
let keyword_start = i == 0 || pdf[i - 1].is_ascii_whitespace() || pdf[i - 1] == b'>';
|
||||
if keyword_start && rest.starts_with(b"endstream") {
|
||||
text.extend_from_slice(b"endstream");
|
||||
i += b"endstream".len();
|
||||
} else if keyword_start && rest.starts_with(b"stream") && matches!(rest.get(b"stream".len()), Some(b'\r' | b'\n')) {
|
||||
// Stream data is the dictionary's `/Length` bytes after the end of line (else it runs to
|
||||
// `endstream`); its bytes are not PDF syntax.
|
||||
let start = i + b"stream".len() + if rest[b"stream".len()..].starts_with(b"\r\n") { 2 } else { 1 };
|
||||
i = match stream_length(&text, pdf) {
|
||||
Some(n) => {
|
||||
let mut end = start.checked_add(n).filter(|&end| end <= pdf.len()).expect("stream /Length is inconsistent with endstream");
|
||||
while matches!(pdf.get(end), Some(b'\r' | b'\n')) {
|
||||
end += 1;
|
||||
}
|
||||
assert!(pdf[end..].starts_with(b"endstream"), "stream /Length is inconsistent with endstream");
|
||||
end
|
||||
}
|
||||
None => i + rest.windows(b"endstream".len()).position(|w| w == b"endstream").expect("stream has no endstream"),
|
||||
};
|
||||
} else if rest[0] == b'(' {
|
||||
// A literal string: balanced parentheses, with `\` escaping the next byte.
|
||||
let mut depth = 0usize;
|
||||
while i < pdf.len() {
|
||||
match pdf[i] {
|
||||
b'\\' => i += 1,
|
||||
b'(' => depth += 1,
|
||||
b')' => depth -= 1,
|
||||
_ => {}
|
||||
}
|
||||
i += 1;
|
||||
if depth == 0 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
text.push(rest[0]);
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
let text = String::from_utf8_lossy(&text);
|
||||
let mut found = vec![];
|
||||
for (what, there) in [
|
||||
("soft masks", text.contains("/SMask") && !text.contains("/SMask/None")),
|
||||
@@ -193,3 +347,79 @@ fn pdf_1_3_files_are_encrypted_with_40_bit_rc4_and_can_be_linearised() {
|
||||
s.execute("document.open", &json!({"dataBase64": vectorcraft_format::base64_encode(&pdf), "name": "old.pdf", "password": "nope"})).is_err()
|
||||
);
|
||||
}
|
||||
|
||||
/// The file ID is base64 that changes with the export time, so it can spell `/BM`; the check
|
||||
/// reads the file's dictionaries only, not its strings or its XMP packet.
|
||||
#[test]
|
||||
fn the_transparency_check_skips_strings_and_metadata() {
|
||||
let pdf = b"%PDF-1.3\n5 0 obj\n<</Title(a/BM/SMask/CA 0.5)>>\nendobj\n6 0 obj\n<</Type/Metadata>>\nstream\n<?xpacket begin=\"\"?><x>q/BMx/S/Transparency</x><?xpacket end=\"r\"?>\nendstream\nendobj\ntrailer\n<</ID[(hIX/BMcE)(hIX/BMcE)]>>\n";
|
||||
assert_eq!(transparency(pdf), Vec::<&str>::new());
|
||||
assert_eq!(transparency(b"<</ExtGState<</G<</BM/Multiply/CA 0.5>>>>>>"), vec!["blend modes", "opacity"]);
|
||||
// A `(` in image data starts no string, and nested and escaped parentheses end where the
|
||||
// string does.
|
||||
let pdf = b"<</Length 3>>\nstream\n(\x00(\nendstream\n<</T(a(b)c\\)d)/SMask 9 0 R>>\n<</S/Transparency>>";
|
||||
assert_eq!(transparency(pdf), vec!["soft masks", "transparency groups"]);
|
||||
// Stream data is skipped by its length, even when it holds `endstream` itself.
|
||||
let pdf = b"1 0 obj\n<</Length 15>>\nstream\nendstream (/BM\nendstream\nendobj\n<</BM/Multiply>>";
|
||||
assert_eq!(transparency(pdf), vec!["blend modes"]);
|
||||
let pdf = b"1 0 obj\n<</Length 13>>\nstream\nendstream /BM\nendstream\nendobj\n";
|
||||
assert_eq!(transparency(pdf), Vec::<&str>::new());
|
||||
let pdf = b"1 0 obj\n<</Length 3>>\nstream\nabc\r\nendstream\nendobj\n<</SMask 9 0 R>>";
|
||||
assert_eq!(transparency(pdf), vec!["soft masks"]);
|
||||
let pdf = b"1 0 obj\n<</Length 3>>\nstream\nabcendstream\nendobj\n<</BM/Multiply>>";
|
||||
assert_eq!(transparency(pdf), vec!["blend modes"]);
|
||||
let pdf = b"1 0 obj\n<</Length 2 0 R>>\nstream\nabc\nendstream\nendobj\n<</SMask 9 0 R>>";
|
||||
assert_eq!(transparency(pdf), vec!["soft masks"]);
|
||||
// Only the stream dictionary's own `/Length` counts, not one in a nested dictionary.
|
||||
let pdf = b"1 0 obj\n<</Length 4/DecodeParms<</Length 1>>>>\nstream\n/BM \nendstream\nendobj\n";
|
||||
assert_eq!(transparency(pdf), Vec::<&str>::new());
|
||||
// `stream` inside a name is not the keyword.
|
||||
let pdf = b"1 0 obj\n<</Type/Upstream\n/BM/Multiply>>\nendobj\n";
|
||||
assert_eq!(transparency(pdf), vec!["blend modes"]);
|
||||
let pdf = b"1 0 obj\n<</Type/stream\n/SMask 9 0 R>>\nendobj\n";
|
||||
assert_eq!(transparency(pdf), vec!["soft masks"]);
|
||||
// An indirect length is read from its object, so `endstream` in the data does not end it.
|
||||
let pdf = b"1 0 obj\n<</Length 2 0 R>>\nstream\nendstream /BM\nendstream\nendobj\n2 0 obj\n13\nendobj\n";
|
||||
assert_eq!(transparency(pdf), Vec::<&str>::new());
|
||||
let payload = b"2 0 obj\n13\nendobj\nendstream /BM";
|
||||
let mut pdf = b"%PDF-1.3\n".to_vec();
|
||||
let stream_at = pdf.len();
|
||||
pdf.extend_from_slice(b"1 0 obj\n<</Length 2 0 R>>\nstream\n");
|
||||
pdf.extend_from_slice(payload);
|
||||
pdf.extend_from_slice(b"\nendstream\nendobj\n");
|
||||
let length_at = pdf.len();
|
||||
pdf.extend_from_slice(format!("2 0 obj\n{}\nendobj\n", payload.len()).as_bytes());
|
||||
let catalog_at = pdf.len();
|
||||
pdf.extend_from_slice(b"3 0 obj\n<</Type/Catalog/Pages 4 0 R>>\nendobj\n");
|
||||
let pages_at = pdf.len();
|
||||
pdf.extend_from_slice(b"4 0 obj\n<</Type/Pages/Kids[]/Count 0>>\nendobj\n");
|
||||
let xref_at = pdf.len();
|
||||
pdf.extend_from_slice(b"xref\n0 5\n0000000000 65535 f\r\n");
|
||||
for at in [stream_at, length_at, catalog_at, pages_at] {
|
||||
pdf.extend_from_slice(format!("{at:010} 00000 n\r\n").as_bytes());
|
||||
}
|
||||
pdf.extend_from_slice(format!("trailer\n<</Size 5/Root 3 0 R>>\nstartxref\n{xref_at}\n%%EOF\n").as_bytes());
|
||||
assert_eq!(transparency(&pdf), Vec::<&str>::new());
|
||||
// A stream with no length and no `endstream` fails rather than hiding the rest of the file.
|
||||
let pdf = b"1 0 obj\n<<>>\nstream\nabc\n<</SMask 9 0 R>>";
|
||||
assert!(std::panic::catch_unwind(|| transparency(pdf)).is_err());
|
||||
for length in [2, 20, 999, usize::MAX] {
|
||||
let pdf = format!("1 0 obj\n<</Length {length}>>\nstream\nabc\nendstream\nendobj\n<</SMask 9 0 R/BM/Multiply>>");
|
||||
let panic = std::panic::catch_unwind(|| transparency(pdf.as_bytes())).expect_err("an inconsistent stream /Length must panic");
|
||||
let message = panic.downcast_ref::<&str>().copied().or_else(|| panic.downcast_ref::<String>().map(String::as_str));
|
||||
assert_eq!(message, Some("stream /Length is inconsistent with endstream"), "length {length}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A name that ends in `obj`, such as `/Tag/obj`, is not the object's `obj` keyword, so the
|
||||
/// stream's `/Length` is still read from the outer dictionary.
|
||||
#[test]
|
||||
fn the_stream_length_skips_names_that_end_in_obj() {
|
||||
let text = b"1 0 obj\n<</Length 5/Tag/obj>>\nstream\n";
|
||||
assert_eq!(stream_length(text, text), Some(5));
|
||||
// NUL is PDF white space, so it may separate the generation number from `obj`.
|
||||
let text = b"1 0 obj\n<</Length 9>>\nstream\nabc\nendstream\nendobj\n2 0\0obj\n<</Length 5>>\nstream\n";
|
||||
assert_eq!(stream_length(text, text), Some(5));
|
||||
let pdf = b"1 0 obj\n<</Length 13/Tag/obj>>\nstream\nendstream /BM\nendstream\nendobj\n";
|
||||
assert_eq!(transparency(pdf), Vec::<&str>::new());
|
||||
}
|
||||
@@ -692,7 +692,19 @@ fn render_raster(doc: &Document, art: &[Node], rect: Rect, ppi: f64, clip: Optio
|
||||
}
|
||||
}
|
||||
}
|
||||
let png = img.to_png().map_err(|e| EngineError::Other(format!("Flatten Transparency: {e}")))?;
|
||||
// The PNG is written with fast compression: the exports that flatten (EPS, PDF 1.3) decode it
|
||||
// again right away.
|
||||
let raw = craft_image_codecs::Image::from_raw(
|
||||
img.width,
|
||||
img.height,
|
||||
craft_image_codecs::ChannelLayout::Rgba,
|
||||
craft_image_codecs::SampleType::U8,
|
||||
img.to_straight(),
|
||||
)
|
||||
.map_err(|e| EngineError::Other(format!("Flatten Transparency: {e}")))?;
|
||||
let opts = craft_image_codecs::EncodeOptions { png_compression: craft_image_codecs::PngCompression::Fast, ..Default::default() };
|
||||
let png = craft_image_codecs::encode(&raw, craft_image_codecs::Format::Png, &opts)
|
||||
.map_err(|e| EngineError::Other(format!("Flatten Transparency: {e}")))?;
|
||||
Ok(Raster { blob: ImageBlob::new("image/png", png), width: img.width, height: img.height, xf, clip })
|
||||
}
|
||||
|
||||
|
||||
@@ -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; 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,9 +1001,32 @@ 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"));
|
||||
}
|
||||
// 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);
|
||||
let from_aligned = from_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")));
|
||||
}
|
||||
@@ -1013,6 +1036,36 @@ fn move_node(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
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);
|
||||
|
||||
@@ -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() {
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -553,7 +553,8 @@ pub fn check_write(path: &str) -> Result<(), String> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// [`check_write`] without recording `path` as written.
|
||||
/// [`check_write`] without adding `path` to the files a script run reports as written, for a
|
||||
/// check made before anything is written.
|
||||
pub(crate) fn check_write_unrecorded(path: &str) -> Result<(), String> {
|
||||
current().map_or(Ok(()), |r| r.check(path, Access::Write))?;
|
||||
check_gate(path, Access::Write)
|
||||
|
||||
@@ -258,7 +258,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, ¶ms);
|
||||
|
||||
+106
-57
@@ -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
|
||||
@@ -99,6 +100,7 @@ use crate::{DocState, Document, NodeId, NodeKind, Session, WindowView};
|
||||
|
||||
mod clipboard;
|
||||
mod images;
|
||||
pub(super) mod layers;
|
||||
mod matrix;
|
||||
pub mod preferences;
|
||||
mod print;
|
||||
@@ -182,6 +184,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
|
||||
@@ -219,6 +229,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 +261,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.
|
||||
@@ -445,7 +470,7 @@ 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 or text range `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 +483,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" => {
|
||||
@@ -926,14 +954,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 +988,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 +2216,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 +2264,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 +2290,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 +2309,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,6 +2329,9 @@ 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 = top_items(&st.doc);
|
||||
@@ -2434,8 +2506,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 +2530,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)
|
||||
@@ -2831,7 +2909,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)
|
||||
@@ -3089,19 +3171,6 @@ 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 {
|
||||
match name? {
|
||||
@@ -3118,10 +3187,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}]")))))
|
||||
@@ -3191,7 +3256,9 @@ const ENUMS: &[(&str, &[&str])] = &[
|
||||
pub(super) fn install(realm: &mut Realm, link: &Link) -> std::result::Result<(), RunError> {
|
||||
text::install_enums(realm)?;
|
||||
for (name, members) in ENUMS.iter().chain(save_open::ENUMS).chain(print::ENUMS).chain(images::ENUMS).chain(tracing::ENUMS) {
|
||||
let items = members.iter().map(|m| (m.to_string(), HostItem::Value(text(format!("{name}.{m}"))))).collect();
|
||||
let mut items: Vec<_> = members.iter().map(|m| (m.to_string(), HostItem::Value(text(format!("{name}.{m}"))))).collect();
|
||||
let aliases = save_open::ALIASES.iter().filter(|(e, _, _)| e == name);
|
||||
items.extend(aliases.map(|(_, alias, m)| (alias.to_string(), HostItem::Value(text(format!("{name}.{m}"))))));
|
||||
realm.define_host_object(name, items)?;
|
||||
}
|
||||
let blend_modes = BLEND_MODES.iter().map(|(m, _)| (m.to_string(), HostItem::Value(text(format!("BlendModes.{m}"))))).collect();
|
||||
@@ -3312,7 +3379,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));
|
||||
@@ -3351,7 +3419,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", &[])),
|
||||
@@ -3455,28 +3523,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));
|
||||
}
|
||||
@@ -3486,21 +3544,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
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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
@@ -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 {
|
||||
|
||||
@@ -397,21 +397,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 +432,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 +458,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 +477,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) => {
|
||||
@@ -476,6 +497,9 @@ fn items_index(h: &super::Host, a: &[Data]) -> Answer {
|
||||
/// path, one in a hidden or locked layer or group, or one on a locked artboard stops it before
|
||||
/// anything is deleted, as `PageItems.removeAll()` does.
|
||||
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) = with_doc(h, doc, |_, st| {
|
||||
let ids = path_items(h, st)?;
|
||||
@@ -1813,8 +1837,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", &[])),
|
||||
|
||||
@@ -8,7 +8,8 @@
|
||||
//! <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/> and
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsSVG/>,
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsAutoCAD/> and
|
||||
//! <https://ai-scripting.docsforadobe.dev/jsobjref/PDFFileOptions/> describe.
|
||||
//!
|
||||
//! Each method runs a command (`file.saveAs`, `document.export`, `document.open`) inside the run's
|
||||
@@ -26,6 +27,12 @@
|
||||
//! one file: the active artboard with `artBoardClipping`, otherwise the bounds of the visible art.
|
||||
//! An SVG with `embedRasterImages` false also writes the document's embedded images beside it,
|
||||
//! and when one of those files may not be written, none of them is.
|
||||
//! - `ExportType.AUTOCAD` is the same value as `ExportType.AutoCAD`. An AutoCAD export writes DXF
|
||||
//! (`.dxf`) only: `AutoCADExportFileFormat.DWG`, the default, throws an error that says DWG is not
|
||||
//! available. An option an `ExportOptionsAutoCAD` object leaves out takes the default its help page
|
||||
//! gives; `colors`, `rasterFormat`, `unit` and `unitScaleRatio`, which have none there, default to
|
||||
//! true colors, PNG, millimeters and 1. `unitScaleRatio` is the number of drawing units for one
|
||||
//! `unit`, more than 0 and at most 1000.
|
||||
//! - An option the classes here map is applied; a listed option that is not mapped is accepted at
|
||||
//! the default its help page gives and throws an error that says it is not available yet at any
|
||||
//! other value; a property the help pages do not list throws an error that names it, unless it is
|
||||
@@ -40,8 +47,8 @@
|
||||
//! save of one artboard writes only the file at the path, holding that artboard. Without
|
||||
//! `saveMultipleArtboards` the range is not used, but a value that is not written as a range of
|
||||
//! artboard numbers throws.
|
||||
//! - `Document.path` is a `Folder` for the folder of the document's file. A document that has no
|
||||
//! file has a `fullName` of a `File` for its name in `Folder.current` and a `path` of `""`.
|
||||
//! - `Document.path` is a `Folder` for the folder of the document's file. A file saved or opened
|
||||
//! under a relative path is in the process's working folder. A document that has no file has a `fullName` of a `File` for its name in `Folder.current` and a `path` of `""`.
|
||||
//! `fullName` and `path` of a document whose file the automation read roots do not allow throw
|
||||
//! `Script file access denied`. Changing `Document.saved` runs `document.setSaved`.
|
||||
//! Assigning its current value runs no command.
|
||||
@@ -64,6 +71,7 @@ use std::cell::Cell;
|
||||
use std::rc::Rc;
|
||||
|
||||
use serde_json::{Map, Value, json};
|
||||
use vectorcraft_doc::Unit;
|
||||
use vectorcraft_js::{Data, HostClass, HostError, HostFunction};
|
||||
|
||||
use super::{
|
||||
@@ -86,6 +94,15 @@ pub(in crate::script) struct State {
|
||||
/// The enumerations these members use, as `dom`'s are made.
|
||||
pub(super) const ENUMS: &[(&str, &[&str])] = &[
|
||||
("ExportType", &["AutoCAD", "FLASH", "GIF", "JPEG", "PNG24", "PNG8", "SVG", "TIFF"]),
|
||||
("AutoCADColors", &["Max8Colors", "Max16Colors", "Max256Colors", "TrueColors"]),
|
||||
(
|
||||
"AutoCADCompatibility",
|
||||
&["AutoCADRelease13", "AutoCADRelease18", "AutoCADRelease14", "AutoCADRelease21", "AutoCADRelease15", "AutoCADRelease24"],
|
||||
),
|
||||
("AutoCADExportFileFormat", &["DXF", "DWG"]),
|
||||
("AutoCADExportOption", &["PreserveAppearance", "MaximizeEditability"]),
|
||||
("AutoCADRasterFormat", &["PNG", "JPEG"]),
|
||||
("AutoCADUnit", &["Points", "Picas", "Inches", "Millimeters", "Centimeters", "Pixels"]),
|
||||
(
|
||||
"Compatibility",
|
||||
&[
|
||||
@@ -182,6 +199,10 @@ pub(super) const ENUMS: &[(&str, &[&str])] = &[
|
||||
("SVGFontType", &["CEFFONT", "OUTLINEFONT", "SVGFONT"]),
|
||||
];
|
||||
|
||||
/// Other names of enumeration members: `(enumeration, name, member)` makes `enumeration.name` the
|
||||
/// same value as `enumeration.member`.
|
||||
pub(super) const ALIASES: &[(&str, &str, &str)] = &[("ExportType", "AUTOCAD", "AutoCAD")];
|
||||
|
||||
const DISPLAY: &str = "UserInteractionLevel.DISPLAYALERTS";
|
||||
const QUIET: &str = "UserInteractionLevel.DONTDISPLAYALERTS";
|
||||
|
||||
@@ -196,7 +217,8 @@ enum Default {
|
||||
Member(&'static str, &'static str),
|
||||
/// The help page gives no default: any value throws.
|
||||
Unset,
|
||||
/// White as an `RGBColor`: red, green and blue each 255.
|
||||
/// White as an `RGBColor`: red, green and blue each 255 (its `typename`, when it has one,
|
||||
/// `RGBColor`).
|
||||
White,
|
||||
}
|
||||
|
||||
@@ -209,7 +231,7 @@ impl Default {
|
||||
(Default::Member(e, m), Data::String(b)) => b.split_once('.').is_some_and(|(be, bm)| be == e && bm == m),
|
||||
(Default::White, Data::Object(items)) => {
|
||||
let get = |k: &str| items.iter().find(|(name, _)| name == k).map(|(_, v)| v);
|
||||
matches!(get("typename"), Some(Data::String(t)) if t == "RGBColor")
|
||||
get("typename").is_none_or(|t| matches!(t, Data::String(t) if t == "RGBColor"))
|
||||
&& ["red", "green", "blue"].iter().all(|k| matches!(get(k), Some(Data::Number(n)) if *n == 255.0))
|
||||
}
|
||||
_ => false,
|
||||
@@ -656,9 +678,118 @@ fn svg_starts() -> Vec<(&'static str, Data)> {
|
||||
]
|
||||
}
|
||||
|
||||
/// The members of the enumeration `name` in [`ENUMS`].
|
||||
fn members_of(name: &str) -> &'static [&'static str] {
|
||||
ENUMS.iter().find(|(n, _)| *n == name).map_or(&[][..], |(_, m)| *m)
|
||||
}
|
||||
|
||||
fn autocad_map(name: &str, d: &Data, p: &mut Map<String, Value>) -> std::result::Result<bool, HostError> {
|
||||
let what = format!("ExportOptionsAutoCAD.{name}");
|
||||
let pick = |enumeration: &str| member(d, enumeration, members_of(enumeration), &what);
|
||||
match name {
|
||||
"alterPathsForAppearance" => {
|
||||
p.insert("alterPaths".into(), json!(boolean(d, &what)?));
|
||||
}
|
||||
"colors" => {
|
||||
let colors = match pick("AutoCADColors")? {
|
||||
"Max8Colors" => json!(8),
|
||||
"Max16Colors" => json!(16),
|
||||
"Max256Colors" => json!(256),
|
||||
_ => json!("true"),
|
||||
};
|
||||
p.insert("colors".into(), colors);
|
||||
}
|
||||
"convertTextToOutlines" => {
|
||||
p.insert("outlineText".into(), json!(boolean(d, &what)?));
|
||||
}
|
||||
"exportFileFormat" => {
|
||||
if pick("AutoCADExportFileFormat")? == "DWG" {
|
||||
return Err(HostError::Error(
|
||||
"AutoCADExportFileFormat.DWG is not available: set exportFileFormat to AutoCADExportFileFormat.DXF".into(),
|
||||
));
|
||||
}
|
||||
}
|
||||
"exportOption" => {
|
||||
let preserve = if pick("AutoCADExportOption")? == "PreserveAppearance" { "appearance" } else { "editability" };
|
||||
p.insert("preserve".into(), json!(preserve));
|
||||
}
|
||||
"exportSelectedArtOnly" => {
|
||||
p.insert("selectedOnly".into(), json!(boolean(d, &what)?));
|
||||
}
|
||||
"rasterFormat" => {
|
||||
p.insert("rasterFormat".into(), json!(if pick("AutoCADRasterFormat")? == "JPEG" { "jpeg" } else { "png" }));
|
||||
}
|
||||
"scaleLineweights" => {
|
||||
p.insert("scaleLineweights".into(), json!(boolean(d, &what)?));
|
||||
}
|
||||
"unit" => {
|
||||
let unit = match pick("AutoCADUnit")? {
|
||||
"Points" => Unit::Points,
|
||||
"Picas" => Unit::Picas,
|
||||
"Inches" => Unit::Inches,
|
||||
"Millimeters" => Unit::Millimeters,
|
||||
"Centimeters" => Unit::Centimeters,
|
||||
_ => Unit::Pixels,
|
||||
};
|
||||
p.insert("unit".into(), json!(unit.key()));
|
||||
}
|
||||
"unitScaleRatio" => {
|
||||
let n = match d {
|
||||
Data::Number(n) if n.is_finite() => *n,
|
||||
_ => return Err(HostError::Type(format!("{what} must be a finite number"))),
|
||||
};
|
||||
if !(n > 0.0 && n <= 1000.0) {
|
||||
return Err(HostError::Range(format!("{what} must be more than 0 and at most 1000")));
|
||||
}
|
||||
p.insert("scale".into(), json!(n));
|
||||
}
|
||||
"version" => {
|
||||
let version = match pick("AutoCADCompatibility")? {
|
||||
"AutoCADRelease13" => "R13",
|
||||
"AutoCADRelease14" => "R14",
|
||||
"AutoCADRelease15" => "2000",
|
||||
"AutoCADRelease18" => "2004",
|
||||
"AutoCADRelease21" => "2007",
|
||||
_ => "2010",
|
||||
};
|
||||
p.insert("version".into(), json!(version));
|
||||
}
|
||||
_ => return Ok(false),
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
fn autocad_starts() -> Vec<(&'static str, Data)> {
|
||||
vec![
|
||||
("alterPathsForAppearance", Data::Bool(false)),
|
||||
("convertTextToOutlines", Data::Bool(false)),
|
||||
("exportFileFormat", text("AutoCADExportFileFormat.DWG")),
|
||||
("exportOption", text("AutoCADExportOption.MaximizeEditability")),
|
||||
("exportSelectedArtOnly", Data::Bool(false)),
|
||||
("scaleLineweights", Data::Bool(false)),
|
||||
("version", text("AutoCADCompatibility.AutoCADRelease24")),
|
||||
]
|
||||
}
|
||||
|
||||
/// The options object `d` with the options of a new `class` object it leaves out, or holds as
|
||||
/// `undefined`, added.
|
||||
fn with_starts(class: &OptionClass, d: &Data) -> Data {
|
||||
let Data::Object(items) = d else { return d.clone() };
|
||||
let mut items = items.clone();
|
||||
for (k, v) in (class.starts)() {
|
||||
match items.iter_mut().find(|(n, _)| n == k) {
|
||||
Some((_, held)) if matches!(held, Data::Undefined) => *held = v,
|
||||
Some(_) => {}
|
||||
None => items.push((k.to_string(), v)),
|
||||
}
|
||||
}
|
||||
Data::Object(items)
|
||||
}
|
||||
|
||||
const PNG24: OptionClass = OptionClass { name: "ExportOptionsPNG24", map: png24_map, kept: PNG24_KEPT, starts: png24_starts };
|
||||
const JPEG: OptionClass = OptionClass { name: "ExportOptionsJPEG", map: jpeg_map, kept: JPEG_KEPT, starts: jpeg_starts };
|
||||
const SVG: OptionClass = OptionClass { name: "ExportOptionsSVG", map: svg_map, kept: SVG_KEPT, starts: svg_starts };
|
||||
const AUTOCAD: OptionClass = OptionClass { name: "ExportOptionsAutoCAD", map: autocad_map, kept: &[], starts: autocad_starts };
|
||||
|
||||
/// An `ExportType`: the format `document.export` writes, the extensions a file name may already
|
||||
/// end with (the first is added), and its option class (`None`: no options are taken).
|
||||
@@ -669,9 +800,9 @@ struct ExportKind {
|
||||
}
|
||||
|
||||
fn export_kind(d: &Data) -> std::result::Result<ExportKind, HostError> {
|
||||
let all = ENUMS.iter().find(|(n, _)| *n == "ExportType").map_or(&[][..], |(_, m)| *m);
|
||||
let raster = |format, extensions| ExportKind { format, extensions, options: None };
|
||||
Ok(match member(d, "ExportType", all, "exportType")? {
|
||||
Ok(match member(d, "ExportType", members_of("ExportType"), "exportType")? {
|
||||
"AutoCAD" => ExportKind { format: "dxf", extensions: &["dxf"], options: Some(&AUTOCAD) },
|
||||
"PNG24" => ExportKind { format: "png", extensions: &["png"], options: Some(&PNG24) },
|
||||
"JPEG" => ExportKind { format: "jpg", extensions: &["jpg", "jpeg"], options: Some(&JPEG) },
|
||||
"SVG" => ExportKind { format: "svg", extensions: &["svg"], options: Some(&SVG) },
|
||||
@@ -848,11 +979,26 @@ fn doc_export_file(h: &Host, a: &[Data]) -> Answer {
|
||||
None => Map::new(),
|
||||
},
|
||||
Some(o) => match kind.options {
|
||||
// An AutoCAD option left out takes its help page's default, not the DXF writer's.
|
||||
Some(class) if class.name == AUTOCAD.name => options_params(class, &with_starts(class, o))?,
|
||||
Some(class) => options_params(class, o)?,
|
||||
None if matches!(o, Data::Null) => return Err(HostError::Type("the options must be an object".into())),
|
||||
None => return Err(HostError::Error(format!("options for {} are not available yet", kind.format))),
|
||||
},
|
||||
};
|
||||
// A DXF version before 2004 holds no true color: with `colors` left out it takes 256 indexed
|
||||
// colors, and `AutoCADColors.TrueColors` with it throws.
|
||||
if kind.format == "dxf" && matches!(p.get("version").and_then(Value::as_str), Some("R13" | "R14" | "2000")) {
|
||||
match p.get("colors") {
|
||||
None => {
|
||||
p.insert("colors".into(), json!(256));
|
||||
}
|
||||
Some(c) if c.as_str() == Some("true") => {
|
||||
return Err(HostError::Error("AutoCADColors.TrueColors needs AutoCADRelease18 or a later version".into()));
|
||||
}
|
||||
Some(_) => {}
|
||||
}
|
||||
}
|
||||
let svgz = p.remove("_svgz").and_then(|v| v.as_bool()).unwrap_or(false);
|
||||
let clip = p.remove("_clip").and_then(|v| v.as_bool()).unwrap_or(false);
|
||||
let (hs, vs) = (p.remove("_h").and_then(|v| v.as_f64()).unwrap_or(100.0), p.remove("_v").and_then(|v| v.as_f64()).unwrap_or(100.0));
|
||||
@@ -860,7 +1006,8 @@ fn doc_export_file(h: &Host, a: &[Data]) -> Answer {
|
||||
return Err(HostError::Error("different horizontalScale and verticalScale are not available yet".into()));
|
||||
}
|
||||
// A raster file has one pixel per point at 100%, whatever the document's raster effects resolution.
|
||||
if kind.format != "svg" {
|
||||
// A DXF's `scale` is its drawing units per unit, from `unitScaleRatio`.
|
||||
if !matches!(kind.format, "svg" | "dxf") {
|
||||
p.insert("scale".into(), json!(hs / 100.0));
|
||||
}
|
||||
let format = if svgz { "svgz" } else { kind.format };
|
||||
@@ -1140,7 +1287,7 @@ pub(super) fn document_members(l: &Link) -> Vec<Described> {
|
||||
/// The option classes: each `new Name()` gives a record with its `typename` and the defaults its
|
||||
/// help page gives for the options mapped here.
|
||||
pub(super) fn classes(link: &Link) -> Vec<HostClass> {
|
||||
let all = SAVE_CLASSES.iter().map(|(c, _)| c).chain([&PNG24, &JPEG, &SVG]);
|
||||
let all = SAVE_CLASSES.iter().map(|(c, _)| c).chain([&PNG24, &JPEG, &SVG, &AUTOCAD]);
|
||||
all.map(|c| {
|
||||
let l = link.clone();
|
||||
let f: HostFunction = Rc::new(move |_: Vec<Data>| {
|
||||
|
||||
@@ -2484,7 +2484,7 @@ impl Session {
|
||||
engine: engine.clone(),
|
||||
file: request.file.clone(),
|
||||
palette_event: RefCell::new(palette_event),
|
||||
dom: dom::State::new(heap_bytes),
|
||||
dom: dom::State::new(self.documents(), heap_bytes),
|
||||
actions: request.actions,
|
||||
palette_actions: RefCell::new(None),
|
||||
active_artboards: self.docs.iter().map(|d| (d.uid, dom::active_artboard(d))).collect(),
|
||||
@@ -2804,6 +2804,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
|
||||
|
||||
@@ -350,6 +350,41 @@ fn gradients_rasterize_and_flat_areas_stay_vector() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A rasterized area is stored as a PNG written with fast compression: its zlib header (RFC 1950)
|
||||
/// gives compression level 0, the fastest.
|
||||
#[test]
|
||||
fn rasterized_areas_are_png_with_fast_compression() {
|
||||
let _settings = settings_lock();
|
||||
let mut s = session();
|
||||
let g = rect(&mut s, 10.0, 10.0, 100.0, 100.0, "#000000");
|
||||
run(
|
||||
&mut s,
|
||||
"paint.setFill",
|
||||
json!({"ids": [g], "gradient": {"kind": "linear", "stops": [{"offset": 0, "color": "#ff0000"}, {"offset": 1, "color": "#0000ff"}]}}),
|
||||
);
|
||||
run(&mut s, "transparency.set", json!({"ids": [g], "opacity": 40}));
|
||||
let (ids, _, rasterized) = flatten(&mut s, json!({"ids": [g], "preset": "high"}));
|
||||
assert_eq!(rasterized, 1);
|
||||
let mut keys = vec![];
|
||||
node(&s, ids[0]).walk(&mut |c| {
|
||||
if let NodeKind::Image(im) = &c.kind {
|
||||
keys.push(im.key.clone());
|
||||
}
|
||||
});
|
||||
let [key] = &keys[..] else { panic!("one image: {keys:?}") };
|
||||
let png = &s.doc().unwrap().doc.images[key].bytes;
|
||||
assert!(png.starts_with(b"\x89PNG\r\n\x1a\n"), "a PNG");
|
||||
let mut at = 8;
|
||||
let level = loop {
|
||||
let (Some(len), Some(kind)) = (png.get(at..at + 4), png.get(at + 4..at + 8)) else { panic!("a PNG with image data") };
|
||||
if kind == b"IDAT" {
|
||||
break png[at + 9] >> 6;
|
||||
}
|
||||
at += 12 + u32::from_be_bytes(len.try_into().unwrap()) as usize;
|
||||
};
|
||||
assert_eq!(level, 0, "zlib FLEVEL of the stored PNG");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_long_rasterized_area_is_placed_whole() {
|
||||
let _settings = settings_lock();
|
||||
|
||||
@@ -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
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -339,13 +339,17 @@ fn omitted_options_are_a_new_options_objects_defaults() {
|
||||
d.exportFile(new File(dir + '/j2'), ExportType.JPEG, new ExportOptionsJPEG());\n\
|
||||
d.exportFile(new File(dir + '/p1'), ExportType.PNG24);\n\
|
||||
d.exportFile(new File(dir + '/p2'), ExportType.PNG24, new ExportOptionsPNG24());\n\
|
||||
var j3 = new ExportOptionsJPEG(); j3.matteColor = {{red: 255, green: 255, blue: 255}};\n\
|
||||
d.exportFile(new File(dir + '/j3'), ExportType.JPEG, j3);\n\
|
||||
var p3 = new ExportOptionsPNG24(); p3.matteColor = {{typename: 'RGBColor', red: 255, green: 255, blue: 255}};\n\
|
||||
d.exportFile(new File(dir + '/p3'), ExportType.PNG24, p3);\n\
|
||||
d.exportFile(new File(dir + '/s1'), ExportType.SVG);\n\
|
||||
d.exportFile(new File(dir + '/s2'), ExportType.SVG, new ExportOptionsSVG());\n\
|
||||
d.saveAs(new File(dir + '/a1.pdf'));\n\
|
||||
d.saveAs(new File(dir + '/a2.pdf'), new PDFSaveOptions());"
|
||||
),
|
||||
);
|
||||
for (one, two) in [("j1.jpg", "j2.jpg"), ("p1.png", "p2.png"), ("s1.svg", "s2.svg")] {
|
||||
for (one, two) in [("j1.jpg", "j2.jpg"), ("j1.jpg", "j3.jpg"), ("p1.png", "p2.png"), ("p1.png", "p3.png"), ("s1.svg", "s2.svg")] {
|
||||
assert!(std::fs::read(dir.join(one)).unwrap() == std::fs::read(dir.join(two)).unwrap(), "{one} and {two} differ");
|
||||
}
|
||||
for name in ["a1.pdf", "a2.pdf"] {
|
||||
@@ -523,6 +527,85 @@ fn a_raster_export_at_100_percent_has_a_pixel_per_point() {
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// The value of the DXF header variable `name` (the group after its name).
|
||||
fn dxf_header(dxf: &str, name: &str) -> Option<String> {
|
||||
let lines: Vec<&str> = dxf.lines().map(str::trim).collect();
|
||||
lines.iter().position(|l| *l == name).and_then(|i| lines.get(i + 2)).map(|v| v.to_string())
|
||||
}
|
||||
|
||||
/// The largest x coordinate (group code 10) in the entities of a DXF.
|
||||
fn dxf_widest(dxf: &str) -> f64 {
|
||||
dxf_xs(dxf).into_iter().reduce(f64::max).expect("DXF contains polyline vertices")
|
||||
}
|
||||
|
||||
/// The smallest x coordinate (group code 10) in the entities of a DXF.
|
||||
fn dxf_leftmost(dxf: &str) -> f64 {
|
||||
dxf_xs(dxf).into_iter().reduce(f64::min).expect("DXF contains polyline vertices")
|
||||
}
|
||||
|
||||
/// The x coordinates (group code 10) of the polyline vertices in a DXF. A hatch's code 10 is its
|
||||
/// elevation point, so hatches are left out.
|
||||
fn dxf_xs(dxf: &str) -> Vec<f64> {
|
||||
let lines: Vec<&str> = dxf.lines().map(str::trim).collect();
|
||||
// The section's name is a value; the group codes start on the line after it.
|
||||
let start = lines.iter().position(|l| *l == "ENTITIES").map_or(0, |i| i + 1);
|
||||
let mut entity = "";
|
||||
let mut xs = Vec::new();
|
||||
for p in lines[start..].chunks(2).filter(|p| p.len() == 2) {
|
||||
match p[0] {
|
||||
"0" => entity = p[1],
|
||||
"10" if entity == "LWPOLYLINE" => xs.extend(p[1].parse::<f64>().ok()),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
xs
|
||||
}
|
||||
|
||||
/// `exportFile` with `ExportType.AutoCAD` writes a DXF with the `ExportOptionsAutoCAD` options, and
|
||||
/// DWG, the help page's default format, throws without writing a file.
|
||||
#[test]
|
||||
fn an_autocad_export_writes_a_dxf_with_its_options() {
|
||||
let base = folder("autocad");
|
||||
let mut s = session(&base);
|
||||
let dir = data_folder(&mut s, &base);
|
||||
let d = quoted(&dir);
|
||||
let out = logged(
|
||||
&mut s,
|
||||
&base,
|
||||
&format!(
|
||||
"Folder.userData; var dir = {d}, d = app.documents.add(DocumentColorSpace.RGB, 200, 100);\n\
|
||||
vc.run('shape.rectangle', {{x: 10, y: 10, width: 50, height: 20}});\n\
|
||||
var o = new ExportOptionsAutoCAD(); vc.log([o.typename, o.exportFileFormat, o.version, ExportType.AUTOCAD === ExportType.AutoCAD]);\n\
|
||||
try {{ d.exportFile(new File(dir + '/w'), ExportType.AutoCAD, o); }} catch (e) {{ vc.log(String(e)); }}\n\
|
||||
o.exportFileFormat = AutoCADExportFileFormat.DXF; o.version = AutoCADCompatibility.AutoCADRelease15;\n\
|
||||
o.unit = AutoCADUnit.Inches; o.unitScaleRatio = 25.4; o.colors = AutoCADColors.Max256Colors; o.rasterFormat = AutoCADRasterFormat.JPEG;\n\
|
||||
d.exportFile(new File(dir + '/a'), ExportType.AutoCAD, o);\n\
|
||||
o.unitScaleRatio = 1; d.exportFile(new File(dir + '/b.DXF'), ExportType.AUTOCAD, o);\n\
|
||||
o.unit = AutoCADUnit.Picas; d.exportFile(new File(dir + '/p'), ExportType.AutoCAD, o);\n\
|
||||
var u = new ExportOptionsAutoCAD(); u.exportFileFormat = AutoCADExportFileFormat.DXF; u.version = undefined; d.exportFile(new File(dir + '/u'), ExportType.AutoCAD, u);\n\
|
||||
d.exportFile(new File(dir + '/c'), ExportType.AutoCAD, {{typename: 'ExportOptionsAutoCAD', exportFileFormat: AutoCADExportFileFormat.DXF, version: undefined}});"
|
||||
),
|
||||
);
|
||||
assert_eq!(out[0], json!(["ExportOptionsAutoCAD", "AutoCADExportFileFormat.DWG", "AutoCADCompatibility.AutoCADRelease24", true]));
|
||||
assert!(out[1].as_str().is_some_and(|e| e.contains("DWG is not available")), "{}", out[1]);
|
||||
assert!(!dir.join("w.dxf").exists() && !dir.join("w.dwg").exists() && !dir.join("w").exists(), "DWG writes nothing");
|
||||
let a = std::fs::read_to_string(dir.join("a.dxf")).unwrap();
|
||||
let b = std::fs::read_to_string(dir.join("b.DXF")).unwrap();
|
||||
assert!(!dir.join("b.DXF.dxf").exists(), "a name that ends with the extension keeps it");
|
||||
assert_eq!(dxf_header(&a, "$ACADVER").as_deref(), Some("AC1015"), "AutoCADRelease15 is the 2000 format");
|
||||
assert_eq!(dxf_header(&b, "$INSUNITS").as_deref(), Some("1"), "inches, one drawing unit each");
|
||||
assert!(dxf_widest(&a) > dxf_widest(&b) * 20.0, "unitScaleRatio scales the drawing: {} and {}", dxf_widest(&a), dxf_widest(&b));
|
||||
for name in ["c.dxf", "u.dxf"] {
|
||||
let dxf = std::fs::read_to_string(dir.join(name)).unwrap();
|
||||
assert_eq!(dxf_header(&dxf, "$ACADVER").as_deref(), Some("AC1024"), "{name}: an option left out or undefined is AutoCADRelease24");
|
||||
// The rectangle is 10 pt (3.5 mm) from the artboard's left edge.
|
||||
assert!(dxf_leftmost(&dxf).abs() < 1.0, "{name}: the origin is at the visible art's bounds: {}", dxf_leftmost(&dxf));
|
||||
}
|
||||
let p = std::fs::read_to_string(dir.join("p.dxf")).unwrap();
|
||||
assert!(dxf_widest(&p) > dxf_widest(&b) * 5.0, "a pica is a sixth of an inch: {} and {}", dxf_widest(&p), dxf_widest(&b));
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// With `pDFPreset` named, the options left at a new object's defaults keep the preset's values, and
|
||||
/// an option the script changes applies over the preset.
|
||||
#[test]
|
||||
@@ -606,7 +689,7 @@ fn an_export_writes_nothing_when_a_folder_is_where_one_of_its_files_goes() {
|
||||
}
|
||||
|
||||
/// When the writer a save is given does not check the file access itself, a save of several files
|
||||
/// whose file access refuses one of them hands none of them to the writer.
|
||||
/// whose last file is refused hands none of them to the writer, the refused one included.
|
||||
#[test]
|
||||
fn a_refused_file_stops_a_save_whose_writer_does_not_check() {
|
||||
use crate::cmd::fileio::{SaveMode, save_job, save_plan};
|
||||
@@ -643,9 +726,10 @@ fn a_refused_file_stops_a_save_whose_writer_does_not_check() {
|
||||
Ok(())
|
||||
})
|
||||
});
|
||||
assert!(r.is_err(), "{r:?}");
|
||||
let e = r.unwrap_err().to_string();
|
||||
let refused = refused.unwrap();
|
||||
assert_eq!(written, Vec::<String>::new(), "no file went to the writer, the refused one ({refused}) included");
|
||||
assert!(e.contains(DENIED) && e.contains(&refused), "{e}");
|
||||
assert!(written.is_empty(), "no file went to the writer: {written:?}");
|
||||
let mut perms = std::fs::metadata(&refused).unwrap().permissions();
|
||||
#[allow(clippy::permissions_set_readonly_false)]
|
||||
perms.set_readonly(false);
|
||||
@@ -948,6 +1032,12 @@ fn bad_arguments_are_refused_with_an_error() {
|
||||
(format!("var o = new EPSSaveOptions(); o.postScript = 'LEVEL2'; app.activeDocument.saveAs({f}, o);"), "EPSPostScriptLevelEnum"),
|
||||
(format!("app.activeDocument.exportFile({f}, 'PNG24');"), "ExportType"),
|
||||
(format!("app.activeDocument.exportFile({f}, ExportType.FLASH);"), "is not available yet"),
|
||||
(
|
||||
format!(
|
||||
"var p = new ExportOptionsPNG24(); p.matteColor = {{red: 255, green: 0, blue: 255}}; app.activeDocument.exportFile({f}, ExportType.PNG24, p);"
|
||||
),
|
||||
"ExportOptionsPNG24.matteColor is not available yet",
|
||||
),
|
||||
(format!("app.activeDocument.exportFile({f}, ExportType.PNG24, new ExportOptionsJPEG());"), "ExportOptionsPNG24"),
|
||||
(
|
||||
format!(
|
||||
@@ -970,6 +1060,41 @@ fn bad_arguments_are_refused_with_an_error() {
|
||||
"from 0 to 100",
|
||||
),
|
||||
(format!("app.activeDocument.exportFile({f}, ExportType.GIF, {{}});"), "not available yet"),
|
||||
(format!("app.activeDocument.exportFile({f}, ExportType.AutoCAD);"), "DWG is not available"),
|
||||
(
|
||||
format!("var o = new ExportOptionsAutoCAD(); o.exportFileFormat = undefined; app.activeDocument.exportFile({f}, ExportType.AUTOCAD, o);"),
|
||||
"DWG is not available",
|
||||
),
|
||||
(
|
||||
format!(
|
||||
"var o = new ExportOptionsAutoCAD(); o.exportFileFormat = AutoCADExportFileFormat.DXF; o.unitScaleRatio = 2000; app.activeDocument.exportFile({f}, ExportType.AutoCAD, o);"
|
||||
),
|
||||
"at most 1000",
|
||||
),
|
||||
(
|
||||
format!(
|
||||
"var o = new ExportOptionsAutoCAD(); o.exportFileFormat = AutoCADExportFileFormat.DXF; o.version = 'AutoCADCompatibility.AutoCADRelease99'; app.activeDocument.exportFile({f}, ExportType.AutoCAD, o);"
|
||||
),
|
||||
"AutoCADCompatibility",
|
||||
),
|
||||
(
|
||||
format!(
|
||||
"var o = new ExportOptionsAutoCAD(); o.exportFileFormat = AutoCADExportFileFormat.DXF; o.colors = 256; app.activeDocument.exportFile({f}, ExportType.AutoCAD, o);"
|
||||
),
|
||||
"AutoCADColors",
|
||||
),
|
||||
(
|
||||
format!(
|
||||
"var o = new ExportOptionsAutoCAD(); o.exportFileFormat = AutoCADExportFileFormat.DXF; o.unitScale = 2; app.activeDocument.exportFile({f}, ExportType.AutoCAD, o);"
|
||||
),
|
||||
"ExportOptionsAutoCAD has no option unitScale",
|
||||
),
|
||||
(
|
||||
format!(
|
||||
"var o = new ExportOptionsAutoCAD(); o.exportFileFormat = AutoCADExportFileFormat.DXF; o.version = AutoCADCompatibility.AutoCADRelease14; o.colors = AutoCADColors.TrueColors; app.activeDocument.exportFile({f}, ExportType.AutoCAD, o);"
|
||||
),
|
||||
"TrueColors needs AutoCADRelease18",
|
||||
),
|
||||
(format!("app.open({f}, 'RGB');"), "DocumentColorSpace"),
|
||||
(format!("app.open({f}, undefined, {{pageToOpen: 0}});"), "from 1"),
|
||||
(format!("app.open({f}, undefined, {{pDFCropToBox: 'art'}});"), "PDFBoxType"),
|
||||
@@ -1274,6 +1399,51 @@ fn full_name_path_saved_and_close_follow_the_documents_file() {
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// A document whose file was saved under a relative name is in the working folder the file was
|
||||
/// written in.
|
||||
#[test]
|
||||
fn path_of_a_file_saved_under_a_relative_name_is_the_working_folder() {
|
||||
let base = folder("relative");
|
||||
let mut s = session(&base);
|
||||
s.execute("file.new", &json!({"width": 100, "height": 100})).unwrap();
|
||||
s.active_mut().unwrap().path = Some("drawing.svg".into());
|
||||
let out = logged(
|
||||
&mut s,
|
||||
&base,
|
||||
"var d = app.activeDocument; vc.log([d.path instanceof Folder, d.path === '' ? '' : d.path.fsName, d.fullName.fsName]);",
|
||||
);
|
||||
let cwd = std::env::current_dir().unwrap();
|
||||
assert_eq!(out[0][0], json!(true), "{out}");
|
||||
let same = |shown: &str, want: &Path| {
|
||||
let shown = PathBuf::from(shown);
|
||||
shown == want || std::fs::canonicalize(&shown).ok().zip(std::fs::canonicalize(want).ok()).is_some_and(|(a, b)| a == b)
|
||||
};
|
||||
assert!(same(out[0][1].as_str().unwrap(), &cwd), "{out} is not in {cwd:?}");
|
||||
let file = out[0][2].as_str().unwrap();
|
||||
assert!(Path::new(file).is_absolute() && Path::new(file).file_name() == Some("drawing.svg".as_ref()), "{file}");
|
||||
assert!(same(&Path::new(file).parent().unwrap().to_string_lossy(), &cwd), "{file} is not in {cwd:?}");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// The warnings a save gives, such as editing data left out of a PDF of one artboard of several, go
|
||||
/// to the Script Console.
|
||||
#[test]
|
||||
fn a_saves_warnings_go_to_the_console() {
|
||||
let base = folder("warnings");
|
||||
let mut s = session(&base);
|
||||
let dir = data_folder(&mut s, &base);
|
||||
s.execute("file.new", &json!({"width": 200, "height": 100, "artboards": 2})).unwrap();
|
||||
let save = format!(
|
||||
"Folder.userData; var o = new PDFSaveOptions(); o.preserveEditability = true; o.artboardRange = '1';\n\
|
||||
app.activeDocument.saveAs(new File({}), o);",
|
||||
quoted(&dir.join("one.pdf"))
|
||||
);
|
||||
let r = run(&mut s, &base, &save).unwrap();
|
||||
let lines = r["console"]["lines"].as_array().unwrap();
|
||||
assert!(lines.iter().any(|l| l.as_str().is_some_and(|l| l.starts_with("saveAs: "))), "{lines:?}");
|
||||
let _ = std::fs::remove_dir_all(base);
|
||||
}
|
||||
|
||||
/// A document without unsaved changes closes with `SaveOptions.SAVECHANGES` and with no argument.
|
||||
#[test]
|
||||
fn a_document_without_unsaved_changes_closes_with_any_save_options() {
|
||||
|
||||
@@ -97,10 +97,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"),
|
||||
@@ -129,14 +130,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"),
|
||||
@@ -144,15 +145,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 \
|
||||
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 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",
|
||||
@@ -189,7 +223,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.",
|
||||
@@ -245,6 +282,13 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
PDFOverprint PDFPrintAllowedEnum PDFTrimMarkWeight PDFXStandard PageMarksTypes SVGCSSPropertyLocation SVGDTDVersion \
|
||||
SVGDocumentEncoding SVGFontSubsetting SVGFontType SaveOptions UserInteractionLevel",
|
||||
),
|
||||
("", "AutoCADColors AutoCADCompatibility AutoCADExportFileFormat AutoCADExportOption AutoCADRasterFormat AutoCADUnit"),
|
||||
("AutoCADColors.", "Max16Colors Max256Colors Max8Colors TrueColors"),
|
||||
("AutoCADCompatibility.", "AutoCADRelease13 AutoCADRelease14 AutoCADRelease15 AutoCADRelease18 AutoCADRelease21 AutoCADRelease24"),
|
||||
("AutoCADExportFileFormat.", "DWG DXF"),
|
||||
("AutoCADExportOption.", "MaximizeEditability PreserveAppearance"),
|
||||
("AutoCADRasterFormat.", "JPEG PNG"),
|
||||
("AutoCADUnit.", "Centimeters Inches Millimeters Picas Pixels Points"),
|
||||
("ColorConversion.", "COLORCONVERSIONREPURPOSE COLORCONVERSIONTODEST None"),
|
||||
(
|
||||
"ColorDestination.",
|
||||
@@ -283,7 +327,7 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
),
|
||||
("EPSPostScriptLevelEnum.", "LEVEL2 LEVEL3"),
|
||||
("EPSPreview.", "BWTIFF COLORTIFF None TRANSPARENTCOLORTIFF"),
|
||||
("ExportType.", "AutoCAD FLASH GIF JPEG PNG24 PNG8 SVG TIFF"),
|
||||
("ExportType.", "AUTOCAD AutoCAD FLASH GIF JPEG PNG24 PNG8 SVG TIFF"),
|
||||
("PDFBoxType.", "PDFARTBOX PDFBLEEDBOX PDFBOUNDINGBOX PDFCROPBOX PDFMEDIABOX PDFTRIMBOX"),
|
||||
("PDFCompatibility.", "ACROBAT4 ACROBAT5 ACROBAT6 ACROBAT7 ACROBAT8"),
|
||||
("PDFOverprint.", "DISCARDPDFOVERPRINT PRESERVEPDFOVERPRINT"),
|
||||
@@ -514,11 +558,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 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.
|
||||
|
||||
@@ -152,7 +152,8 @@ fn slot(i: &Interp, o: ObjId, name: &str) -> JsResult<Value> {
|
||||
/// object made with `Object.create(File.prototype)` included.
|
||||
pub(crate) fn file_path(i: &Interp, id: ObjId) -> JsResult<Option<String>> {
|
||||
let Some(c) = &i.files else { return Ok(None) };
|
||||
if i.object(id)?.proto != Some(c.file_proto) {
|
||||
let o = i.object(id)?;
|
||||
if o.proto != Some(c.file_proto) {
|
||||
return Ok(None);
|
||||
}
|
||||
Ok(match own_path(i, id)? {
|
||||
|
||||
@@ -204,7 +204,8 @@ struct Reading {
|
||||
path: Vec<Step>,
|
||||
function: Rc<str>,
|
||||
/// Objects of host classes are read as [`crate::host_ref`] gives them, a `File` as its path under
|
||||
/// [`crate::FILE_REF_KEY`], and a plain object that has either key is refused.
|
||||
/// [`crate::FILE_REF_KEY`], and a plain object that has one of the keys, or
|
||||
/// [`crate::FOLDER_REF_KEY`], is refused.
|
||||
hosted: bool,
|
||||
}
|
||||
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -56,6 +56,9 @@ pub(crate) struct Known {
|
||||
/// A file gives names values the analysis doesn't read ([`Declared::unsure`]): no object counts
|
||||
/// as a Folder object whatever the path names.
|
||||
pub unsure: bool,
|
||||
/// The script includes another file ([`Declared::includes`]), whose code may give a file's
|
||||
/// variables values the scan of that file does not read.
|
||||
pub others: bool,
|
||||
}
|
||||
|
||||
impl Known {
|
||||
@@ -75,6 +78,7 @@ impl Known {
|
||||
/// object only when both sides say so; otherwise it may hold a File object.
|
||||
pub fn add(&mut self, other: Known, entries: usize) {
|
||||
self.unsure |= other.unsure;
|
||||
self.others |= other.others;
|
||||
for (name, chain) in other.bound {
|
||||
if self.bound.len() < entries || self.bound.contains_key(&name) {
|
||||
self.bound.entry(name).or_insert(chain);
|
||||
@@ -286,8 +290,8 @@ struct ObjectValue {
|
||||
/// key's whole value, a bit each ([`Analyzer::writers`]).
|
||||
bits: u8,
|
||||
/// It is the value of the first name a `var` statement declares, and the statement is directly
|
||||
/// in a function body or the global code, not in a block and not after `if (…)`, `else`, `do` or
|
||||
/// a loop's parentheses: only then does the variable hold `bits` after it.
|
||||
/// in a function body or the global code, not in a block and not after `if (…)`, `else`, `do`, a
|
||||
/// loop's parentheses or a label: only then does the variable hold `bits` after it.
|
||||
whole: bool,
|
||||
/// The bit of the method whose value is being read, and how far that value has been read.
|
||||
value: Option<(u8, Value)>,
|
||||
@@ -696,6 +700,8 @@ struct Analyzer<'s, 'a, 'l> {
|
||||
/// What the receiver before the last `[` read defines in [`Analyzer::writers`], 0 for a receiver
|
||||
/// that is not such a variable.
|
||||
index_receiver: u8,
|
||||
/// The script includes another file ([`Known::others`]): no variable joins [`Analyzer::writers`].
|
||||
others: bool,
|
||||
/// The variables that may get another value when code read elsewhere runs: assigned inside a
|
||||
/// function body that does not declare them, or as a property of `this` ([`Analyzer::reassigned_later`]).
|
||||
/// None of them joins [`Analyzer::writers`].
|
||||
@@ -783,6 +789,7 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
|
||||
objects: vec![],
|
||||
closed: None,
|
||||
index_receiver: 0,
|
||||
others: known.others || declared.includes,
|
||||
later: HashSet::new(),
|
||||
later_full: false,
|
||||
unsure: known.unsure || declared.unsure,
|
||||
@@ -1518,10 +1525,21 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
|
||||
/// The variable of the [`ObjectValue::whole`] literal whose `}` the token before `t` was joins
|
||||
/// [`Analyzer::writers`] when `t` ends the value (`;`, `,` or a line break). It is read before `t`
|
||||
/// closes a function body, so a literal given to the body's own variable stays inside the body.
|
||||
/// Calls inside a loop that assigns the variable use [`Declared::looped`] to classify its methods.
|
||||
/// No variable joins when code the scan does not follow at that point may give it another value:
|
||||
/// a function body that assigns its name ([`Declared::body_assigned`], [`Analyzer::later`]), a
|
||||
/// member assignment of a property of that name, which may be the global object's
|
||||
/// ([`Declared::rebound`]), a function body that assigns a `saveAs` or `exportFile` property of
|
||||
/// any object ([`Declared::body_writer_assigned`]), code given as text or a `with` statement
|
||||
/// ([`Analyzer::unsure`]), and an included file ([`Analyzer::others`]). Calls inside a loop that
|
||||
/// assigns the variable use [`Declared::looped`] to classify its methods.
|
||||
fn settle_literal(&mut self, t: &Sig<'s>) {
|
||||
if let Some((name, bits)) = self.closed.take()
|
||||
&& (t.is(";") || t.is(",") || (t.nl && !goes_on_with(t)))
|
||||
&& !self.unsure
|
||||
&& !self.others
|
||||
&& !self.declared.rebound.contains(&name)
|
||||
&& !self.declared.body_assigned.contains(name.as_str())
|
||||
&& !self.declared.body_writer_assigned
|
||||
&& !self.later_full
|
||||
&& !self.later.contains(&name)
|
||||
&& !self.declared.looped_full
|
||||
@@ -1855,7 +1873,13 @@ impl<'s, 'a, 'l> Analyzer<'s, 'a, 'l> {
|
||||
}
|
||||
// A variable that any assignment gave a value that may be a File object leaves as one.
|
||||
let folders = self.folders.iter().filter(|name| self.folder(name)).cloned().collect();
|
||||
let known = Known { bound: std::mem::take(&mut self.bound), files: std::mem::take(&mut self.files), folders, unsure: self.unsure };
|
||||
let known = Known {
|
||||
bound: std::mem::take(&mut self.bound),
|
||||
files: std::mem::take(&mut self.files),
|
||||
folders,
|
||||
unsure: self.unsure,
|
||||
others: self.others,
|
||||
};
|
||||
(std::mem::take(&mut self.includes), module, known)
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,10 @@
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
use super::{Acc, Brackets, Lexer, LineBreaks, Read, Sig, T, catalog, for_in, goes_on_after, goes_on_with, is, member_mark, unquote, word};
|
||||
use super::{
|
||||
Acc, Brackets, COMPOUND, Lexer, LineBreaks, Read, Sig, T, Token, catalog, directives, for_in, goes_on_after, goes_on_with, is, member_mark,
|
||||
unquote, word,
|
||||
};
|
||||
|
||||
/// The names that give variables values the analysis doesn't read: a `with` statement makes an
|
||||
/// object's properties stand for names in its body (ECMA-262 3rd edition, section 12.10), and `eval`,
|
||||
@@ -67,6 +70,19 @@ pub(crate) struct Declared<'s> {
|
||||
/// The property names a member assignment writes (`o.d = …`, `o['d'] = …`). The object may be
|
||||
/// the global object, so a variable of that name may get a value the analysis doesn't read.
|
||||
pub(super) rebound: HashSet<String>,
|
||||
/// The names a function body assigns by name (`d = …`, `d += …`, `d++`, `for (d in …)`) other than
|
||||
/// in a `var` statement's declarations, unless a body around the assignment declared the name with
|
||||
/// `var` before it. The function may run at any time after it is defined,
|
||||
/// also before its body in the text when it is a declaration, so a variable of that name may lose
|
||||
/// the value an assignment the analysis read gave it.
|
||||
pub(super) body_assigned: HashSet<&'s str>,
|
||||
/// A function body assigns a property named as one of [`catalog::DOM_FILE_WRITES`]
|
||||
/// (`o.saveAs = …`, `this['exportFile'] = …`). The function may run at any time after it is
|
||||
/// defined, and the object may be any variable's, so no variable's method of that name stays
|
||||
/// the script's own.
|
||||
pub(super) body_writer_assigned: bool,
|
||||
/// The file has an `#include` line: the included file's code may give its variables values.
|
||||
pub(super) includes: bool,
|
||||
/// The variables assigned inside a loop, its parentheses included (`name = …`), each by the
|
||||
/// offset of the `{` of the function body that declares it (`None`: the global code's), with the
|
||||
/// outermost loops that assign it, entries of `loop_spans`.
|
||||
@@ -197,7 +213,7 @@ pub(crate) fn declarations<'s>(src: &'s str, acc: &mut Acc) -> Declared<'s> {
|
||||
for t in lexer.by_ref() {
|
||||
match breaks.read(&t) {
|
||||
Read::Skip => {}
|
||||
Read::Directive => d.directive(),
|
||||
Read::Directive => d.directive(&t),
|
||||
Read::Token(sig) => d.token(sig),
|
||||
}
|
||||
}
|
||||
@@ -270,9 +286,43 @@ impl<'s> Declarations<'s, '_, '_> {
|
||||
if t.word("function") && !member_mark(h0) && !word(h0, "function") {
|
||||
self.function = Some(depth);
|
||||
}
|
||||
if !self.bodies.is_empty() || self.untracked.is_some() {
|
||||
self.body_assignment(&t, depth);
|
||||
}
|
||||
self.h = [Some(t), h0, h1];
|
||||
}
|
||||
|
||||
/// `t` inside a function body at bracket depth `depth`: the name it assigns, when it assigns one
|
||||
/// by name outside a `var` statement's declarations, joins [`Declared::body_assigned`].
|
||||
fn body_assignment(&mut self, t: &Sig<'s>, depth: usize) {
|
||||
let [h0, h1, _] = self.h;
|
||||
let name = |s: Option<Sig<'s>>| s.filter(|s| s.kind == T::Ident).map(|s| s.text);
|
||||
let declares = word(h1, "var") || (is(h1, ",") && self.var_depth == Some(depth));
|
||||
let assigned = if t.kind == T::Punct && (t.text == "=" || COMPOUND.contains(&t.text) || matches!(t.text, "++" | "--")) {
|
||||
// `d = …`, `d += …` and `d++`, not `o.d = …` (a member: [`Declared::rebound`]) or `var d = …`.
|
||||
name(h0).filter(|_| !member_mark(h1) && !(t.text == "=" && declares))
|
||||
} else if t.kind == T::Ident && (is(h0, "++") || is(h0, "--")) {
|
||||
// `++d`.
|
||||
Some(t.text)
|
||||
} else if t.word("in") && (is(h1, "(") || word(h1, "var")) {
|
||||
// `for (d in …)`.
|
||||
name(h0)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
// A name the innermost body around `t` has declared with `var` before it is that body's own. A
|
||||
// name only an outer body declared is that body's variable, which a nested function may assign
|
||||
// before a call in the outer body runs.
|
||||
let own = |name: &str| self.untracked.is_none() && self.bodies.last().is_some_and(|b| b.names.contains(name));
|
||||
if let Some(name) = assigned.filter(|n| !own(n)) {
|
||||
if self.out.body_assigned.contains(name) || self.acc.room(self.out.body_assigned.len()) {
|
||||
self.out.body_assigned.insert(name);
|
||||
} else {
|
||||
self.out.unsure = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `t`, a token before the brackets are followed past it: the body of the innermost loop starts
|
||||
/// at it, and `for`, `while` and `do` start a loop. Past [`crate::Limits::nesting`] loops, any
|
||||
/// variable may be assigned in one ([`Declared::looped_full`]).
|
||||
@@ -507,6 +557,9 @@ impl<'s> Declarations<'s, '_, '_> {
|
||||
None
|
||||
};
|
||||
if let Some(name) = property {
|
||||
if (!self.bodies.is_empty() || self.untracked.is_some()) && catalog::DOM_FILE_WRITES.contains(&name.as_str()) {
|
||||
self.out.body_writer_assigned = true;
|
||||
}
|
||||
if self.out.rebound.contains(&name) || self.acc.room(self.out.rebound.len()) {
|
||||
self.out.rebound.insert(name);
|
||||
} else {
|
||||
@@ -613,7 +666,10 @@ impl<'s> Declarations<'s, '_, '_> {
|
||||
/// A preprocessor line ends the statement before it, as in [`Analyzer::directive`]. Inside a
|
||||
/// property's name in brackets it hides the tokens before the name (`this[`, a line, `'eval']`),
|
||||
/// so the name may be any.
|
||||
fn directive(&mut self) {
|
||||
fn directive(&mut self, t: &Token<'s>) {
|
||||
if directives::parse(t.text).known == Some("include") {
|
||||
self.out.includes = true;
|
||||
}
|
||||
if self.keys.iter().any(|k| k.member) {
|
||||
self.out.unsure = true;
|
||||
}
|
||||
|
||||
@@ -868,7 +868,8 @@ fn try_clauses_and_else_after_a_nested_do_loop_are_in_the_loop() {
|
||||
|
||||
/// A literal after a label's line break may not run, a `this` assignment in a function whose own
|
||||
/// variable hides the global one changes the global, and a property `d` of another object is not
|
||||
/// the variable `d`.
|
||||
/// the variable `d`. A member assignment of a property `g` (`holder.this.g = …`) may be the global
|
||||
/// object's, so `g.saveAs` writes a file.
|
||||
#[test]
|
||||
fn labels_hidden_globals_and_other_objects_keep_writes_known() {
|
||||
let r = report(concat!(
|
||||
@@ -893,7 +894,7 @@ fn labels_hidden_globals_and_other_objects_keep_writes_known() {
|
||||
"function other() { var g; holder.this.g = app.activeDocument; holder.this['g'] = 1; }\n",
|
||||
"other(); g.saveAs(f);\n",
|
||||
));
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[5, 8, 17][..]));
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[5, 8, 17, 20][..]));
|
||||
}
|
||||
|
||||
/// Only a `var` statement directly in a function body or the global code that gives its first name
|
||||
@@ -925,6 +926,61 @@ fn only_a_whole_var_value_makes_save_as_the_scripts_own() {
|
||||
assert_eq!(feature(&r, "file.write").map(|f| f.lines.as_slice()), Some(&[4, 7, 9, 11, 13, 14, 17][..]));
|
||||
}
|
||||
|
||||
/// A literal's `saveAs` stays the script's own only while no code the check does not follow may give
|
||||
/// the variable another value: a declaration after a label, which `if` may skip, a function body that
|
||||
/// assigns the variable (its own method's, or a declaration's that runs before its text), a member
|
||||
/// assignment of a property of that name, which may be the global object's, a function body that
|
||||
/// assigns a `saveAs` or `exportFile` property of any object, code given as text, a `with` statement
|
||||
/// and an included file each leave the write reported. A function that declares its own variable of the
|
||||
/// name, or assigns another property of it, leaves it the script's own. A nested function that assigns
|
||||
/// a variable its enclosing body declared leaves the write reported too.
|
||||
#[test]
|
||||
fn a_save_as_other_code_may_replace_writes_a_file() {
|
||||
let cases: [(&str, &[usize]); 16] = [
|
||||
("var f = new File(p);\nvar d = app.activeDocument;\nif (flag) label:\nvar d = {saveAs: function () {}};\nd.saveAs(f);\n", &[5]),
|
||||
(
|
||||
"var f = new File(p);\nvar d = {\n saveAs: function () {},\n useDocument: function () {\n d = null;\n d = app.activeDocument;\n }\n};\nd.useDocument();\nd.saveAs(f);\n",
|
||||
&[10],
|
||||
),
|
||||
("var f = new File(p);\nvar d = {saveAs: function () {}};\nswap();\nd.saveAs(f);\nfunction swap() { d = app.activeDocument; }\n", &[4]),
|
||||
("var f = new File(p);\nvar d = {saveAs: function () {}};\nthis.d = app.activeDocument;\nd.saveAs(f);\n", &[4]),
|
||||
("var f = new File(p);\nvar d = {saveAs: function () {}};\neval(s);\nd.saveAs(f);\n", &[4]),
|
||||
("#include \"other.jsx\"\nvar f = new File(p);\nvar d = {saveAs: function () {}};\nd.saveAs(f);\n", &[4]),
|
||||
("var f = new File(p);\nvar d = {saveAs: function () {}};\n#include \"other.jsx\"\nd.saveAs(f);\n", &[4]),
|
||||
("var f = new File(p);\nvar d = {saveAs: function () {}};\nwith ({d: app.activeDocument}) {\n d.saveAs(f);\n}\n", &[4]),
|
||||
(
|
||||
"var f = new File(p);\nfunction replace() { d.saveAs = app.activeDocument.saveAs; }\nvar d = {saveAs: function () {}};\nreplace();\nd.saveAs(f);\n",
|
||||
&[5],
|
||||
),
|
||||
(
|
||||
"var f = new File(p);\nfunction replace(o) { o['exportFile'] = w; }\nvar d = {exportFile: function () {}};\nreplace(d);\nd.exportFile(f);\n",
|
||||
&[5],
|
||||
),
|
||||
("var f = new File(p);\nfunction note() { d.n = 1; }\nvar d = {saveAs: function () {}};\nnote();\nd.saveAs(f);\n", &[]),
|
||||
("var f = new File(p);\nvar d = {saveAs: function () {}};\nfunction g() { var d = app.activeDocument; d = 1; }\nd.saveAs(f);\n", &[]),
|
||||
(
|
||||
"var f = new File(p);\nfunction run() {\n var d = {saveAs: function () {}};\n swap();\n d.saveAs(f);\n function swap() { d = app.activeDocument; }\n}\nrun();\n",
|
||||
&[5],
|
||||
),
|
||||
(
|
||||
"var f = new File(p);\nfunction run() {\n var d = {saveAs: function () {}};\n swap();\n d.saveAs(f);\n function swap() { d += 1; }\n}\n",
|
||||
&[5],
|
||||
),
|
||||
(
|
||||
"var f = new File(p);\nfunction run() {\n var d = {saveAs: function () {}};\n swap();\n d.saveAs(f);\n function swap() { d++; }\n}\n",
|
||||
&[5],
|
||||
),
|
||||
(
|
||||
"var f = new File(p);\nfunction run() {\n var d = {saveAs: function () {}};\n swap();\n d.saveAs(f);\n function swap() { for (d in o) {} }\n}\n",
|
||||
&[5],
|
||||
),
|
||||
];
|
||||
for (src, lines) in cases {
|
||||
let r = report(src);
|
||||
assert_eq!(feature(&r, "file.write").map_or(&[][..], |f| f.lines.as_slice()), lines, "{src}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn writer_calls_after_many_assignment_loops_have_bounded_work() {
|
||||
for reinitialize in [false, true] {
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -301,6 +301,28 @@ pub(crate) fn column_of<'a>(layout: &'a Layout<String>, panel: &str) -> Option<(
|
||||
Some((edge, column))
|
||||
}
|
||||
|
||||
/// Where the dock last drew the docked column holding `panel`; none until the dock has drawn it, and while `panel`
|
||||
/// floats or is closed.
|
||||
pub(crate) fn column_rect(app: &VectorcraftApp, panel: &str) -> Option<egui::Rect> {
|
||||
let (Some(_), column) = column_of(layout_of(&app.ui), panel)? else { return None };
|
||||
app.dock_rt.columns.iter().find(|(first, _)| column.panels().any(|p| p == first)).map(|(_, rect)| *rect)
|
||||
}
|
||||
|
||||
/// The top left a new floating window of `panel` takes beside the docked column holding `beside`: level with the
|
||||
/// column's top, the cascade inset away from it on the side toward the middle of the float space. None until the dock
|
||||
/// has drawn that column.
|
||||
pub(crate) fn float_origin_beside(app: &VectorcraftApp, panel: &str, beside: &str) -> Option<egui::Pos2> {
|
||||
let column = column_rect(app, beside)?;
|
||||
let space = command_space(app);
|
||||
let x = if column.center().x <= space.area.center().x {
|
||||
column.right() + space.inset
|
||||
} else {
|
||||
let width = space.size_of(&DragUnit::Panel(panel.to_owned()), None).x;
|
||||
column.left() - space.inset - width
|
||||
};
|
||||
Some(egui::pos2(x, column.top()))
|
||||
}
|
||||
|
||||
/// Is the dock's outer column of panels (Properties · Layers · Libraries) collapsed to icons?
|
||||
pub(crate) fn dock_collapsed(ui: &UiState) -> bool {
|
||||
dock_columns(layout_of(ui)).first().is_some_and(|c| c.iconic)
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -62,6 +62,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) => {
|
||||
@@ -90,6 +91,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.
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -146,7 +146,8 @@ pub fn root_theme(prefs: &Prefs) -> (ThemeId, ModeChoice, Option<Rgba>) {
|
||||
}
|
||||
|
||||
/// The app's sizes over the framework's size sets (`sizes.json`): push buttons have the app's 4-point corners
|
||||
/// where the sets give pills, the Home title is 26-point with a 36-point call to action, 28-point New and Open with 16
|
||||
/// where the sets give pills, the Home title is 24-point on a 29-point line (its nominal 26 points on 32 at the 92%
|
||||
/// the body type below is set at) with a 36-point call to action, 28-point New and Open with 16
|
||||
/// points beside their labels and 24-point link rows. Home's margin and the gaps between its title, actions, sections,
|
||||
/// headings and links are the framework's page tokens, which follow its spacing scale (`space.gap.*`). The compact set
|
||||
/// takes the reference app's metrics:
|
||||
@@ -159,8 +160,8 @@ pub fn root_theme(prefs: &Prefs) -> (ThemeId, ModeChoice, Option<Rgba>) {
|
||||
const SIZES: &[u8] = br#"{
|
||||
"all": {
|
||||
"radius.button": 4,
|
||||
"typography.display.size": 26,
|
||||
"typography.display.line_height": 32,
|
||||
"typography.display.size": 24,
|
||||
"typography.display.line_height": 29,
|
||||
"size.page.action": 36,
|
||||
"size.page.button": 28,
|
||||
"size.page.button_side": 16,
|
||||
@@ -236,6 +237,37 @@ mod tests {
|
||||
assert!(AppSizes::parse(SIZES).is_ok_and(|sizes| !sizes.is_empty()));
|
||||
}
|
||||
|
||||
/// The Home title (the display type) is set at the same scale as the compact body type, so it keeps the nominal
|
||||
/// 26-point title over a 13-point body proportion, and its line keeps the framework's display line proportion.
|
||||
#[test]
|
||||
fn the_home_title_is_scaled_with_the_body_type() {
|
||||
use craft::theme::Size;
|
||||
use craft::ui::runtime::env::{Env, RootEnv};
|
||||
use craft::ui::testing::Fixture;
|
||||
use std::cell::Cell;
|
||||
use std::rc::Rc;
|
||||
const NOMINAL_TITLE_OVER_BODY: f32 = 26.0 / 13.0;
|
||||
let typography = |sizes: Arc<AppSizes>| {
|
||||
let seen = Rc::new(Cell::new(None));
|
||||
let seen_in = Rc::clone(&seen);
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let t = Env::of(ui).tokens.tokens().typography;
|
||||
seen_in.set(Some((t.display, t.body)));
|
||||
});
|
||||
let mut root = RootEnv::new().density(Size::Compact);
|
||||
root.sizes = sizes;
|
||||
fixture.root(root);
|
||||
fixture.frame(vec![]);
|
||||
seen.get().expect("the fixture drew a frame")
|
||||
};
|
||||
let (display, body) = typography(app_sizes());
|
||||
let ratio = display.size / body.size;
|
||||
assert!((ratio - NOMINAL_TITLE_OVER_BODY).abs() < 0.05, "a {}-point title over a {}-point body", display.size, body.size);
|
||||
let (framework, _) = typography(Arc::new(AppSizes::default()));
|
||||
let (line, framework_line) = (display.line_height / display.size, framework.line_height / framework.size);
|
||||
assert!((line - framework_line).abs() < 0.05, "a {}-point line for a {}-point title", display.line_height, display.size);
|
||||
}
|
||||
|
||||
/// Home's margin and gaps are the framework's page tokens: no size set gives them points of its own, so they follow
|
||||
/// the framework's spacing scale.
|
||||
#[test]
|
||||
|
||||
@@ -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};
|
||||
@@ -294,11 +294,17 @@ pub(crate) fn is_floating(app: &VectorcraftApp, toolbar: Option<&str>, key: &str
|
||||
strips(app, toolbar).iter().any(|g| g.first() == Some(&key))
|
||||
}
|
||||
|
||||
/// Float the group `first` of `owner` as a strip at `at` (none: the canvas's corner).
|
||||
/// Float the group `first` of `owner` as a strip at `at`. Without `at` the strip opens at the canvas's corner, or,
|
||||
/// before a view has been laid out, beside `owner`'s docked rail, else beside the Tools panel's.
|
||||
fn place_strip(app: &mut VectorcraftApp, owner: &Owner, first: &str, at: Option<Pos2>) -> Result<(), String> {
|
||||
let at = at.unwrap_or_else(|| app.canvas_view().map_or(Pos2::ZERO, |v| v.rect.min));
|
||||
let id = strip_id(owner, first);
|
||||
let at = at
|
||||
.or_else(|| app.canvas_view().map(|v| v.rect.min))
|
||||
.or_else(|| crate::panel_docking::float_origin_beside(app, &id, &owner.panel()))
|
||||
.or_else(|| crate::panel_docking::float_origin_beside(app, &id, TOOLS))
|
||||
.unwrap_or(Pos2::ZERO);
|
||||
// A width of 0 leaves the window's width to the panel's grid.
|
||||
crate::panel_docking::place_floating(app, &strip_id(owner, first), at, 0.0)
|
||||
crate::panel_docking::place_floating(app, &id, at, 0.0)
|
||||
}
|
||||
|
||||
/// Float the toolbar group (of the current layout) holding `tool` as a strip of tool buttons, put
|
||||
@@ -893,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"))
|
||||
@@ -913,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
|
||||
}
|
||||
|
||||
|
||||
@@ -483,6 +483,30 @@ fn window_float_tools_floats_and_puts_back_a_group() {
|
||||
assert!(strip_rect(&app, "rectangle").is_none() && !is_floating(&app, None, "pen"));
|
||||
}
|
||||
|
||||
/// `window.floatTools` run before a view has been laid out (right after a document opens, or with none open) floats the
|
||||
/// strip beside the docked Tools rail, not over it, and the strip stays clear of the rail once the frames are drawn.
|
||||
#[test]
|
||||
fn a_strip_floated_before_a_view_is_laid_out_opens_beside_the_tools_rail() {
|
||||
for (case, document) in [("document just opened", true), ("no document", false)] {
|
||||
let mut app = VectorcraftApp::new(Session::new(), Default::default());
|
||||
let ctx = crate::testing::ui_context();
|
||||
settled(&mut app, &ctx, 0.0, 900.0);
|
||||
if document {
|
||||
app.run("file.new", json!({"width": 300, "height": 300})).unwrap();
|
||||
}
|
||||
assert!(app.canvas_view().is_none(), "{case}: no view has been laid out yet");
|
||||
let rail = crate::panel_docking::column_rect(&app, TOOLS).unwrap_or_else(|| panic!("{case}: the Tools rail is docked"));
|
||||
app.run("window.floatTools", json!({"tool": "pen"})).unwrap();
|
||||
let strip = strip_rect(&app, "pen").unwrap_or_else(|| panic!("{case}: the Pen strip floats"));
|
||||
assert!(strip.left() >= rail.right(), "{case}: the strip {strip:?} opens right of the rail {rail:?}");
|
||||
assert!((strip.top() - rail.top()).abs() <= f32::EPSILON, "{case}: the strip {strip:?} is level with the rail {rail:?}");
|
||||
settled(&mut app, &ctx, 1.0, 900.0);
|
||||
let rail = crate::panel_docking::column_rect(&app, TOOLS).unwrap_or_else(|| panic!("{case}: the Tools rail stays docked"));
|
||||
let strip = strip_rect(&app, "pen").unwrap_or_else(|| panic!("{case}: the Pen strip still floats"));
|
||||
assert!(!strip.intersects(rail), "{case}: the strip {strip:?} is clear of the rail {rail:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A floated group is a panel of the workspace's layout: a saved workspace brings it back, the built-in ones have none.
|
||||
#[test]
|
||||
fn workspaces_keep_floating_flyouts_and_reset_puts_them_back() {
|
||||
@@ -703,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());
|
||||
@@ -744,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();
|
||||
|
||||
@@ -64,6 +64,10 @@ pub struct WorkspaceRecord {
|
||||
/// Tabs closed together by a panel shortcut.
|
||||
#[serde(skip_serializing_if = "Vec::is_empty")]
|
||||
pub docking_hidden_groups: Vec<Vec<String>>,
|
||||
/// The panel open from a column collapsed to icons (built-in workspaces: the panel the
|
||||
/// workspace is for; workspaces saved without this field: none).
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub open_panel: Option<String>,
|
||||
/// The tool each flyout group of the main Tools shows (built-in workspaces: the first).
|
||||
pub tools_last_used: LastUsed<String>,
|
||||
/// The toolbars made with New Toolbar in this workspace (built-in workspaces: none).
|
||||
@@ -87,6 +91,7 @@ impl Default for WorkspaceRecord {
|
||||
status_bar: true,
|
||||
help_bar: true,
|
||||
docking_hidden_groups: Vec::new(),
|
||||
open_panel: None,
|
||||
tools_last_used: LastUsed::default(),
|
||||
toolbars: Vec::new(),
|
||||
}
|
||||
@@ -245,25 +250,30 @@ pub fn builtins() -> Vec<Builtin> {
|
||||
x.rulers = true;
|
||||
x.toolbar_advanced = true;
|
||||
x.task_bar = false;
|
||||
x.open_panel = Some("color".into());
|
||||
}),
|
||||
w("Automation", &["layers", "actions"], &|x| {
|
||||
x.control_bar = true;
|
||||
x.toolbar_advanced = true;
|
||||
x.open_panel = Some("actions".into());
|
||||
}),
|
||||
w("Layout", &["layers", "align"], &|x| {
|
||||
x.control_bar = true;
|
||||
x.rulers = true;
|
||||
x.toolbar_advanced = true;
|
||||
x.open_panel = Some("align".into());
|
||||
}),
|
||||
w("Painting", &["brushes"], &|x| {
|
||||
x.control_bar = true;
|
||||
x.toolbar_advanced = true;
|
||||
x.open_panel = Some("brushes".into());
|
||||
})
|
||||
.double_tools(),
|
||||
w("Printing and Proofing", &["info"], &|x| {
|
||||
x.control_bar = true;
|
||||
x.rulers = true;
|
||||
x.toolbar_advanced = true;
|
||||
x.open_panel = Some("info".into());
|
||||
}),
|
||||
w("Tracing", &["layers"], &|x| {
|
||||
x.control_bar = true;
|
||||
@@ -274,16 +284,19 @@ pub fn builtins() -> Vec<Builtin> {
|
||||
x.control_bar = true;
|
||||
x.rulers = true;
|
||||
x.toolbar_advanced = true;
|
||||
x.open_panel = Some("character".into());
|
||||
}),
|
||||
w("Web", &["symbols"], &|x| {
|
||||
x.control_bar = true;
|
||||
x.rulers = true;
|
||||
x.toolbar_advanced = true;
|
||||
x.open_panel = Some("symbols".into());
|
||||
}),
|
||||
w(TOUCH, &["align"], &|x| {
|
||||
x.control_bar = true;
|
||||
x.toolbar_advanced = true;
|
||||
x.task_bar = true;
|
||||
x.open_panel = Some("align".into());
|
||||
}),
|
||||
]
|
||||
}
|
||||
@@ -387,6 +400,7 @@ pub fn record(ui: &UiState) -> WorkspaceRecord {
|
||||
status_bar: ui.status_bar,
|
||||
help_bar: ui.help_bar,
|
||||
docking_hidden_groups: ui.docking_hidden_groups.clone(),
|
||||
open_panel: ui.open_panel.clone(),
|
||||
tools_last_used: ui.tools_last_used.clone(),
|
||||
toolbars: ui.custom_toolbars.clone(),
|
||||
}
|
||||
@@ -412,6 +426,7 @@ fn apply_record(ui: &mut UiState, w: &WorkspaceRecord) {
|
||||
ui.status_bar = w.status_bar;
|
||||
ui.help_bar = w.help_bar;
|
||||
ui.docking_hidden_groups = w.docking_hidden_groups.clone();
|
||||
ui.open_panel = w.open_panel.clone();
|
||||
ui.tools_last_used = w.tools_last_used.clone();
|
||||
ui.custom_toolbars = w.toolbars.clone();
|
||||
crate::custom_toolbars::sanitize(&mut ui.custom_toolbars);
|
||||
@@ -450,10 +465,19 @@ pub fn switch(app: &mut VectorcraftApp, key: &str) -> Result<String, String> {
|
||||
let w = ui.workspaces.edited.get(&id).cloned().unwrap_or_else(|| saved_record(&ui.workspaces, &id));
|
||||
apply_record(ui, &w);
|
||||
crate::panel_docking::reconcile(&mut ui.dock_workspace);
|
||||
close_stale_flyout(ui);
|
||||
crate::panel_docking::show_panels(app);
|
||||
Ok(name)
|
||||
}
|
||||
|
||||
/// Close the open panel when the layout now in use does not show it from a column collapsed to
|
||||
/// icons (it was moved, expanded or closed).
|
||||
fn close_stale_flyout(ui: &mut UiState) {
|
||||
if ui.open_panel.as_ref().is_some_and(|panel| !crate::panel_docking::layout_of(ui).opens_in_flyout(panel)) {
|
||||
ui.open_panel = None;
|
||||
}
|
||||
}
|
||||
|
||||
/// Reset the current workspace to the way it was saved, dropping its changes.
|
||||
pub fn reset(app: &mut VectorcraftApp) -> String {
|
||||
let ui = &mut app.ui;
|
||||
@@ -467,6 +491,7 @@ pub fn reset(app: &mut VectorcraftApp) -> String {
|
||||
apply_record(ui, &w);
|
||||
ui.custom_toolbars = toolbars;
|
||||
crate::panel_docking::reconcile(&mut ui.dock_workspace);
|
||||
close_stale_flyout(ui);
|
||||
crate::panel_docking::show_panels(app);
|
||||
current_name(&app.ui).to_string()
|
||||
}
|
||||
@@ -715,12 +740,64 @@ mod tests {
|
||||
switch(&mut app, "Essentials Classic").unwrap();
|
||||
assert!(app.ui.control_bar && app.ui.view.rulers && app.ui.toolbar_advanced);
|
||||
assert!(front(&app.ui, "color"));
|
||||
assert_eq!(app.ui.open_panel.as_deref(), Some("color"));
|
||||
assert_eq!(current_name(&app.ui), "Essentials Classic");
|
||||
switch(&mut app, "essentials").unwrap();
|
||||
assert!(!app.ui.control_bar && !app.ui.view.rulers);
|
||||
assert_eq!(app.ui.open_panel, None);
|
||||
assert_eq!(app.ui.brightness, crate::theme::Brightness::Light);
|
||||
}
|
||||
|
||||
/// A built-in workspace shows the panel it is for, from its collapsed column too: the second
|
||||
/// panel it brings forward (Automation's Actions) as well as the only one (Painting's
|
||||
/// Brushes). A panel closed there stays closed when the workspace is left and switched back
|
||||
/// to, and Reset opens it again.
|
||||
#[test]
|
||||
fn builtin_workspaces_show_their_panel_after_switch_and_reset() {
|
||||
let showing = crate::panel_docking::showing;
|
||||
let mut app = app();
|
||||
for (name, panel) in [("Painting", "brushes"), ("Automation", "actions"), ("Essentials Classic", "color")] {
|
||||
switch(&mut app, name).unwrap();
|
||||
assert!(showing(&app.ui, panel), "{name} shows {panel}");
|
||||
}
|
||||
assert!(crate::panel_docking::layout_of(&app.ui).opens_in_flyout(&"color".to_string()), "Classic's Color opens from its icon");
|
||||
app.ui.open_panel = None;
|
||||
switch(&mut app, ESSENTIALS).unwrap();
|
||||
assert!(!showing(&app.ui, "color"), "Essentials opens no panel");
|
||||
switch(&mut app, "Essentials Classic").unwrap();
|
||||
assert!(!showing(&app.ui, "color"), "Classic comes back as it was left");
|
||||
reset(&mut app);
|
||||
assert!(showing(&app.ui, "color"), "Reset Essentials Classic shows Color again");
|
||||
}
|
||||
|
||||
/// A saved workspace keeps the panel open from its icons, through the preferences' JSON too; a
|
||||
/// workspace saved without that field opens none, and one naming a panel its layout does not
|
||||
/// show from icons opens none either.
|
||||
#[test]
|
||||
fn saved_workspaces_restore_the_open_panel() {
|
||||
let mut app = app();
|
||||
switch(&mut app, "Essentials Classic").unwrap();
|
||||
save_as(&mut app.ui, "Colors").unwrap();
|
||||
switch(&mut app, ESSENTIALS).unwrap();
|
||||
assert_eq!(app.ui.open_panel, None);
|
||||
switch(&mut app, "Colors").unwrap();
|
||||
assert_eq!(app.ui.open_panel.as_deref(), Some("color"));
|
||||
let id = id_of(&app.ui, "Colors");
|
||||
let back: UiState = serde_json::from_value(serde_json::to_value(&app.ui).unwrap()).unwrap();
|
||||
assert_eq!(back.workspaces.records[&id].open_panel.as_deref(), Some("color"));
|
||||
let mut old = serde_json::to_value(&back.workspaces.records[&id]).unwrap();
|
||||
assert!(old.as_object_mut().unwrap().remove("openPanel").is_some());
|
||||
let old: WorkspaceRecord = serde_json::from_value(old).unwrap();
|
||||
assert_eq!(old.open_panel, None);
|
||||
switch(&mut app, ESSENTIALS).unwrap();
|
||||
app.ui.workspaces.edited.get_mut(&id).unwrap().open_panel = Some("no-such-panel".into());
|
||||
switch(&mut app, "Colors").unwrap();
|
||||
assert_eq!(app.ui.open_panel, None, "switching opens no panel the layout's icons lack");
|
||||
app.ui.workspaces.records.get_mut(&id).unwrap().open_panel = Some("no-such-panel".into());
|
||||
reset(&mut app);
|
||||
assert_eq!(app.ui.open_panel, None, "Reset opens no panel the layout's icons lack");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn save_apply_round_trip() {
|
||||
let mut app = app();
|
||||
|
||||
+7
-5
@@ -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`.
|
||||
|
||||
+135
-22
@@ -3133,9 +3133,9 @@ 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
|
||||
@@ -3215,10 +3215,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`
|
||||
@@ -3228,7 +3230,12 @@ 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`
|
||||
@@ -3248,7 +3255,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
|
||||
@@ -3258,6 +3265,86 @@ 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`. `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` and `artboard.reorder`, returns nothing;
|
||||
read `artboards[index]` afterward), `remove(index)` (runs
|
||||
`artboard.delete`), `getActiveArtboardIndex()` and `setActiveArtboardIndex(index)`. An `Artboard`
|
||||
(https://ai-scripting.docsforadobe.dev/jsobjref/Artboard/) has `typename`, `parent`, `artboardRect`, `name`,
|
||||
`rulerOrigin`, `rulerPAR` (0.1 to 10), `showCenter`, `showCrossHairs`, `showSafeAreas` and `remove()`; its
|
||||
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. 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.
|
||||
- `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.
|
||||
- `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`.
|
||||
@@ -3278,7 +3365,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
|
||||
@@ -3287,7 +3375,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
|
||||
@@ -3322,7 +3412,20 @@ through `$`:
|
||||
with `antiAliasing`, `artBoardClipping`, `horizontalScale` and `verticalScale` (the same value, from 1 to
|
||||
776.19; 100 writes one pixel per point whatever the raster effects resolution) for PNG24 and JPEG, `matteColor` (PNG24 and JPEG; only white, an `RGBColor` of 255, 255, 255, is accepted, and another color is an error), `transparency` (PNG24), `qualitySetting` (0 to 100) and `optimization` (JPEG), and
|
||||
`coordinatePrecision` (1 to 7), `embedRasterImages`, `compressed`, `preserveEditability` and
|
||||
`includeVariablesAndDatasets` (SVG); `PNG8`, `GIF` and `TIFF` take no options. `app.open`'s
|
||||
`includeVariablesAndDatasets` (SVG); `PNG8`, `GIF` and `TIFF` take no options. `AutoCAD` (also written
|
||||
`ExportType.AUTOCAD`) takes `new ExportOptionsAutoCAD()` (https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsAutoCAD/)
|
||||
and writes a DXF file, as `document.export {format: dxf}` does, with `exportFileFormat`, `version`
|
||||
(`AutoCADRelease13`, `14`, `15`, `18`, `21` and `24` as the R13, R14, 2000, 2004, 2007 and 2010 formats), `unit`,
|
||||
`unitScaleRatio` (the drawing units for one `unit`, more than 0 and at most 1000), `colors`, `rasterFormat`,
|
||||
`exportOption`, `alterPathsForAppearance`, `convertTextToOutlines`, `exportSelectedArtOnly` and `scaleLineweights`.
|
||||
An option the object leaves out takes its help page's default; `colors`, `rasterFormat`, `unit` and
|
||||
`unitScaleRatio`, which have none there, default to true colors, PNG, millimeters and 1, VectorCraft's own values.
|
||||
`AutoCADRelease13`, `14` and `15` hold no true color: with them `colors` defaults to `Max256Colors`, and
|
||||
`AutoCADColors.TrueColors` throws an error.
|
||||
`AutoCADExportFileFormat.DWG`, the help page's default, throws an error that says DWG is not available, so an
|
||||
AutoCAD export sets `exportFileFormat` to `AutoCADExportFileFormat.DXF`. The enumerations `AutoCADColors`,
|
||||
`AutoCADCompatibility`, `AutoCADExportFileFormat`, `AutoCADExportOption`, `AutoCADRasterFormat` and `AutoCADUnit`
|
||||
hold the members the scripting constants page lists. `app.open`'s
|
||||
`options` is a `PDFFileOptions` record (https://ai-scripting.docsforadobe.dev/jsobjref/PDFFileOptions/) with
|
||||
`pageToOpen` and `pDFCropToBox`. These options require PDF content, including PDF-compatible `.ai` and `.ait` files.
|
||||
`app.open` rejects a file over 128 MiB before reading it.
|
||||
@@ -3345,12 +3448,13 @@ through `$`:
|
||||
files a command reads or writes besides the one named, such as an SVG's linked files, are
|
||||
read and written only where the script's folders allow. `userInteractionLevel` does not change what a command
|
||||
does or where it may read and write, since a command a script runs never shows a dialog. `exportFile` adds the
|
||||
format's extension unless the name already ends with it (`.jpg` or `.jpeg`, `.tif` or `.tiff`, `.svgz` with
|
||||
format's extension unless the name already ends with it (`.jpg` or `.jpeg`, `.tif` or `.tiff`, `.dxf`, `.svgz` with
|
||||
`compressed`), and writes one file: the active artboard with `artBoardClipping`, otherwise the bounds of the
|
||||
visible art. An SVG with `embedRasterImages` false also writes the document's embedded images beside it, and
|
||||
when the script's folders refuse one of those files, none of them is written; a write that fails once the
|
||||
visible art. An SVG with `embedRasterImages` false also writes the document's embedded images beside it, and a
|
||||
DXF of a drawing with placed raster images writes each image it exports beside it as a PNG file, or a JPEG
|
||||
file with `rasterFormat` `AutoCADRasterFormat.JPEG`; those files must travel with the DXF. When the script's folders refuse one of those files, none of them is written; a write that fails once the
|
||||
first file is in place leaves the files written before it. A listed option that is not mapped is accepted at its help page's default, and any other value throws
|
||||
an error that says it is not available yet, as do `ExportType.FLASH` and `ExportType.AutoCAD`. A property the help
|
||||
an error that says it is not available yet, as does `ExportType.FLASH`. A property the help
|
||||
pages do not list throws an error that names it (`PDFFileOptions` also accepts its read-only `typename` and
|
||||
`parent`), and an `undefined` one is left out. With `pDFPreset` named, a `PDFSaveOptions` option still at a new object's default
|
||||
keeps the preset's value. A `pDFPreset` in square brackets, such as `[Smallest File Size]`, names the built-in
|
||||
@@ -3363,7 +3467,8 @@ through `$`:
|
||||
writes only the file at the path, holding that artboard. Without `saveMultipleArtboards`, a `.ai` or EPS
|
||||
`artboardRange` is not checked against the document's artboards, but one that is not written as a range of
|
||||
artboard numbers (such as `abc` or `0-`) throws. `Document.path` is a `Folder` for the folder of the document's
|
||||
file. A document that has no file has a `fullName` of a `File` for its name in `Folder.current` and a `path` of
|
||||
file. A relative path that a file is saved or opened under is resolved against the working folder of the process that wrote or read it,
|
||||
for `fullName`, `path` and `close` alike. A document that has no file has a `fullName` of a `File` for its name in `Folder.current` and a `path` of
|
||||
`""`. `fullName` and `path` of a document whose file the automation read roots do not allow throw
|
||||
`Script file access denied`. Changing `saved` runs `document.setSaved`: `true` records the document as saved
|
||||
without saving it, so `close()` then closes it, and `false` records it as having unsaved changes; neither adds an
|
||||
@@ -3403,8 +3508,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()`
|
||||
@@ -3770,9 +3876,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
|
||||
@@ -4953,6 +5063,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
|
||||
@@ -8238,7 +8349,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,
|
||||
@@ -11081,7 +11193,8 @@ that category), `name`, `width`/`height`
|
||||
rows, spacing, rightToLeft}` (`artboards`, `columns` and `rows` are whole numbers from 1 to 1000, and any other number is an error; `rows` gives a `gridByColumn` layout that many rows, at most one for each artboard, in place of `columns`, and is
|
||||
an error with another layout; a preset keeps the rows, and `file.newPresets` lists them as set even when there are
|
||||
fewer artboards, until `columns` without `rows`, or another layout, is given; New Document's Columns shows the columns
|
||||
the rows give the current number of artboards, and New Document drops the rows when Columns or the layout changes),
|
||||
the rows give the current number of artboards, and New Document drops the rows when Columns or the layout changes;
|
||||
with neither `columns` nor `rows` set, Columns shows the columns `file.new` lays out: one row of all the artboards in a grid),
|
||||
`bleed`, `backgroundContents`, `colorMode`, `rasterEffectsPpi` (1 to 2,400; a saved preset's
|
||||
value outside that range is read as the nearer end), `previewMode` and `alignNewObjectsToPixelGrid` (see
|
||||
[Align New Objects to Pixel Grid](#align-new-objects-to-pixel-grid)).
|
||||
|
||||
+1
-1
@@ -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.
|
||||
|
||||
|
||||
@@ -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,7 +1115,7 @@ 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: `app.preferences` reads, stores and removes values by key with the type they were set as, keeps them across runs and restarts, and turns the warning before a picked script on with the key `ShowExternalJSXWarning`, and off only after the person answers Yes to a confirm (https://ai-scripting.docsforadobe.dev/jsobjref/Preferences/; the confirm is VectorCraft's own rule); `app` makes, joins, inverts and compares `Matrix` records (https://ai-scripting.docsforadobe.dev/jsobjref/Matrix/), rounding each joined value once from its exact sum of products and deciding whether an inverted value overflows from its exact quotient, and runs Copy, Cut and Paste on the active document inside the run's transaction (https://ai-scripting.docsforadobe.dev/jsobjref/Application/). `crates/engine/src/tests/script_dom_prefs.rs`.
|
||||
- Scripts: `Document.pathItems` lists the paths and makes rectangles, rounded rectangles, ellipses, polygons, stars and empty paths with the defaults the help page https://ai-scripting.docsforadobe.dev/jsobjref/PathItems/ gives; each path's points, closed state, fill rule, area, length, guide state, selected points, fill and stroke colors, stroke options and transforms read and change as https://ai-scripting.docsforadobe.dev/jsobjref/PathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/PathPoints/ and https://ai-scripting.docsforadobe.dev/jsobjref/PathPoint/ describe them, and `RGBColor`, `CMYKColor`, `GrayColor`, `LabColor` and `NoColor` make colors (`docs/mcp.md`). `pathItems["name"]` reads a path by name as `pageItems` does, and `removeAll()` deletes nothing and throws when any path is on a locked artboard. A path takes the page item transforms, and `resize` also sets its stroke weight to a `changeLineWidths` percent from 0 to 100000 (at most 1000 points; a member of a compound sets the compound's stroke); gradients move with positions, so a `changeFillGradients` different from `changePositions` throws an error, as do `changeFillPatterns` and `changeStrokePattern` given as different values (`docs/mcp.md` lists these limits). Gradient stops are not there yet. A `PathPoint` of a path in an Objects on Path group goes stale when an edit of another path in the group moves it. `crates/engine/src/tests/script_dom_paths.rs`.
|
||||
- Scripts: `Document.placedItems` and `Document.rasterItems` list a document's linked and embedded images; `placedItems.add()` with a `File` assigned to `file` places an image linked, and `PlacedItem.relink(file)` and `embed()` relink and embed it, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PlacedItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PlacedItem/, https://ai-scripting.docsforadobe.dev/jsobjref/RasterItems/ and https://ai-scripting.docsforadobe.dev/jsobjref/RasterItem/ describe them. A raster item's bits per channel, channels, color space and transparency come from its encoded pixels' header. Only files the script may read, of at most 256 MiB and holding an image, are placed or relinked. Rasterizing and capturing are not there yet. `crates/engine/src/tests/script_dom_images.rs`.
|
||||
- Scripts: `PlacedItem.trace()` and `RasterItem.trace()` make an Image Trace object and return it as a `PluginItem` whose `tracing` gives its path, anchor and color counts, the source image's resolution, `expandTracing()`, `releaseTracing()` and its `TracingOptions`; assigning an option or loading a preset traces it again, except that the view options (`viewRaster` and `viewVector`) only change the view, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PluginItem/, https://ai-scripting.docsforadobe.dev/jsobjref/TracingObject/ and https://ai-scripting.docsforadobe.dev/jsobjref/TracingOptions/ describe them. Option values are checked for type and range before any trace, a script cannot save a preset, and the options without a VectorCraft setting throw. The source image of a traced item is left out of `pageItems`, `placedItems` and `rasterItems`; a script reaches it through `PluginItem.tracing.sourceArt`. Renaming an ordinary group that holds an image first to `Image Trace`, or moving or duplicating an image to the bottom of an ordinary group with that name, throws an error. `crates/engine/src/tests/script_dom_tracing.rs`.
|
||||
@@ -1125,15 +1125,17 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
|
||||
- Scripts: `document.characterStyles` and `document.paragraphStyles` add, find, rename, redefine, apply and remove character and paragraph styles, with the Normal styles listed first and kept, and a text range lists the styles its text is in, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/CharacterStyles/, https://ai-scripting.docsforadobe.dev/jsobjref/CharacterStyle/, https://ai-scripting.docsforadobe.dev/jsobjref/ParagraphStyles/, https://ai-scripting.docsforadobe.dev/jsobjref/ParagraphStyle/ and https://ai-scripting.docsforadobe.dev/jsobjref/TextRange/ describe them (`docs/mcp.md`). Style names of 1 to 256 characters without control characters, and at most 4,096 styles named in one run, are VectorCraft's own rules. Load Character Styles, Load Paragraph Styles and Load All Styles refuse a file larger than 64 MB. A paragraph style's character attributes are not there yet. `crates/engine/src/tests/script_styles.rs`.
|
||||
- Scripts: a text frame's `nextFrame` and `previousFrame` read and set its links to the frames before and after it, `areaText` and `pathText` thread a new frame to a base frame, and `document.stories` lists the stories, each with its frames in thread order and its text across them as one text range with its characters, words and paragraphs, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/TextFrameItem/, https://ai-scripting.docsforadobe.dev/jsobjref/Story/ and https://ai-scripting.docsforadobe.dev/jsobjref/Stories/ describe them; `text.thread.setNeighbor` links or unlinks two frames by id (`docs/mcp.md`). Which links are refused, and how a story is listed and found, are VectorCraft's own rules. `crates/engine/src/tests/script_threads.rs`.
|
||||
- Scripts: `PageItem.tags` reads, adds, renames and deletes an object's tags, name and value pairs that the native file keeps, and `Document.tags` reads, renames and deletes the tags of every page item but adds none (its `add` throws; a script adds a tag through the page item's `tags`), as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Tags/ and https://ai-scripting.docsforadobe.dev/jsobjref/Tag/ describe them, through `object.tags` and the `object.tag.*` commands, at most 64 tags an object (`docs/mcp.md`). `crates/engine/src/tests/script_tags.rs`.
|
||||
- Scripts: a document's layers and sublayers with their options, stacking and current layer, its groups and compound paths with clipping masks, new empty groups and compound paths and paths moved into compound paths, and its artboards with their rectangles, names, ruler origins and display options, added, inserted, removed and made active, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Layer/, https://ai-scripting.docsforadobe.dev/jsobjref/Layers/, https://ai-scripting.docsforadobe.dev/jsobjref/GroupItems/, https://ai-scripting.docsforadobe.dev/jsobjref/CompoundPathItem/, https://ai-scripting.docsforadobe.dev/jsobjref/CompoundPathItems/, https://ai-scripting.docsforadobe.dev/jsobjref/Artboard/ and https://ai-scripting.docsforadobe.dev/jsobjref/Artboards/ describe them (`docs/mcp.md`); `artboards.add` returns the new artboard and `artboards.insert` returns nothing. Scoped collections support string conversion, which fails for `Layers`, `GroupItems`, `CompoundPathItems` and `Artboards` once their container is gone; 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. `crates/engine/src/tests/script_dom.rs`, `crates/ui-egui/src/tests/script_run.rs`.
|
||||
- Scripts: `Document.print` prints the document to a file with `PrintOptions` and the job, color management, color separation, coordinate, flattener, font, page marks, paper and PostScript option classes the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PrintOptions/ and https://ai-scripting.docsforadobe.dev/jsobjref/PrintJobOptions/ describe, over the document's print settings, and `app.printPresetsList` lists the print presets (`docs/mcp.md`); `CUSTOMPROFILE` without a profile `name` throws. `crates/engine/src/tests/script_print.rs`.
|
||||
- Scripts: `Document.exportFile` with `ExportType.AutoCAD` writes a DXF file with the `ExportOptionsAutoCAD` options and the AutoCAD enumerations that https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsAutoCAD/ and https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/ describe; DWG throws an error that says it is not available (`docs/mcp.md`). `crates/engine/src/tests/script_save_open.rs`.
|
||||
- Scripts: `Document.print` without a file prints to the printer `PrintOptions.printerName` names, or the default printer, and `app.printerList` lists the installed printers as `Printer` objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/PrintOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/Application/ and https://ai-scripting.docsforadobe.dev/jsobjref/Printer/ describe. VectorCraft's own rules: the jobs are sent after the run's changes are kept and the person at the keyboard clicks Print or presses Space on it, which takes no click or focus for the first second, nothing is sent from a failed run, and the web build, and MCP or the command line without the app, cannot print to a printer from a script (`docs/mcp.md`). `crates/engine/src/tests/script_print.rs`, `crates/ui-egui/src/tests/script_print.rs`.
|
||||
- Scripts: `Document.saveAs`, `Document.exportFile` and `app.open` save, export and open documents, `Document.fullName` and `saved` give a document's file and saved state, setting `saved` records that state (`document.setSaved`), `Document.path` gives its folder as a `Folder` (VectorCraft's own type), and `Document.close` closes it, saving to its file first with `SaveOptions.SAVECHANGES`, with the option classes the help pages https://ai-scripting.docsforadobe.dev/jsobjref/IllustratorSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/EPSSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/PDFSaveOptions/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsPNG24/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsJPEG/, https://ai-scripting.docsforadobe.dev/jsobjref/ExportOptionsSVG/, https://ai-scripting.docsforadobe.dev/jsobjref/PDFFileOptions/ and https://ai-scripting.docsforadobe.dev/jsobjref/Document/ describe (the enumerations of the options that keep their defaults included), and read and write only where the script's `File` objects may, refusing a path whose real file name is not valid UTF-8; the warnings of each save, export and open go to the console (`docs/mcp.md`). `crates/engine/src/tests/script_save_open.rs`.
|
||||
- Scripts: the global `app` gives the open documents, new documents from a startup preset and a `DocumentPreset`, the active document, each document's selection and its page items with their names, notes, visibility, lock, opacity, position, size, bounds and stacking order, and moves and copies them into or beside other objects, as the help pages https://ai-scripting.docsforadobe.dev/jsobjref/Application/, https://ai-scripting.docsforadobe.dev/jsobjref/Documents/, https://ai-scripting.docsforadobe.dev/jsobjref/DocumentPreset/, https://ai-scripting.docsforadobe.dev/jsobjref/Document/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItems/, https://ai-scripting.docsforadobe.dev/jsobjref/PageItem/ and https://ai-scripting.docsforadobe.dev/jsobjref/GroupItem/ describe them; each change runs a command inside the run's transaction (`docs/mcp.md`). A script can check a member with `hasOwnProperty`, and can read a collection by name and name `activeDocument`, `documents` and `selection` without `app.` (https://ai-scripting.docsforadobe.dev/scriptingJavascript/objectReferences/). A key such as `1` is an array index and reads that position; in `pageItems` and `documents`, a number that is not an array index, such as `-1` or `1.5`, is looked up by name when the key is the text JavaScript writes for that number. VectorCraft's own rule. `app.executeMenuCommand` runs the menu items Select All, Deselect, Group, Ungroup, Make and Release Clipping Mask, Make and Release Compound Path, and Fit to Artwork Bounds by their menu command names (https://community.adobe.com/questions-652/a-list-of-illustrator-menu-commands-we-can-call-from-javascript-769510, https://gist.github.com/shalakolee/df3246659d4289eb99149b9ed00a00ee). The `parent` of a page item at the top of a layer is a `Layer` with `name`, `typename` and `toString`. A page item's `blendingMode` reads and sets its blend mode with the `BlendModes` values (https://ai-scripting.docsforadobe.dev/jsobjref/scripting-constants/).
|
||||
`Document.views` lists the document's drawn windows with their bounds, center, zoom and screen mode (https://ai-scripting.docsforadobe.dev/jsobjref/View/). Zoom follows each window's displayed percentage, including display density with Display Print Size at 100% Zoom enabled; bounds retain the physical camera scale. View objects keep their targets when windows are renumbered. View changes run no command, add no undo step, and remain when a script fails. A center outside the canvas after coordinate conversion throws a `RangeError`. `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
@@ -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 |
|
||||
|
||||
Reference in new issue
Block a user