mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-29 01:34:29 +01:00
Merge pull request #8924 from dotCooCoo/feat/script-warning-reaches
Scripts: the Other Script… warning lists what the script reaches outside the document
This commit is contained in:
7 files changed
+380
-20
No files matched your search
@@ -2070,7 +2070,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"ui.runScript",
|
||||
"Other Script…",
|
||||
"Cmd+F12",
|
||||
"{path? | source?, name?} run a .js or .jsx file (script.run), after the warning unless Preferences › General › Show External Script Warning is off (dialog `scriptRun`: `name`, `script`, `dontShow`); without a file pick one (the web opens the browser's file picker); with Preferences › General › Run Startup Scripts on, the startup scripts run first (script.startup.run) and script.run's reply also holds `startup`, script.startup.run's reply; while a startup script runs before it the reply is {running: true, queued: true}, and a later failure to start shows in the status bar",
|
||||
"{path? | source?, name?} run a .js or .jsx file (script.run), after the warning unless Preferences › General › Show External Script Warning is off (dialog `scriptRun`: `choice`, `skip`, and `reaches`, which ui.dialog.set cannot set: the `kind`, `needs`, `outside`, `includes` and `truncated` of script.check's report on the script, which the warning lists, or null when the check failed); without a file pick one (the web opens the browser's file picker); with Preferences › General › Run Startup Scripts on, the startup scripts run first (script.startup.run) and script.run's reply also holds `startup`, script.startup.run's reply; while a startup script runs before it the reply is {running: true, queued: true}, and a later failure to start shows in the status bar",
|
||||
),
|
||||
(
|
||||
"ui.runInstalledScript",
|
||||
|
||||
@@ -115,7 +115,7 @@ pub(crate) fn problem_label(code: &str) -> Option<&'static str> {
|
||||
}
|
||||
|
||||
/// Where something is: `line 12`, or `lib/a.jsxinc, line 3` in an included file.
|
||||
fn place(item: &Value) -> String {
|
||||
pub(super) fn place(item: &Value) -> String {
|
||||
let line = item["line"].as_u64().map(|l| l.to_string());
|
||||
match (item["file"].as_str(), line) {
|
||||
(Some(file), Some(line)) => crate::i18n::fmt(tl!("{file}, line {line}"), &[("file", file), ("line", &line)]),
|
||||
@@ -136,7 +136,7 @@ fn lines(item: &Value) -> String {
|
||||
}
|
||||
|
||||
/// `count` and `lines` of an entry as a note: `3 · lines 4, 9, 12`.
|
||||
fn tally(item: &Value) -> String {
|
||||
pub(super) fn tally(item: &Value) -> String {
|
||||
let count = item["count"].as_u64().unwrap_or_default();
|
||||
match lines(item) {
|
||||
l if l.is_empty() => count.to_string(),
|
||||
@@ -144,7 +144,7 @@ fn tally(item: &Value) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
fn list<'r>(r: &'r Value, key: &str) -> &'r [Value] {
|
||||
pub(super) fn list<'r>(r: &'r Value, key: &str) -> &'r [Value] {
|
||||
r[key].as_array().map_or(&[][..], Vec::as_slice)
|
||||
}
|
||||
|
||||
|
||||
@@ -7,9 +7,20 @@
|
||||
//! asks for a `.js` or `.jsx` file through the app's file asks. With Preferences › General › Show
|
||||
//! External Script Warning off, the chosen script runs at once. With General › Run Startup Scripts
|
||||
//! on, the startup scripts run first (`script.startup.run`). The warning (kind `scriptRun`) is a
|
||||
//! prompt: its `choice` field (`proceed` runs, `cancel` does not) and `skip` (true: turn the
|
||||
//! warning off). The growth question (`scriptGrowth`) and the question quitting asks
|
||||
//! (`scriptClose`) have the `choice` field alone.
|
||||
//! prompt: its `choice` field (`proceed` runs, `cancel` does not), `skip` (true: turn the warning
|
||||
//! off) and `reaches`, which `ui.dialog.set` cannot set: the `kind`, `needs`, `outside`, `includes`
|
||||
//! and `truncated` of `script.check`'s report on the script, read without running it (a path also
|
||||
//! checks the files its `#include` lines name), or null when the check fails. The warning lists
|
||||
//! what the report finds the script reaches outside the document (each of `script.check`'s
|
||||
//! `outside` categories, such as files it writes, moves or deletes, files it opens in other apps,
|
||||
//! the network, native code, environment variables and code the checker can't read), the files
|
||||
//! and dialogs it needs, features only the reference app has, and its includes (at most
|
||||
//! [`SHOWN_INCLUDES`], then the count of the rest). It says when the script is too large to check,
|
||||
//! compiled or not a script, when the check failed, and when a list was cut short at its limit.
|
||||
//! The listing is information: Run runs the script as before, after checking it again. When the
|
||||
//! report has changed since the warning opened, nothing runs and the warning opens again with the
|
||||
//! new report. The growth question
|
||||
//! (`scriptGrowth`) and the question quitting asks (`scriptClose`) have the `choice` field alone.
|
||||
//!
|
||||
//! A script's dialog (kind `scriptDialog`) has the fields `kind` (alert, confirm or prompt),
|
||||
//! `message`, `title` (null: Script Alert), `errorIcon`, `noAsDefault`, `value` (the prompt's
|
||||
@@ -37,7 +48,7 @@ use craft::theme::variant::Tone;
|
||||
use craft::ui::buttons::Button;
|
||||
use craft::ui::contract::{Bind, Outcome as _, Props as _, Scroll, Show as _, ShowContainer as _};
|
||||
use craft::ui::dialog::{
|
||||
DialogHost, DialogId, DialogResult, DialogStack, FieldRefusal, Prompt, PromptChoice, StackDialog, StandardPrompt, dialog_id,
|
||||
DialogHost, DialogId, DialogResult, DialogStack, FieldRefusal, HeldOk, Prompt, PromptAnswer, PromptChoice, StackDialog, StandardPrompt, dialog_id,
|
||||
};
|
||||
use craft::ui::display::Text;
|
||||
use craft::ui::layout_components::Stack;
|
||||
@@ -77,7 +88,53 @@ const PICKED_LIST_HEIGHT: f32 = 120.0;
|
||||
/// The warning before a script runs. One type per question, so the host's per-type results never
|
||||
/// mix the three questions of this area.
|
||||
pub(crate) struct RunQuestion(pub(crate) StandardPrompt);
|
||||
crate::dialogs::confirm::wrapped_dialog!(RunQuestion, StandardPrompt, KIND);
|
||||
|
||||
/// The prompt's own dialog, with `reaches` added to its fields: what the warning lists.
|
||||
impl StackDialog for RunQuestion {
|
||||
type Result = PromptAnswer;
|
||||
|
||||
fn id(&self) -> DialogId {
|
||||
dialog_id(KIND)
|
||||
}
|
||||
|
||||
fn instance(&self) -> Option<DialogId> {
|
||||
StackDialog::instance(&self.0)
|
||||
}
|
||||
|
||||
fn key(&self) -> Option<&str> {
|
||||
Some(KIND)
|
||||
}
|
||||
|
||||
fn show(&mut self, ui: &mut Ui, stack: &DialogStack) -> Option<DialogResult<PromptAnswer>> {
|
||||
StackDialog::show(&mut self.0, ui, stack)
|
||||
}
|
||||
|
||||
fn confirm(&mut self, ctx: &egui::Context) -> Option<PromptAnswer> {
|
||||
self.0.confirm(ctx)
|
||||
}
|
||||
|
||||
fn held_state(&self) -> Option<HeldOk> {
|
||||
self.0.held_state()
|
||||
}
|
||||
|
||||
fn json_fields(&self) -> Option<Value> {
|
||||
let mut fields = self.0.json_fields()?;
|
||||
fields["reaches"] = self.0.tag_as::<RunWarning>().map_or(Value::Null, |w| w.reaches.clone());
|
||||
Some(fields)
|
||||
}
|
||||
|
||||
fn set_json_field(&mut self, ctx: &egui::Context, field: &str, value: Value) -> Result<(), String> {
|
||||
self.0.set_json_field(ctx, field, value)
|
||||
}
|
||||
|
||||
fn cancelled(&mut self, ctx: &egui::Context) {
|
||||
self.0.cancelled(ctx);
|
||||
}
|
||||
|
||||
fn preview_color(&mut self, key: &str, color: Option<craft::theme::Srgba>) {
|
||||
self.0.preview_color(key, color);
|
||||
}
|
||||
}
|
||||
|
||||
/// The question a run asks when it has added a great deal.
|
||||
pub(crate) struct GrowthQuestion(pub(crate) StandardPrompt);
|
||||
@@ -87,9 +144,11 @@ crate::dialogs::confirm::wrapped_dialog!(GrowthQuestion, StandardPrompt, GROWTH_
|
||||
pub(crate) struct CloseQuestion(pub(crate) StandardPrompt);
|
||||
crate::dialogs::confirm::wrapped_dialog!(CloseQuestion, StandardPrompt, CLOSE_KIND);
|
||||
|
||||
/// The tag of the warning: the params `script.run` takes once the warning is answered.
|
||||
/// The tag of the warning: the params `script.run` takes once the warning is answered, and the
|
||||
/// parts of `script.check`'s report the warning lists ([`reaches`]).
|
||||
struct RunWarning {
|
||||
params: Value,
|
||||
reaches: Value,
|
||||
/// The automation roots in force when asked: the script runs under them, and under any in force
|
||||
/// when the warning is answered.
|
||||
scope: ScopeHandle,
|
||||
@@ -509,19 +568,111 @@ pub(crate) fn chosen(app: &mut VectorcraftApp, params: Value) -> Result<Value, S
|
||||
if !app.session.prefs.show_external_script_warning {
|
||||
return crate::script_runs::run_chosen(app, params);
|
||||
}
|
||||
let reaches = reaches(app, ¶ms);
|
||||
let automated = app.automation_asked();
|
||||
warn(app, params, reaches, ScopeHandle::capture(), automated)
|
||||
}
|
||||
|
||||
/// Opens the warning for the script `params` name, listing `reaches`; the script runs under
|
||||
/// `scope`, and as automation when `automated` ([`RunWarning`]).
|
||||
fn warn(app: &mut VectorcraftApp, params: Value, reaches: Value, scope: ScopeHandle, automated: bool) -> Result<Value, String> {
|
||||
let path = params.get("path").and_then(Value::as_str);
|
||||
let name = params.get("name").and_then(Value::as_str).or(path).map_or_else(|| "script".to_string(), vectorcraft_engine::cmd::fileio::file_name);
|
||||
// The script's name is the message: it is what the person reads first.
|
||||
let prompt = StandardPrompt::custom(name)
|
||||
.title(tl!("Run Script"))
|
||||
.paragraph(tl!("A script can change the open documents and can write files through the commands it runs. Run only scripts you trust."))
|
||||
.paragraph(tl!("A script can change the open documents and can write files through the commands it runs. Run only scripts you trust."));
|
||||
let prompt = listed(prompt, &reaches)
|
||||
.dont_show_again()
|
||||
.button(PromptChoice::Proceed, tl!("Run"))
|
||||
.button(PromptChoice::Cancel, tl!("Cancel"))
|
||||
.tag(RunWarning { params, scope: ScopeHandle::capture(), automated: app.automation_asked() });
|
||||
.tag(RunWarning { params, reaches, scope, automated });
|
||||
with_host(app, |host, _| host.open(RunQuestion(prompt))).ok_or_else(|| "there is no window to ask in".to_string())?;
|
||||
Ok(Value::Null)
|
||||
}
|
||||
|
||||
/// The status when Run finds that the script's report changed since the warning opened: the
|
||||
/// warning opens again with the new report, and nothing runs.
|
||||
pub(crate) const CHANGED_SINCE_WARNING: &str = "The script changed after its warning opened: check the warning again";
|
||||
|
||||
/// The most includes the warning lists; a line after them gives the count of the rest.
|
||||
pub(crate) const SHOWN_INCLUDES: usize = 20;
|
||||
|
||||
/// The parts of `script.check`'s report on the script `script.run`'s `params` name that the
|
||||
/// warning lists, read without running the script; a path also checks the files its `#include`
|
||||
/// lines name. Null when the check fails: the run reports why the script can't be read.
|
||||
fn reaches(app: &mut VectorcraftApp, params: &Value) -> Value {
|
||||
checked(app, params).unwrap_or(Value::Null)
|
||||
}
|
||||
|
||||
/// [`reaches`], with the check's error when it fails, for example when the request asking can't
|
||||
/// read the script.
|
||||
fn checked(app: &mut VectorcraftApp, params: &Value) -> Result<Value, String> {
|
||||
let check = match (params.get("path"), params.get("source")) {
|
||||
(Some(path), _) => json!({"path": path, "includes": true}),
|
||||
(None, Some(source)) => json!({"data": source}),
|
||||
(None, None) => return Ok(Value::Null),
|
||||
};
|
||||
let r = app.session.execute("script.check", &check).map_err(|e| e.to_string())?;
|
||||
Ok(json!({"kind": r["kind"], "needs": r["needs"], "outside": r["outside"], "includes": r["includes"], "truncated": r["truncated"]}))
|
||||
}
|
||||
|
||||
/// `prompt` with what the report `r` finds the script reaches outside the document, one line each;
|
||||
/// nothing more for a script that was checked and reaches nothing. A failed check (null) says the
|
||||
/// script was not read.
|
||||
fn listed(prompt: StandardPrompt, r: &Value) -> StandardPrompt {
|
||||
use super::script_check::{list, need_label, outside_label, place, status_label, tally};
|
||||
let unchecked = match r["kind"].as_str() {
|
||||
Some("script") => None,
|
||||
Some("compiled") => Some(tl!("Compiled script: ask its author for the .jsx file")),
|
||||
Some("tooLarge") => Some(tl!("Too large to check")),
|
||||
_ if r.is_null() => Some(tl!("Not read")),
|
||||
_ => Some(tl!("Not a script for the reference app")),
|
||||
};
|
||||
if let Some(text) = unchecked {
|
||||
return prompt.note(text);
|
||||
}
|
||||
// A row: its text, then its count, lines or status when it has them.
|
||||
let row = |text: &str, note: &str| if note.is_empty() { text.to_string() } else { format!("{text} · {note}") };
|
||||
let outside: Vec<String> = list(r, "outside")
|
||||
.iter()
|
||||
.filter_map(|o| {
|
||||
let label = o["id"].as_str().and_then(outside_label)?;
|
||||
let modes: Vec<&str> = list(o, "modes").iter().filter_map(Value::as_str).collect();
|
||||
let label = if modes.is_empty() { label.to_string() } else { format!("{label} ({})", modes.join(", ")) };
|
||||
Some(row(&label, &tally(o)))
|
||||
})
|
||||
.collect();
|
||||
let needs = list(r, "needs").iter().filter_map(Value::as_str).filter(|n| matches!(*n, "files" | "dialogs" | "hostOnly")).filter_map(need_label);
|
||||
// The needs come first, each a sentence of its own; the heading names only what the script does
|
||||
// outside the document.
|
||||
let mut lines: Vec<String> = needs.map(str::to_string).collect();
|
||||
if !outside.is_empty() {
|
||||
lines.push(crate::i18n::colon(tl!("Outside the document")));
|
||||
lines.extend(outside);
|
||||
}
|
||||
let includes = list(r, "includes");
|
||||
if !includes.is_empty() {
|
||||
lines.push(crate::i18n::colon(tl!("Includes")));
|
||||
for i in includes.iter().take(SHOWN_INCLUDES) {
|
||||
let status = i["status"].as_str().and_then(status_label).unwrap_or_default();
|
||||
let note = [status.to_string(), place(i)].into_iter().filter(|s| !s.is_empty()).collect::<Vec<_>>().join(" · ");
|
||||
lines.push(row(i["value"].as_str().unwrap_or_default(), ¬e));
|
||||
}
|
||||
if includes.len() > SHOWN_INCLUDES {
|
||||
let count = (includes.len() - SHOWN_INCLUDES).to_string();
|
||||
lines.push(crate::i18n::fmt(tl!("Included files not listed: {count}"), &[("count", &count)]));
|
||||
}
|
||||
}
|
||||
if r["truncated"].as_bool() == Some(true) {
|
||||
lines.push(tl!("Some lists were cut short at their limit.").to_string());
|
||||
}
|
||||
if lines.is_empty() {
|
||||
return prompt;
|
||||
}
|
||||
prompt.paragraph(tl!("VectorCraft read this script without running it.")).lines(lines.into_iter().map(Into::into))
|
||||
}
|
||||
|
||||
fn growth_question() -> GrowthQuestion {
|
||||
GrowthQuestion(
|
||||
StandardPrompt::custom(tl!("This script has added a great many objects. Continue, or stop it and undo what it did?"))
|
||||
@@ -611,12 +762,29 @@ pub(crate) fn pump(app: &mut VectorcraftApp, _ctx: &egui::Context) {
|
||||
}
|
||||
if let Some(DialogResult::Ok(mut answer)) = run
|
||||
&& answer.choice == PromptChoice::Proceed
|
||||
&& let Some(RunWarning { params, scope, automated }) = answer.take_tag::<RunWarning>()
|
||||
&& let Some(RunWarning { params, reaches: listed, scope, automated }) = answer.take_tag::<RunWarning>()
|
||||
{
|
||||
let stored = if answer.skip { app.run("prefs.set", json!({"key": "showExternalScriptWarning", "value": false})).map(drop) } else { Ok(()) };
|
||||
let run = |app: &mut VectorcraftApp| crate::script_runs::run_chosen(app, params).map(drop);
|
||||
let automated = automated || app.automation_asked();
|
||||
if let Err(e) = stored.and_then(|()| scope.within_current().run(|| file_asks::as_automated(app, automated, run))) {
|
||||
// A script whose report changed while the warning was open is listed again before it runs.
|
||||
// A script read when the warning opened that the answering request can't read is
|
||||
// refused with the check's error, not listed again as changed.
|
||||
// The check reads the script under the access the run would have.
|
||||
let ran = match scope.clone().within_current().run(|| checked(app, ¶ms)) {
|
||||
Err(e) if !listed.is_null() => Err(e),
|
||||
now => Ok(now.unwrap_or(Value::Null)),
|
||||
}
|
||||
.and_then(|now| {
|
||||
if now == listed {
|
||||
let stored =
|
||||
if answer.skip { app.run("prefs.set", json!({"key": "showExternalScriptWarning", "value": false})).map(drop) } else { Ok(()) };
|
||||
let run = |app: &mut VectorcraftApp| crate::script_runs::run_chosen(app, params).map(drop);
|
||||
let automated = automated || app.automation_asked();
|
||||
stored.and_then(|()| scope.within_current().run(|| file_asks::as_automated(app, automated, run)))
|
||||
} else {
|
||||
app.status(CHANGED_SINCE_WARNING);
|
||||
warn(app, params, now, scope, automated).map(drop)
|
||||
}
|
||||
});
|
||||
if let Err(e) = ran {
|
||||
app.status(e);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2071,7 +2071,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
|
||||
"ui.runScript",
|
||||
"Other Script…",
|
||||
"Cmd+F12",
|
||||
"{path? | source?, name?} run a .js or .jsx file (script.run), after the warning unless Preferences › General › Show External Script Warning is off (dialog `scriptRun`: `name`, `script`, `dontShow`); without a file pick one (the web opens the browser's file picker); with Preferences › General › Run Startup Scripts on, the startup scripts run first (script.startup.run) and script.run's reply also holds `startup`, script.startup.run's reply; while a startup script runs before it the reply is {running: true, queued: true}, and a later failure to start shows in the status bar",
|
||||
"{path? | source?, name?} run a .js or .jsx file (script.run), after the warning unless Preferences › General › Show External Script Warning is off (dialog `scriptRun`: `choice`, `skip`, and `reaches`, which ui.dialog.set cannot set: the `kind`, `needs`, `outside`, `includes` and `truncated` of script.check's report on the script, which the warning lists, or null when the check failed); without a file pick one (the web opens the browser's file picker); with Preferences › General › Run Startup Scripts on, the startup scripts run first (script.startup.run) and script.run's reply also holds `startup`, script.startup.run's reply; while a startup script runs before it the reply is {running: true, queued: true}, and a later failure to start shows in the status bar",
|
||||
),
|
||||
(
|
||||
crate::scripts_menu::COMMAND,
|
||||
|
||||
@@ -9,7 +9,8 @@ use vectorcraft_engine::cmd::scripts::TOO_LARGE;
|
||||
use vectorcraft_engine::script::MAX_SOURCE_BYTES;
|
||||
use vectorcraft_engine::script::folder::Clock;
|
||||
|
||||
use super::script_dialogs::{cancel, confirm, frame, is_open, key, open_id, pump, set};
|
||||
use super::script_dialogs::{cancel, confirm, fields, frame, is_open, key, open_id, pump, set};
|
||||
use crate::dialogs::script_check;
|
||||
use crate::dialogs::script_run::{
|
||||
self, BY_PERSON, CLOSE_KIND, FilesAnswer, GROWTH_KIND, GrowthQuestion, KIND, PICKER_KIND, RunQuestion, ScriptFiles,
|
||||
};
|
||||
@@ -612,6 +613,187 @@ fn a_scripts_file_dialog_keeps_at_most_2048_picked_files() {
|
||||
finish(&mut app);
|
||||
}
|
||||
|
||||
/// The texts the open warning draws, after a few frames of the whole app.
|
||||
fn dialog_texts(app: &mut VectorcraftApp) -> Vec<String> {
|
||||
fn texts(s: &egui::Shape, out: &mut Vec<String>) {
|
||||
match s {
|
||||
egui::Shape::Text(t) => out.push(t.galley.text().to_string()),
|
||||
egui::Shape::Vec(v) => v.iter().for_each(|s| texts(s, out)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let ctx = app.ui_ctx.clone().unwrap();
|
||||
let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1600.0, 4000.0));
|
||||
let mut out = None;
|
||||
for i in 0..4 {
|
||||
let raw = egui::RawInput { time: Some(0.1 * f64::from(i)), screen_rect: Some(screen), ..Default::default() };
|
||||
out = Some(crate::testing::app_frame(app, &ctx, raw));
|
||||
}
|
||||
let mut v = vec![];
|
||||
out.unwrap().shapes.iter().for_each(|c| texts(&c.shape, &mut v));
|
||||
v
|
||||
}
|
||||
|
||||
/// The warning before a run lists the files the script writes, read without running it.
|
||||
#[test]
|
||||
fn the_warning_lists_the_files_a_script_writes() {
|
||||
let mut app = app();
|
||||
let source = "var f = new File(Folder.temp + '/out.txt');\nf.open('w');\nf.write('x');\nf.close();\n";
|
||||
menus::run_ui_command(&mut app, "ui.runScript", &json!({"source": source, "name": "write.js"})).unwrap().unwrap();
|
||||
assert!(!app.session.script_running());
|
||||
let texts = dialog_texts(&mut app);
|
||||
let writes = script_check::outside_label("filesWritten").unwrap();
|
||||
assert!(texts.iter().any(|t| t.starts_with(writes) && t.contains("(w)")), "{texts:?}");
|
||||
assert!(texts.iter().any(|t| t == script_check::need_label("files").unwrap()), "{texts:?}");
|
||||
assert!(texts.iter().any(|t| t == "Outside the document:"), "{texts:?}");
|
||||
// The warning lists the report as `reaches`, which `ui.dialog.set` cannot change.
|
||||
assert_eq!(fields(&app, KIND)["reaches"]["outside"][0]["id"], "filesWritten");
|
||||
assert!(set(&app, KIND, "reaches", json!(null)).is_err());
|
||||
assert_eq!(fields(&app, KIND)["reaches"]["outside"][0]["id"], "filesWritten");
|
||||
cancel(&mut app, KIND);
|
||||
finish(&mut app);
|
||||
}
|
||||
|
||||
/// A script that reaches nothing outside the document gets the warning with nothing more.
|
||||
#[test]
|
||||
fn the_warning_for_a_script_that_reaches_nothing_lists_nothing_more() {
|
||||
let mut app = app();
|
||||
menus::run_ui_command(&mut app, "ui.runScript", &json!({"source": DRAW, "name": "draw.js"})).unwrap().unwrap();
|
||||
let texts = dialog_texts(&mut app);
|
||||
assert!(texts.iter().any(|t| t.starts_with("A script can change the open documents")), "{texts:?}");
|
||||
for heading in ["Outside the document:", "Includes:", "VectorCraft read this script without running it."] {
|
||||
assert!(!texts.iter().any(|t| t == heading), "{heading}: {texts:?}");
|
||||
}
|
||||
assert!(confirm(&mut app, KIND));
|
||||
finish(&mut app);
|
||||
assert_eq!(objects(&app), 2);
|
||||
}
|
||||
|
||||
/// A script file's warning also lists what the files its `#include` lines name reach.
|
||||
#[test]
|
||||
fn the_warning_lists_what_a_scripts_included_files_reach() {
|
||||
let mut app = app();
|
||||
let dir = folder("includes");
|
||||
std::fs::create_dir_all(dir.join("lib")).unwrap();
|
||||
std::fs::write(dir.join("main.jsx"), "#include 'lib/net.jsxinc'\n").unwrap();
|
||||
std::fs::write(dir.join("lib/net.jsxinc"), "var s = new Socket();\n").unwrap();
|
||||
menus::run_ui_command(&mut app, "ui.runScript", &json!({"path": dir.join("main.jsx").to_string_lossy()})).unwrap().unwrap();
|
||||
let texts = dialog_texts(&mut app);
|
||||
assert!(texts.iter().any(|t| t.starts_with("lib/net.jsxinc · ")), "{texts:?}");
|
||||
assert!(texts.iter().any(|t| t == "Includes:"), "{texts:?}");
|
||||
assert!(texts.iter().any(|t| t == script_check::need_label("hostOnly").unwrap()), "{texts:?}");
|
||||
cancel(&mut app, KIND);
|
||||
finish(&mut app);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A script that opens a dialog and reaches nothing outside the document lists the need without the
|
||||
/// outside-the-document heading.
|
||||
#[test]
|
||||
fn the_warning_lists_a_need_without_the_outside_heading() {
|
||||
let mut app = app();
|
||||
let source = "var w = new Window('dialog', 'Title');";
|
||||
menus::run_ui_command(&mut app, "ui.runScript", &json!({"source": source, "name": "dialog.js"})).unwrap().unwrap();
|
||||
assert_eq!(fields(&app, KIND)["reaches"]["outside"], json!([]));
|
||||
let texts = dialog_texts(&mut app);
|
||||
assert!(texts.iter().any(|t| t == script_check::need_label("dialogs").unwrap()), "{texts:?}");
|
||||
assert!(!texts.iter().any(|t| t == "Outside the document:"), "{texts:?}");
|
||||
cancel(&mut app, KIND);
|
||||
finish(&mut app);
|
||||
}
|
||||
|
||||
/// A script file that changes what it reaches while its warning is open does not run on Run: the
|
||||
/// warning opens again with the new report, and the next Run runs it.
|
||||
#[test]
|
||||
fn run_lists_a_script_again_when_it_changed_after_its_warning_opened() {
|
||||
let mut app = app();
|
||||
let dir = folder("changed");
|
||||
let path = dir.join("changed.jsx");
|
||||
std::fs::write(&path, DRAW).unwrap();
|
||||
menus::run_ui_command(&mut app, "ui.runScript", &json!({"path": path.to_string_lossy()})).unwrap().unwrap();
|
||||
assert_eq!(fields(&app, KIND)["reaches"]["outside"], json!([]));
|
||||
std::fs::write(&path, format!("{DRAW}\nvar s = new Socket();\n")).unwrap();
|
||||
assert!(confirm(&mut app, KIND));
|
||||
assert!(!app.session.script_running());
|
||||
assert!(is_open::<RunQuestion>(&app));
|
||||
assert_eq!(app.ui.status, script_run::CHANGED_SINCE_WARNING);
|
||||
assert_eq!(fields(&app, KIND)["reaches"]["outside"][0]["id"], "network");
|
||||
assert!(confirm(&mut app, KIND));
|
||||
assert!(app.session.script_running());
|
||||
finish(&mut app);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A script with more includes than the warning lists gives the count of the rest.
|
||||
#[test]
|
||||
fn the_warning_counts_the_includes_it_does_not_list() {
|
||||
let mut app = app();
|
||||
let dir = folder("many-includes");
|
||||
let names: Vec<String> = (0..script_run::SHOWN_INCLUDES + 3).map(|n| format!("i{n}.jsxinc")).collect();
|
||||
for name in &names {
|
||||
std::fs::write(dir.join(name), "var x = 1;\n").unwrap();
|
||||
}
|
||||
let main: String = names.iter().map(|n| format!("#include '{n}'\n")).collect();
|
||||
std::fs::write(dir.join("main.jsx"), main).unwrap();
|
||||
menus::run_ui_command(&mut app, "ui.runScript", &json!({"path": dir.join("main.jsx").to_string_lossy()})).unwrap().unwrap();
|
||||
let texts = dialog_texts(&mut app);
|
||||
let listed = |name: &str| texts.iter().any(|t| t.starts_with(&format!("{name} · ")));
|
||||
assert!(listed(&names[script_run::SHOWN_INCLUDES - 1]), "{texts:?}");
|
||||
assert!(!listed(&names[script_run::SHOWN_INCLUDES]), "{texts:?}");
|
||||
assert!(texts.iter().any(|t| t == "Included files not listed: 3"), "{texts:?}");
|
||||
assert_eq!(fields(&app, KIND)["reaches"]["includes"].as_array().map(Vec::len), Some(names.len()));
|
||||
cancel(&mut app, KIND);
|
||||
finish(&mut app);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A script the checker could not read as a script gets a warning that says so, not the warning of
|
||||
/// a script that was checked and reaches nothing.
|
||||
#[test]
|
||||
fn the_warning_says_when_a_script_was_not_checked() {
|
||||
let missing = std::env::temp_dir().join(format!("vc-script-run-ui-missing-{}.js", std::process::id()));
|
||||
for (params, text) in [
|
||||
(json!({"source": "export const b = 2;", "name": "module.js"}), "Not a script for the reference app"),
|
||||
(json!({"source": "var a = 1;\u{0}", "name": "binary.js"}), "Not a script for the reference app"),
|
||||
(json!({"source": "@JSXBIN@ES@2.0@MyBbyBn0ABJAnA", "name": "compiled.js"}), "Compiled script: ask its author for the .jsx file"),
|
||||
(json!({"path": missing.to_string_lossy()}), "Not read"),
|
||||
] {
|
||||
let mut app = app();
|
||||
menus::run_ui_command(&mut app, "ui.runScript", ¶ms).unwrap().unwrap();
|
||||
let texts = dialog_texts(&mut app);
|
||||
assert!(texts.iter().any(|t| t == text), "{params}: {texts:?}");
|
||||
cancel(&mut app, KIND);
|
||||
finish(&mut app);
|
||||
}
|
||||
}
|
||||
|
||||
/// A script whose report was cut short at a list's limit says so, also when nothing else is listed.
|
||||
#[test]
|
||||
fn the_warning_says_when_a_list_was_cut_short() {
|
||||
let mut app = app();
|
||||
let source: String = (0..=1000).map(|n| format!("x = app.m{n};\n")).collect();
|
||||
menus::run_ui_command(&mut app, "ui.runScript", &json!({"source": source, "name": "many.js"})).unwrap().unwrap();
|
||||
let texts = dialog_texts(&mut app);
|
||||
assert!(texts.iter().any(|t| t == "Some lists were cut short at their limit."), "{texts:?}");
|
||||
cancel(&mut app, KIND);
|
||||
finish(&mut app);
|
||||
}
|
||||
|
||||
/// A script over the checker's size limit gets a warning that says it was too large to check.
|
||||
#[test]
|
||||
fn the_warning_says_when_a_script_is_too_large_to_check() {
|
||||
let mut app = app();
|
||||
let dir = folder("large");
|
||||
let path = dir.join("large.js");
|
||||
std::fs::write(&path, vec![b' '; MAX_SOURCE_BYTES + 1]).unwrap();
|
||||
menus::run_ui_command(&mut app, "ui.runScript", &json!({"path": path.to_string_lossy()})).unwrap().unwrap();
|
||||
let texts = dialog_texts(&mut app);
|
||||
assert!(texts.iter().any(|t| t == "Too large to check"), "{texts:?}");
|
||||
cancel(&mut app, KIND);
|
||||
finish(&mut app);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_script_sees_the_window_and_sets_its_zoom_centre_and_screen_mode() {
|
||||
let mut app = app();
|
||||
|
||||
+10
-1
@@ -2742,7 +2742,16 @@ shares the key's existing string buffer.
|
||||
Block-scoped declaration checks retain one copy of each `var` declaration name through nested blocks.
|
||||
File › Scripts › Other Script… (Cmd+F12) picks a `.js` or `.jsx` file and runs it the same way; the help page
|
||||
https://helpx.adobe.com/illustrator/desktop/automate-visualize-data/automate-actions/install-and-run-scripts.html
|
||||
describes that menu item. Pass exactly one of `path` and `source`. A `path` must end in `.js` or `.jsx`, in any
|
||||
describes that menu item. Its warning before the run lists what `script.check` finds the script reaches outside
|
||||
the document, read without running it: each `outside` category of the report (files it writes, moves or deletes,
|
||||
files it opens in other apps, messages to other apps, the network, native code, environment variables, the reference
|
||||
app's preferences and code the checker can't read), the files and dialogs it needs, features only the reference app
|
||||
has, and the files its `#include` lines name (the first 20, then the count of the rest; VectorCraft's own limit). It
|
||||
says when the script is too large to check, compiled or not a script, when the check failed, and when a list was cut
|
||||
short at its limit. The listing does not stop the run. Run checks the script again, and when the report has changed
|
||||
since the warning opened, nothing runs and the warning opens again with the new report. A script from the Scripts
|
||||
folder runs without the warning.
|
||||
Pass exactly one of `path` and `source`. A `path` must end in `.js` or `.jsx`, in any
|
||||
case. A `.jsxbin` file or text that starts with `@JSXBIN@` is compiled and ends with an error, as does text that is
|
||||
not UTF-8. The language is ES5.1, except that identifiers take the characters Unicode's `ID_Start` and
|
||||
`ID_Continue` properties allow, as later editions define them, and may use `\u{...}` escapes. A `path` that ends in
|
||||
|
||||
@@ -1118,6 +1118,7 @@ Moved from the ROADMAP's "Shipped so far" on 2026-10-10. Update it when a featur
|
||||
- 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: 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`.
|
||||
- Scripts: the `$` object has the other members the Dollar object page lists (https://extendscript.docsforadobe.dev/extendscript-tools-features/dollar-object/), from `$.about()` to `$.version`, and scripts have the global `localize(object, ...values)` (https://extendscript.docsforadobe.dev/extendscript-tools-features/localizing-extendscript-strings/), `toSource(value)` and `Object.prototype.toSource()`. Each run starts with the interface's locale, and what a script changes in `$` lasts only for that run. `crates/engine/src/tests/script_dollar.rs`, `crates/js/src/extension_tests.rs`.
|
||||
- Scripts: `toSource` throws a `TypeError` for a property that is not writable or not configurable, a sealed, frozen or non-extensible object or array, and an array with a read-only `length` (VectorCraft's own rule). `crates/js/src/extension_tests.rs`.
|
||||
- Scripts: `UnitValue` measurements ([the help page](https://extendscript.docsforadobe.dev/extendscript-tools-features/specifying-measurement-values/)): the constructor with a number and a unit, with text such as `12 pt`, or with another `UnitValue`; the length units, `px` and `%` by abbreviation, singular or plural; `value`, `type` and `baseUnit` on the class and on each object; `as` and `convert`; and the arithmetic, comparison and unary operators with a number or another `UnitValue`, the right one converted to the left one's unit, with `>` and `>=` as the negations of `<=` and `<`. Realms without `UnitValue` keep the standard operators. VectorCraft's own rules: an invalid object has `type` `?` and value 0, and converting it or using it with these operators, a result that is not finite (a division by 0 included), a comparison with a number that is not finite and a base that is not a length greater than 0 throw. `crates/js/src/unit_value_tests.rs`, `crates/engine/src/tests/script_dollar.rs`.
|
||||
|
||||
Reference in new issue
Block a user