mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-12-01 02:35:37 +01:00
Merge pull request #9277 from dotCooCoo/feat/scripts-app-select-tool
Scripts: app.selectTool picks a tool
This commit is contained in:
13 files changed
+271
-20
No files matched your search
@@ -72,10 +72,11 @@ serde_json = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
log = { workspace = true }
|
||||
|
||||
# Whether a recovery area folder is this account's own (`FolderStore::own_area`). Already in
|
||||
# Cargo.lock (tempfile, ui-egui), so this adds no new crate.
|
||||
# Whether a recovery area folder is this account's own (`FolderStore::own_area`), and opening a
|
||||
# file without following a link (`store::read_capped_plain`). Already in Cargo.lock (tempfile,
|
||||
# ui-egui), so this adds no new crate.
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
rustix = { workspace = true, features = ["std", "process"] }
|
||||
rustix = { workspace = true, features = ["std", "process", "fs"] }
|
||||
|
||||
# Whether a recovery area's lock file is still the one that was opened (`FolderStore::still_named`),
|
||||
# and whether two paths a script names are one file (`script::files`). Already in Cargo.lock
|
||||
|
||||
@@ -1045,11 +1045,13 @@ impl Session {
|
||||
match std::fs::symlink_metadata(&path) {
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
|
||||
// A link is refused: the script's gate does not check where it leads.
|
||||
Ok(m) if !m.file_type().is_file() => return Err("not a plain file".to_string()),
|
||||
Ok(m) if !m.file_type().is_file() => return Err(crate::store::NOT_PLAIN.to_string()),
|
||||
_ => {}
|
||||
}
|
||||
crate::file_access::check_read(&file).map_err(denied)?;
|
||||
crate::store::read_capped(&path, MAX_PROFILE_BYTES).map(Some)
|
||||
// Read without following a link, so a link put in the file's place since the check
|
||||
// above is refused too.
|
||||
crate::store::read_capped_plain(&path, MAX_PROFILE_BYTES).map(Some)
|
||||
})?;
|
||||
let Some(bytes) = read else { return Ok(None) };
|
||||
// The color profiles the file carries are installed where missing, as opening it installs
|
||||
|
||||
@@ -49,6 +49,9 @@
|
||||
//! `No active document`.
|
||||
//! - Assigning `Document.selection` takes one object, a list of them, `null` or `[]`; every object
|
||||
//! must be one of that document's that can be selected, or nothing changes. `undefined` throws.
|
||||
//! - `app.selectTool(name)` takes a tool's id, its label, or a name of the list cited at
|
||||
//! [`TOOL_NAME_PREFIX`], and the tool becomes the current tool when the run ends without an
|
||||
//! error. A run that fails leaves the tool as it was.
|
||||
//! - `controlBounds` is the visible bounds, widened to take in the direction points of every path
|
||||
//! in the object.
|
||||
//! - `Document.views` holds the document's drawn windows ([`crate::Session::window_views`]),
|
||||
@@ -172,7 +175,8 @@ const ARTBOARD_COORDS: &str = "CoordinateSystem.ARTBOARDCOORDINATESYSTEM";
|
||||
/// written yet, how many times each path's points went stale and each path as the run last saw its
|
||||
/// points, whether a call's own savepoint ([`atomically`]) is open, the settings of each
|
||||
/// `DocumentPreset` the run made, with the size of the values they hold now and the most they may
|
||||
/// hold (the run's heap), and the `Variable` and `Dataset` objects it gave out.
|
||||
/// hold (the run's heap), the `Variable` and `Dataset` objects it gave out, and the tool
|
||||
/// `app.selectTool` chose last.
|
||||
#[derive(Default)]
|
||||
pub(super) struct State {
|
||||
coords: Cell<Coords>,
|
||||
@@ -207,6 +211,7 @@ pub(super) struct State {
|
||||
preset_bytes: Cell<u64>,
|
||||
preset_limit: u64,
|
||||
vars: variables::Handles,
|
||||
tool: Cell<Option<&'static str>>,
|
||||
}
|
||||
|
||||
impl State {
|
||||
@@ -219,6 +224,12 @@ impl State {
|
||||
pub(super) fn saving(&self) -> bool {
|
||||
self.saving.get()
|
||||
}
|
||||
|
||||
/// The id of the tool `app.selectTool` chose last in the run, which becomes the current tool
|
||||
/// when the run ends without an error.
|
||||
pub(super) fn chosen_tool(&self) -> Option<&'static str> {
|
||||
self.tool.get()
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs `f`, whose commands are kept together or put back together: when `f` fails, every
|
||||
@@ -844,12 +855,24 @@ fn restore_layer(h: &Host, uid: u64, layer: Option<NodeId>, rows: &[NodeId]) ->
|
||||
/// commands changed it (commands given ids select them first), direct-selected anchors, segments,
|
||||
/// ruler guides, slices, the key, a Layers panel target and an object chosen inside a dynamic
|
||||
/// symbol instance or an Objects on Path group included, less the objects that are now deleted,
|
||||
/// hidden or locked.
|
||||
/// hidden or locked. `f`'s commands and the steps that put things back succeed or fail together
|
||||
/// ([`atomically`]): when putting back the selection, the layer or the active document fails, `f`'s
|
||||
/// changes are undone as well.
|
||||
fn on_doc<T>(
|
||||
h: &Host,
|
||||
uid: u64,
|
||||
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))
|
||||
}
|
||||
|
||||
/// The steps of [`on_doc`].
|
||||
fn on_doc_steps<T>(
|
||||
h: &Host,
|
||||
uid: u64,
|
||||
keep_selection: bool,
|
||||
f: impl FnOnce(&Host) -> std::result::Result<T, HostError>,
|
||||
) -> std::result::Result<T, HostError> {
|
||||
let (index, active, before, layer, activated) = {
|
||||
let s = h.session.borrow();
|
||||
@@ -1021,6 +1044,69 @@ fn app_is_open(h: &Host, a: &[Data]) -> Answer {
|
||||
Ok(Data::Bool(open))
|
||||
}
|
||||
|
||||
/// The start of the tool names that scripts pass to `app.selectTool`, as the list at
|
||||
/// <https://community.adobe.com/questions-652/what-s-new-in-illustrator-scripting-cc2020-769942> gives them.
|
||||
const TOOL_NAME_PREFIX: &str = "Adobe "; // brand-ok: the start of the tool names scripts pass
|
||||
|
||||
/// The names on that list, without [`TOOL_NAME_PREFIX`], whose words differ from the label of the
|
||||
/// VectorCraft tool they choose, with that tool's id. Names whose words are a VectorCraft tool's
|
||||
/// label (`Pen Tool`) choose that tool without a row here. The pairs are VectorCraft's own.
|
||||
const TOOL_NAMES: &[(&str, &str)] = &[
|
||||
("Select Tool", "selection"),
|
||||
("Direct Select Tool", "directSelection"),
|
||||
("Direct Object Select Tool", "groupSelection"),
|
||||
("Direct Lasso Tool", "lasso"),
|
||||
("Path Type Tool", "typeOnPath"),
|
||||
("Vertical Path Type Tool", "verticalTypeOnPath"),
|
||||
("Line Tool", "lineSegment"),
|
||||
("Shape Construction Regular Polygon Tool", "polygon"),
|
||||
("Shape Construction Star Tool", "star"),
|
||||
("Shape Construction Spiral Tool", "spiral"),
|
||||
("Brush Tool", "paintbrush"),
|
||||
("Freehand Tool", "pencil"),
|
||||
("Freehand Smooth Tool", "smooth"),
|
||||
("Freehand Erase Tool", "pathEraser"),
|
||||
("Corner Join Tool", "join"),
|
||||
("Knife Tool", "knife"),
|
||||
("New Twirl Tool", "twirl"),
|
||||
("Cyrstallize Tool", "crystallize"),
|
||||
("Planar Paintbucket Tool", "livePaintBucket"),
|
||||
("Planar Face Select Tool", "livePaintSelection"),
|
||||
("Mesh Editing Tool", "mesh"),
|
||||
("Gradient Vector Tool", "gradient"),
|
||||
("Crop Tool", "artboard"),
|
||||
("Slice Select Tool", "sliceSelection"),
|
||||
("Scroll Tool", "hand"),
|
||||
("Page Tool", "printTiling"),
|
||||
];
|
||||
|
||||
/// The id of the tool `name` names: a tool's id (`pen`), its label (`Pen Tool`), or a name of the
|
||||
/// list [`TOOL_NAME_PREFIX`] cites.
|
||||
fn tool_named(name: &str) -> Option<&'static str> {
|
||||
let tools = || vectorcraft_tools::catalog::all_tools();
|
||||
if let Some(t) = tools().find(|t| t.id == name || t.label == name) {
|
||||
return Some(t.id);
|
||||
}
|
||||
let rest = name.strip_prefix(TOOL_NAME_PREFIX)?;
|
||||
if let Some((_, id)) = TOOL_NAMES.iter().find(|(n, _)| *n == rest) {
|
||||
return vectorcraft_tools::tool_info(id).map(|t| t.id);
|
||||
}
|
||||
tools().find(|t| t.label == rest).map(|t| t.id)
|
||||
}
|
||||
|
||||
/// `app.selectTool(name)`: chooses the tool `name` names ([`tool_named`]) and gives `true`. The
|
||||
/// tool becomes the current tool when the run ends without an error, as a choice on the toolbar
|
||||
/// does; the tool chosen last in a run is the one that counts. A name no tool has throws.
|
||||
fn app_select_tool(h: &Host, a: &[Data]) -> Answer {
|
||||
let Data::String(name) = arg(a, 1) else { return Err(HostError::Type("selectTool needs a tool name, as a string".into())) };
|
||||
if name.len() > MAX_TEXT_BYTES {
|
||||
return Err(HostError::Range("the tool name is too long".into()));
|
||||
}
|
||||
let id = tool_named(name).ok_or_else(|| HostError::Error(format!("No tool is named \"{name}\"")))?;
|
||||
h.dom.tool.set(Some(id));
|
||||
Ok(Data::Bool(true))
|
||||
}
|
||||
|
||||
/// The menu command strings `app.executeMenuCommand` takes, each with the command it runs. The
|
||||
/// strings are the ones
|
||||
/// <https://community.adobe.com/questions-652/a-list-of-illustrator-menu-commands-we-can-call-from-javascript-769510>
|
||||
@@ -2224,9 +2310,9 @@ fn item_set_opacity(h: &Host, a: &[Data]) -> Answer {
|
||||
if !(0.0..=100.0).contains(&v) {
|
||||
return Err(HostError::Range("opacity must be from 0 to 100".into()));
|
||||
}
|
||||
// A value the getter reports for the item's opacity sends the opacity it has, and
|
||||
// `object.setProps` finds the no-op itself: an opacity a graph mark or label already has still
|
||||
// replaces the one the graph keeps for its series or kind.
|
||||
// A value the getter reports for the item's opacity runs no command, unless the item is a graph
|
||||
// mark or label whose graph keeps another opacity for its series or kind: then the opacity the
|
||||
// item has is sent, and replaces the one the graph keeps.
|
||||
// The opacity the item already has may be assigned while its layer is hidden or locked, unless
|
||||
// it would still replace the opacity a graph keeps for the item's series or kind.
|
||||
let (now, keeps_other) = with_doc(h, item.doc, |_, st| {
|
||||
@@ -2240,7 +2326,7 @@ fn item_set_opacity(h: &Host, a: &[Data]) -> Answer {
|
||||
if now.is_none() || keeps_other {
|
||||
refuse_protected_edit(h, item)?;
|
||||
}
|
||||
set_props(h, a, |_| false, json!({"opacity": now.unwrap_or(v)}))
|
||||
set_props(h, a, |_| now.is_some() && !keeps_other, json!({"opacity": now.unwrap_or(v)}))
|
||||
}
|
||||
|
||||
/// The members of `BlendModes` with the blend mode each one names.
|
||||
@@ -2842,6 +2928,7 @@ fn classes(link: &Link) -> Vec<HostClass> {
|
||||
("coordinateSystem", property(l, app_coords, app_set_coords), typed("CoordinateSystem")),
|
||||
("getIsFileOpen", method(l, app_is_open), returns("boolean", &[("filePath", "string")])),
|
||||
("redraw", method(l, app_redraw), returns("undefined", &[])),
|
||||
("selectTool", method(l, app_select_tool), returns("boolean", &[("toolName", "string")])),
|
||||
("undo", method(l, app_undo), returns("undefined", &[])),
|
||||
("redo", method(l, app_redo), returns("undefined", &[])),
|
||||
("executeMenuCommand", method(l, app_menu_command), returns("undefined", &[("menuCommandString", "string")])),
|
||||
|
||||
@@ -2647,7 +2647,15 @@ impl Session {
|
||||
o.insert("unhandledRejectionCount".into(), json!(job.realm.unhandled_rejection_count()));
|
||||
}
|
||||
close_run(self, host, &mut report, console::Ending::Finished);
|
||||
let tool = host.dom.chosen_tool();
|
||||
self.end_job(job, false);
|
||||
// The tool `app.selectTool` chose last becomes the current tool, as a choice on the
|
||||
// toolbar makes it; the run's changes are kept when the tool cannot be chosen.
|
||||
if let Some(id) = tool
|
||||
&& let Err(e) = self.select_tool(id, self.last_view)
|
||||
{
|
||||
report["toolError"] = json!(e.to_string());
|
||||
}
|
||||
self.script_report = Some(report.clone());
|
||||
Ok(report)
|
||||
}
|
||||
|
||||
@@ -219,6 +219,52 @@ fn read_past_cap(path: &Path, max: u64) -> std::io::Result<Vec<u8>> {
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
/// What [`read_capped_plain`] tells a path that is not a plain file.
|
||||
pub(crate) const NOT_PLAIN: &str = "not a plain file";
|
||||
|
||||
/// The content of `path` when it is a plain file of at most `max` bytes. The file is opened without
|
||||
/// following a link at `path` (on Windows a junction or other reparse point is opened itself), and
|
||||
/// its kind and bytes are read from that open file, so a link put at `path` after an earlier check
|
||||
/// is refused with [`NOT_PLAIN`] rather than read.
|
||||
pub(crate) fn read_capped_plain(path: &Path, max: u64) -> Result<Vec<u8>, String> {
|
||||
let file = open_no_link(path).map_err(|e| match std::fs::symlink_metadata(path) {
|
||||
Ok(m) if !m.file_type().is_file() || reparse_point(&m) => NOT_PLAIN.to_string(),
|
||||
_ => e.to_string(),
|
||||
})?;
|
||||
let m = file.metadata().map_err(|e| e.to_string())?;
|
||||
if !m.file_type().is_file() || reparse_point(&m) {
|
||||
return Err(NOT_PLAIN.to_string());
|
||||
}
|
||||
let mut bytes = vec![];
|
||||
file.take(max + 1).read_to_end(&mut bytes).map_err(|e| e.to_string())?;
|
||||
if bytes.len() as u64 > max {
|
||||
return Err(too_large(max));
|
||||
}
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
/// `path` opened for reading, without following a link there. A pipe put in its place does not hold
|
||||
/// the open up.
|
||||
#[cfg(unix)]
|
||||
fn open_no_link(path: &Path) -> std::io::Result<std::fs::File> {
|
||||
use std::os::unix::fs::OpenOptionsExt;
|
||||
let flags = rustix::fs::OFlags::NOFOLLOW | rustix::fs::OFlags::NONBLOCK;
|
||||
std::fs::OpenOptions::new().read(true).custom_flags(flags.bits() as i32).open(path)
|
||||
}
|
||||
|
||||
/// `path` opened for reading; a link or junction there is opened itself, not its target.
|
||||
#[cfg(windows)]
|
||||
fn open_no_link(path: &Path) -> std::io::Result<std::fs::File> {
|
||||
use std::os::windows::fs::OpenOptionsExt;
|
||||
const FILE_FLAG_OPEN_REPARSE_POINT: u32 = 0x0020_0000;
|
||||
std::fs::OpenOptions::new().read(true).custom_flags(FILE_FLAG_OPEN_REPARSE_POINT).open(path)
|
||||
}
|
||||
|
||||
#[cfg(not(any(unix, windows)))]
|
||||
fn open_no_link(path: &Path) -> std::io::Result<std::fs::File> {
|
||||
std::fs::File::open(path)
|
||||
}
|
||||
|
||||
/// Plug-ins loading on worker threads, which [`Session::poll_plugin_loads`] and
|
||||
/// [`Session::finish_plugin_loads`] install.
|
||||
pub(crate) enum PluginLoad {
|
||||
|
||||
@@ -155,6 +155,27 @@ fn page_item_size_setters_on_a_rotated_object_give_the_page_aligned_size() {
|
||||
assert_eq!(format!("{:?}", s.active().unwrap().doc.node(b)), other, "the other object stays as it was");
|
||||
}
|
||||
|
||||
/// `controlBounds` holds a curve's handles, which reach past the curve; for a rectangle it is the
|
||||
/// visible bounds.
|
||||
#[test]
|
||||
fn control_bounds_hold_the_handles_of_a_curve() {
|
||||
let (mut s, _, _) = doc();
|
||||
s.execute("path.create", &json!({"d": "M100 200 C100 100 200 100 200 200"})).unwrap();
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var p = app.activeDocument.pageItems, c = p[0], r = p[1];\
|
||||
function h(b) { return b[1] - b[3]; }\
|
||||
vc.log([h(c.visibleBounds), h(c.controlBounds), c.controlBounds[0] <= c.visibleBounds[0]]);\
|
||||
vc.log(String(r.controlBounds) === String(r.visibleBounds));",
|
||||
);
|
||||
let heights = out[0].as_array().unwrap();
|
||||
let (visible, control) = (heights[0].as_f64().unwrap(), heights[1].as_f64().unwrap());
|
||||
// The curve rises 75 pt and its handles 100 pt; half the stroke's weight reaches above the curve.
|
||||
assert!(control - visible > 20.0 && control - visible <= 25.0 + 1e-6, "{out:?}");
|
||||
assert_eq!(heights[2], json!(true), "{out:?}");
|
||||
assert_eq!(out[1], json!(true), "{out:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn convert_coordinate_pair_is_inverse_and_y_up() {
|
||||
let mut s = Session::new();
|
||||
@@ -500,6 +521,7 @@ fn assigning_the_reported_opacity_changes_nothing() {
|
||||
assert_eq!(out, vec![json!(33.3333)]);
|
||||
assert_eq!(s.active().unwrap().doc.node(a).unwrap().opacity, before);
|
||||
assert_eq!(undo_steps(&s), steps);
|
||||
assert_eq!(s.script_report().unwrap()["slowestCommands"], json!([]), "the assignment runs no command");
|
||||
// A value close to the reported one but not equal to it is still applied.
|
||||
s.execute("object.setProps", &json!({"id": a.0, "opacity": 50})).unwrap();
|
||||
let (before, steps) = (s.active().unwrap().doc.node(a).unwrap().opacity, undo_steps(&s));
|
||||
@@ -560,6 +582,14 @@ fn selection_assignment_is_atomic_across_invalid_items() {
|
||||
let e = failure(&mut s, "var p = app.activeDocument.pageItems; app.activeDocument.selection = [p[0], p[1]];");
|
||||
assert!(e.contains("Cannot select PathItem"), "{e}");
|
||||
assert!(s.active().unwrap().selection.objects.is_empty());
|
||||
// With the valid item first and the error caught, the run sees the selection unchanged.
|
||||
let out = log(
|
||||
&mut s,
|
||||
"var d = app.activeDocument, p = d.pageItems; try { d.selection = [p[1], p[0]]; vc.log('assigned'); }\
|
||||
catch (e) { vc.log(String(e).indexOf('Cannot select PathItem') >= 0); } vc.log(d.selection.length);",
|
||||
);
|
||||
assert_eq!(out, vec![json!(true), json!(0)]);
|
||||
assert!(s.active().unwrap().selection.objects.is_empty());
|
||||
s.execute("object.setProps", &json!({"ids": [b.0], "locked": false})).unwrap();
|
||||
let out = log(
|
||||
&mut s,
|
||||
@@ -2116,6 +2146,35 @@ fn prototype_changes_cannot_forge_a_page_item() {
|
||||
assert_eq!(s.active().unwrap().doc.node(a).unwrap().name, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn select_tool_makes_the_named_tool_current_when_the_run_ends() {
|
||||
let (mut s, _, _) = doc();
|
||||
assert_eq!(s.tool_id(), "selection");
|
||||
// A tool's id, its label and a name in the form scripts pass all choose it; the last one counts.
|
||||
assert_eq!(log(&mut s, "vc.log(app.selectTool('pen'));"), vec![json!(true)]);
|
||||
assert_eq!(s.tool_id(), "pen");
|
||||
log(&mut s, "app.selectTool('Rectangle Tool');");
|
||||
assert_eq!(s.tool_id(), "rectangle");
|
||||
log(&mut s, "app.selectTool('Adobe Ellipse Tool'); app.selectTool('Adobe Direct Select Tool');");
|
||||
assert_eq!(s.tool_id(), "directSelection");
|
||||
log(&mut s, "app.selectTool('Adobe Select Tool');");
|
||||
assert_eq!(s.tool_id(), "selection");
|
||||
// An unknown name throws, a caught error chooses nothing, and a run that fails leaves the tool.
|
||||
assert!(failure(&mut s, "app.selectTool('No Such Tool');").contains("No tool is named \"No Such Tool\""));
|
||||
assert!(failure(&mut s, "app.selectTool('Adobe ');").contains("No tool is named"));
|
||||
let out = log(&mut s, "try { app.selectTool('pencil tool'); } catch (e) { vc.log(e.message); }");
|
||||
assert_eq!(out, vec![json!("No tool is named \"pencil tool\"")]);
|
||||
assert!(failure(&mut s, "app.selectTool('pen'); throw new Error('stop');").contains("stop"));
|
||||
let out = log(&mut s, "try { app.selectTool(5); } catch (e) { vc.log(e.name); }");
|
||||
assert_eq!(out, vec![json!("TypeError")]);
|
||||
assert!(failure(&mut s, "app.selectTool(new Array(5000).join('a'));").contains("too long"));
|
||||
assert_eq!(s.tool_id(), "selection");
|
||||
// With no document open the tool is chosen too.
|
||||
let mut empty = Session::new();
|
||||
log(&mut empty, "app.selectTool('Adobe Freehand Tool');");
|
||||
assert_eq!(empty.tool_id(), "pencil");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsupported_members_say_so() {
|
||||
let (mut s, _, _) = doc();
|
||||
@@ -2340,6 +2399,9 @@ fn a_collection_read_with_a_name_gives_the_named_object() {
|
||||
vc.log(m);",
|
||||
);
|
||||
assert_eq!(out, vec![json!([true, "n", true, false, true]), json!([true, true, false]), json!(["Not found", "Not found"])]);
|
||||
// A name the collection inherits is not looked up as an object's name when it is assigned.
|
||||
let out = log(&mut s, "Object.prototype.tag = 1; var p = app.activeDocument.pageItems; p.tag = 2; vc.log(p.tag);");
|
||||
assert_eq!(out, vec![json!(1)]);
|
||||
}
|
||||
|
||||
/// A collection read with a name that is the text of a number but not an array index, such as `-1`
|
||||
|
||||
@@ -157,6 +157,24 @@ fn a_write_reads_the_file_it_replaces_only_one_byte_past_the_new_length() {
|
||||
assert!(holds(&[][..], &[]));
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn a_plain_capped_read_refuses_a_link_and_reads_a_plain_file() {
|
||||
use crate::store::{NOT_PLAIN, read_capped_plain};
|
||||
let root = fresh_dir("plain-read");
|
||||
let target = root.join("target.bin");
|
||||
std::fs::write(&target, b"outside").unwrap();
|
||||
let link = root.join("profile.vectorcraft");
|
||||
std::os::unix::fs::symlink(&target, &link).unwrap();
|
||||
assert_eq!(read_capped_plain(&link, 100), Err(NOT_PLAIN.to_string()));
|
||||
let folder = root.join("folder");
|
||||
std::fs::create_dir(&folder).unwrap();
|
||||
assert_eq!(read_capped_plain(&folder, 100), Err(NOT_PLAIN.to_string()));
|
||||
assert_eq!(read_capped_plain(&target, 100), Ok(b"outside".to_vec()));
|
||||
assert_eq!(read_capped_plain(&target, 7), Ok(b"outside".to_vec()));
|
||||
assert!(read_capped_plain(&target, 6).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_saved_preset_replaces_an_oversized_file_in_its_place() {
|
||||
let root = fresh_dir("oversized-put");
|
||||
|
||||
@@ -91,8 +91,8 @@ const INSIDE: &[(&str, &str)] = &[
|
||||
(
|
||||
"Application.prototype.",
|
||||
"activeDocument activeDocument= beep beep= constructor coordinateSystem coordinateSystem= documents doScript \
|
||||
executeMenuCommand getIsFileOpen loadAction loadAction= redo redraw selection selection= textFonts toString typename \
|
||||
undo unloadAction unloadAction=",
|
||||
executeMenuCommand getIsFileOpen loadAction loadAction= redo redraw selection selection= selectTool textFonts toString \
|
||||
typename undo unloadAction unloadAction=",
|
||||
),
|
||||
("DocumentPreset.", "prototype"),
|
||||
(
|
||||
|
||||
@@ -966,6 +966,26 @@ fn objects_of_a_host_class_report_its_available_members_as_their_own() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unavailable_member_hides_the_member_its_parent_class_has() {
|
||||
let mut r = realm(1_000_000);
|
||||
let value: HostFunction = Rc::new(|_| Ok(Data::Number(1.0)));
|
||||
let missing: HostFunction = Rc::new(|_| Err(HostError::Error("not here yet".into())));
|
||||
let class = |name: &str, parent: Option<&str>, member: HostMember| HostClass {
|
||||
name: name.into(),
|
||||
parent: parent.map(Into::into),
|
||||
members: vec![("size".to_string(), member)],
|
||||
info: Vec::new(),
|
||||
index: None,
|
||||
construct: None,
|
||||
};
|
||||
let classes = vec![class("Base", None, HostMember::Get(value)), class("Leaf", Some("Base"), HostMember::Unavailable(missing))];
|
||||
let objects = vec![("it".into(), host_ref("Leaf", &[1.0])), ("base".into(), host_ref("Base", &[2.0]))];
|
||||
r.define_host_classes(classes, objects).unwrap();
|
||||
r.start("[it.hasOwnProperty('size'), it.propertyIsEnumerable('size'), base.hasOwnProperty('size')].join()").unwrap();
|
||||
assert_eq!(finish(&mut r, 1_000_000).0.unwrap(), JsValue::String("false,false,true".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_member_a_class_declares_unavailable_is_not_its_own_when_its_parent_has_it() {
|
||||
let mut r = realm(1_000_000);
|
||||
|
||||
@@ -202,7 +202,7 @@ features! {
|
||||
ScriptuiDrawing "scriptui.drawing" Dialogs,
|
||||
ScriptuiPalette "scriptui.palette" HostOnly,
|
||||
ScriptuiWindow "scriptui.window" Dialogs,
|
||||
SelectTool "selectTool" HostOnly,
|
||||
SelectTool "selectTool" Dom,
|
||||
Socket "socket" HostOnly,
|
||||
UnitValue "unitValue" Language,
|
||||
Xml "xml" Language,
|
||||
|
||||
@@ -1596,7 +1596,7 @@ fn declarations_past_a_limit_hold_from_where_they_stand() {
|
||||
fn application_methods_are_features_not_members() {
|
||||
let r = report("app.executeMenuCommand('acmecopyall');\napp.selectTool('acme');\n");
|
||||
assert!(r.members.is_empty(), "{:?}", r.members);
|
||||
assert_eq!(r.needs, [Need::MenuCommands, Need::HostOnly]);
|
||||
assert_eq!(r.needs, [Need::Dom, Need::MenuCommands]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
+11
-5
@@ -2719,9 +2719,9 @@ control character, in the first 8 KiB) or `tooLarge` (over 8 MiB). For a script,
|
||||
|
||||
- `needs` lists what the script needs from the app that runs it: `language` (the script language's own objects,
|
||||
syntax and directives, such as `$`, `alert`, `UnitValue`, `reflect`, the XML object and E4X, `#target` and
|
||||
`#targetengine`), `dom` (the reference app's document model), `files`, `menuCommands`, `dialogs`, and `hostOnly`
|
||||
(features only the reference app has: palettes, BridgeTalk, sockets, native code, XMP, operator overloading,
|
||||
actions and `selectTool`).
|
||||
`#targetengine`), `dom` (the reference app's document model, `app.selectTool` included), `files`, `menuCommands`,
|
||||
`dialogs`, and `hostOnly` (features only the reference app has: palettes, BridgeTalk, sockets, native code, XMP,
|
||||
operator overloading and actions).
|
||||
- `directives` lists the `#include`, `#includepath`, `#script`, `#strict`, `#target` and `#targetengine` lines,
|
||||
and `targets` splits each `#target` line's application specifier into `app`, `instance`, `version` and
|
||||
`locale`. A directive is read where it starts a line, written `#name` or `//@name`.
|
||||
@@ -2932,7 +2932,7 @@ through `$`:
|
||||
describes: `app.documents`, `app.activeDocument` (assigning an open document makes it the active one),
|
||||
`app.selection` (assigning it sets the active document's selection), `app.coordinateSystem`,
|
||||
`app.redraw()`, `app.undo()`, `app.redo()`,
|
||||
`app.getIsFileOpen(path)` and `app.executeMenuCommand(name)`. `app.redraw()` returns without changing
|
||||
`app.getIsFileOpen(path)`, `app.selectTool(name)` and `app.executeMenuCommand(name)`. `app.redraw()` returns without changing
|
||||
anything. `app.undo()` and `app.redo()` run `edit.undo` and `edit.redo` in the active document and reach
|
||||
only the steps the run made; with no such step they change nothing, and with no document open they throw
|
||||
`No active document` (VectorCraft's own rules). After a run that succeeds, each document that was open
|
||||
@@ -2954,7 +2954,13 @@ through `$`:
|
||||
assigning `activeDocument` or `selection` without `app.` assigns the application's member. A top-level
|
||||
`var selection = ...` does the same and does not make a variable of the script. An assignment to `documents`
|
||||
leaves its value unchanged. Outside strict mode the assignment is ignored, and in strict mode code
|
||||
(`'use strict'`) or with `#strict on` it throws a `TypeError`. `app.documents`
|
||||
(`'use strict'`) or with `#strict on` it throws a `TypeError`. `selectTool`
|
||||
(https://community.adobe.com/questions-652/what-s-new-in-illustrator-scripting-cc2020-769942) takes a tool's id
|
||||
(`pen`), its label (`Pen Tool`) or a tool name in the form that thread lists, returns `true`, and makes the tool it
|
||||
names the current tool when the run ends without an error; the tool chosen last in a run is the one that counts,
|
||||
and a run that fails leaves the tool as it was. A name no tool has throws `No tool is named "<name>"`, a name that
|
||||
is not a string throws a `TypeError`, and a name of more than 4,096 bytes throws a `RangeError`. Which tool each
|
||||
name in that thread chooses is VectorCraft's own reading; names with no VectorCraft tool throw. `app.documents`
|
||||
(https://ai-scripting.docsforadobe.dev/jsobjref/Documents/) has `length`, `[i]`, `index(key)`, `getByName(name)`
|
||||
and `add(colorSpace?, width?, height?, numArtBoards?, artboardLayout?, artboardSpacing?, artboardRowsOrCols?)`,
|
||||
which runs `file.new` (`artboardRowsOrCols` is the number of rows for `GridByCol` and `RLGridByCol`, and of
|
||||
|
||||
@@ -1134,6 +1134,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
|
||||
`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`, 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: 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`.
|
||||
|
||||
Reference in new issue
Block a user